diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 19c076242f8..5e56ac2a1fc 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -101,28 +101,30 @@ Long description (Can span accross multiple lines). ### Pull Requests -When submitting a pull request, use same rule as [Commits](#commits) for the message. +Pull Request (PR) process is the process to submit a change (enhancement, bug fix, ...) into the code of the project. There is some rules to know and +a process to follow to optimize the chance to have PRs merged efficiently... -If your pull request only contains one commit, GitHub will be smart enough to fill it for you. +When submitting a pull request, use same rule as [Commits](#commits) for the message. +If your pull request only contains 1 commit, GitHub will be smart enough to fill it for you. Otherwise, please be a bit verbose about what you're providing. -Your Pull Request (PR) must pass the Continuous Integration checks. +Your Pull Request (PR) must pass the Continuous Integration checks and code quality checks. Also, some code changes need a prior approbation: * if you want to include a new external library (into htdocs/includes directory), please ask before to the project manager (@eldy) to see if such a library can be accepted. -* if you add a new table, you must first create a page on http://wiki.dolibarr.org/index.php/Category:Table_SQL (copy an existing page changing its name to see it into this index page). Than ask the project manager (@eldy) if the new data model you plan to add can be accepted as you suggest. +* if you add a new table, you must first create a page on https://wiki.dolibarr.org/index.php/Category:Table_SQL (copy an existing page changing its name to see it into this index page). Then ask the project manager (@eldy) if the new data model you plan to add is compatible with curent and future works in progress and can be accepted as you suggest. -Once a PR has been submitted, you may need to wait for its integration. It is common that the project leader let the PR open for a long delay to allow every developer discuss about the PR. +Once a PR has been submitted, you may need to wait for its integration. It is common that the project leader let the PR open for a long delay to allow every developer discuss about the PR (A label is added in such a case). If the label of PR start with "WIP" (Work In Progress), it will not be analyzed (until you change the label of PR). If your PR has errors reported by the Continuous Integration Platform, it means your PR is not valid and nothing will be done with it. It will be kept open to allow developers to fix this, or it may be closed several month later. Don't expect anything on your PR if you have such errors, you MUST first fix the Continuous Integration error to have it taken into consideration. If the PR is valid, and is kept open for a long time, a tag will also be added on the PR to describe the status of your PR and why the PR is kept open. By putting your mouse on the tag, you will get a full explanation of the tag/status that explain why your PR has not been integrated yet. -In most cases, it gives you information of things you have to do to have the PR taken into consideration (for example a change is requested, a conflict is expected to be solved, some questions were asked). If you have a yellow, red flag of purple flag, don't expect to have your PR validated. You must first provide the answer the flag ask you. The majority of PR are waiting an action of the developer/author. +In most cases, it gives you information of things you have to do to have the PR taken into consideration (for example a change is requested, a conflict is expected to be solved, some questions were asked). If you have a yellow, red flag of purple flag, don't expect to have your PR validated. You must first provide the answer the tag ask you. The majority of open PR are waiting an action of the author of the PR. -Statistics on Dolibarr project shows that around 95% of submitted PR are reviewed and tagged. This is one of the most important ratio of answered PR in Open Source world. Don't expect the core team to reach the 100%. With the increasing popularity of Dolibarr, this ratio will probably decrease in future. +Statistics on Dolibarr project shows that around 95% of submitted PR are reviewed and tagged. Average answer delay is also one of the best among Open source project (just few days before having the Answer Tag set). This is one of the most important ratio of answered PR in Open Source world for a major project. Don't expect the core team to reach the 100%. A so high ratio is very rare on a so popular project and with the increasing popularity of Dolibarr, this ratio will probably decrease in future to a more common level. ### Resources diff --git a/.github/workflows/greetings-pr.yml.disabled b/.github/workflows/greetings-pr.yml.disabled new file mode 100644 index 00000000000..2a930929a6d --- /dev/null +++ b/.github/workflows/greetings-pr.yml.disabled @@ -0,0 +1,13 @@ +# See syntax file on https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions +name: Greetings PR + +on: [pull_request] + +jobs: + greeting: + runs-on: ubuntu-latest + steps: + - uses: actions/first-interaction@v1 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + pr-message: 'Welcome to the Dolibarr army. You are on the road to become an Admiral (see https://wiki.dolibarr.org/index.php/Dolibarr_Project)' diff --git a/.github/workflows/stale-issues-safe.yml b/.github/workflows/stale-issues-safe.yml new file mode 100644 index 00000000000..55599654707 --- /dev/null +++ b/.github/workflows/stale-issues-safe.yml @@ -0,0 +1,24 @@ +# See syntax file on https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions +name: "Close stale issues (bugs and feature requests)" + +on: + schedule: + - cron: "0 21 * * *" + issue_comment: + types: [created] + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: Dolibarr/stale@staleunstale + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-message: 'This issue is stale because it has been open 1 year with no activity. If this is a bug, please comment to confirm it is still present on latest stable version. if this is a feature request, please comment to notify the request is still relevant and not yet covered by latest stable version. This issue may be closed automatically by stale bot in 15 days (you should still be able to re-open it if required).' + stale-label: 'Issue Stale (automatic label)' + exempt-labels: 'Priority High / Blocking,Priority Top Strategic,Priority Medium,Hacktoberfest,good first issue,Bug Security (CVE)' + days-before-stale: 365 + days-before-close: 15 + operations-per-run: 100 + dry-run: false + \ No newline at end of file diff --git a/.github/workflows/stale-issues.yml.disabled b/.github/workflows/stale-issues.yml.disabled new file mode 100644 index 00000000000..6e7dad5dc9b --- /dev/null +++ b/.github/workflows/stale-issues.yml.disabled @@ -0,0 +1,25 @@ +# See syntax file on https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions +name: "Close stale issues (bugs and feature requests)" + +on: + schedule: + - cron: "0 20 * * *" + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: Dolibarr/stale@master + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'This issue is stale because it has been open 1 year with no activity. If this is a bug, please comment to confirm it is still present on latest stable version. if this is a feature request, please comment to notify the request is still relevant and not yet covered by latest stable version. This issue may be closed automatically by stale bot in 15 days (you should still be able to re-open it if required).' + stale-issue-label: 'Issue Stale (automatic label)' + exempt-issue-label: 'Priority High / Blocking' + days-before-stale: 365 + days-before-close: -1 + operations-per-run: 100 + #stale-pr-message: 'This PR is stale because it has been open 1 year with no activity. If this PR is still mergeable (no conflict, nor Continuous Integration errors), please comment to confirm this merge is still expected. Without comment, this issue will be closed automatically by stale bot in 15 days.' + stale-pr-label: 'PR Stale (automatic label)' + stale-pr-message: + exempt-pr-label: 'Priority Top Strategic' + \ No newline at end of file diff --git a/.gitignore b/.gitignore index ffacba65feb..30151359365 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,4 @@ htdocs/includes/sebastian/ htdocs/includes/squizlabs/ htdocs/includes/symfony/ htdocs/includes/webmozart/ +htdocs/.well-known/apple-developer-merchantid-domain-association diff --git a/.travis.yml b/.travis.yml index dd3322e5cf7..613d2fa2420 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,7 @@ # For syntax, see http://about.travis-ci.org/docs/user/languages/php/ # We use dist: xenial to have php 5.6+ available +os: linux dist: xenial sudo: required @@ -43,7 +44,7 @@ env: global: # Set to true for very verbose output - DEBUG=false - matrix: + jobs: # MariaDB overrides MySQL installation so it's not possible to test both yet #- DB=mariadb - DB=mysql @@ -53,7 +54,7 @@ env: # See https://github.com/DracoBlue/travis-ci-nginx-php-fpm-test #- WS=nginx -matrix: +jobs: fast_finish: true allow_failures: - php: nightly diff --git a/COPYRIGHT b/COPYRIGHT index fe707c1d63d..c1f400aff4e 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -17,7 +17,7 @@ CKEditor 4.12.1 LGPL-2.1+ Yes EvalMath 1.0 BSD Yes Safe math expressions evaluation Escpos-php 2.2 MIT License Yes Thermal receipt printer library, for use with ESC/POS compatible printers GeoIP 1.4 LGPL-2.1+ Yes Sample code to make geoip convert (not into deb package) -Mobiledetect 2.8.33 MIT License Yes Detect mobile devices browsers +Mobiledetect 2.8.34 MIT License Yes Detect mobile devices browsers NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package) PEAR Mail_MIME 1.8.9 BSD Yes NuSoap dependency ParseDown 1.6 MIT License Yes Markdown parser @@ -32,15 +32,16 @@ PSR/simple-cache ? Library for cache (used by PHPSp Restler 3.0.0RC6 LGPL-3+ Yes Library to develop REST Web services (+ swagger-ui js lib into dir explorer) Sabre 3.2.2 BSD Yes DAV support Swift Mailer 5.4.2-DEV MIT license Yes Comprehensive mailing tools for PHP -Stripe 6.41 MIT licence Yes Library for Stripe module +Stripe 6.43.1 MIT licence Yes Library for Stripe module TCPDF 6.3.2 LGPL-3+ Yes PDF generation TCPDI 1.0.0 LGPL-3+ / Apache 2.0 Yes FPDI replacement JS libraries: -Ace 1.4.6 BSD Yes JS library to get code syntaxique coloration in a textarea. +Ace 1.4.8 BSD Yes JS library to get code syntaxique coloration in a textarea. +Chart 2.9.3 MIT License Yes JS library for graph jQuery 3.4.1 MIT License Yes JS library jQuery UI 1.12.1 GPL and MIT License Yes JS library plugin UI -jQuery select2 4.0.5 GPL and Apache License Yes JS library plugin for sexier multiselect +jQuery select2 4.0.13 GPL and Apache License Yes JS library plugin for sexier multiselect jQuery blockUI 2.70.0 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors jQuery Flot 0.8.3 MIT License Yes JS library to build graph diff --git a/ChangeLog b/ChangeLog index 83c1adfe3d8..7089658872e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -5,19 +5,195 @@ English Dolibarr ChangeLog ***** ChangeLog for 12.0.0 compared to 11.0.0 ***** For Users: - +NEW: Module MO (Manufacturing Order) is available as stable module. For Developers or integrators: - +* A new way to navigate between pages in list is available. To use it, you must + - replace $page = GETPOST('page', 'int') with $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); + - remove input field in form '';' + - add parameter $pagenavastextinput to value 1 when calling print_barre_liste WARNING: Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: * PHP 5.5 is no more supported. Minimum PHP is now 5.6+. +* Default mode for GETPOST function is now 'alphanohtml' instead of 'none'. So check when you make POST or GET requests + with HTML content that you make a GETPOST('myparam', 'restricthtml') or GETPOST('myparam', 'none') if you really need posted content without sanitizing + the HTML into content (in such a case, sanitize data later) +* Removed hidden constant MAIN_EXTRAFIELDS_IN_ONE_TD that was useless. +* Reference of object including a "/" are no more allowed. It is never used by default but to support setup that introduced it, the "/" will be replaced + by a "_" automatically when a reference (with a custom numbering mask that use it) is generated. + + + +***** ChangeLog for 11.0.3 compared to 11.0.2 ***** +FIX: unit price for selected supplier products not set. NaN was used. +FIX: use bad var to check if total is positive for each VAT rate when validating an invoice +FIX: status missing from last customer invoices box when using MAIN_STATUS_USES_CSS +FIX: translations for "orders" not loaded in the homepage box +FIX: #13194 +FIX: #13274 cannot add or update 0 value for an int or double extrafield +FIX: #13285 SQL error during migration with pgsql +FIX: #13294 +FIX: #13313 +FIX: Clone Fourn Command, add line's extrafields +FIX: cols parameter not propagated to tpl +FIX: CSRF error when creating an intervention +FIX: date order was -1D and desc with label repetition +FIX: empty of series in graph of product distribution +FIX: fk_type subscription list via api REST +FIX: link when using anchor on "/" in website module +FIX: menu export document was not visible when using "simple accounting" +FIX: missing class declaration +FIX: missing global $conf +FIX: Missing token in some forms (avoid unset POST errors) +FIX: params of setEventMessage($langs->trans('ErrorProductClone')... +FIX: Remove unexisting link +FIX: mass action on stock movements +FIX: substitute lines dates values on doc generator (ODT, ...) +FIX: Ticket - Load Cache Messages Ticket, wrong message's status +FIX: Ticket Public - Private messages are displayed +FIX: wrong include - replace extrafields_create.tpl.php to extrafields_add.tpl.php + +***** ChangeLog for 11.0.2 compared to 11.0.1 ***** +FIX: #10309 +FIX: #13110 +FIX: #13118 +FIX: #13124 +FIX: #13131 +FIX: #13135 +FIX: #13146 +FIX: #13198 +FIX: #13175 +FIX: #13182 +FIX: #13183 +FIX: #13184 +FIX: #13263 +FIX: #13267 +FIX: an external user can not approve +FIX: API Get list of documents for supplier_invoice +FIX: API to push an expense report +FIX: API upload/download doc for expensereport +FIX: Avoid to download the export if we just press enter to refresh form +FIX: Bad link to template invoices +FIX: Bad sort link in accounting report +FIX: Bad translation for productlot EatBy and SellBy +FIX: better method to check user rights AND usergroup rights ! +FIX: CA by product list filter +FIX: CSS +FIX: Disable js if no javascript +FIX: duplicate class name into some log lines +FIX: etrafield with visibilty=5 were not in read only. +FIX: excess paid from situation invoices not counted when calculating remain to pay. +FIX: Force FEC export to txt format. +FIX: Free input for email no more visible. +FIX: Keep assigned users in session when loading projects and tasks +FIX: List of viewed projects too large in task widget. +FIX: Menu truncated. Add tooltip to have all content. +FIX: Missing field "billed" in export. +FIX: missing "statut" for getNomUrl() function +FIX: modFournisseur is required by modSupplierProposal +FIX: Multicompany compatibility +FIX: must be == and not = +FIX: option for topbar search and bookmarks +FIX: option MAIN_OPTIMIZEFORTEXTBROWSER +FIX: some responsive troubles +FIX: round MT in accountancy books +FIX: search with '0' +FIX: sort link +FIX: SQL Overload in default contact trigger. +FIX: SQl syntax error. +FIX: Submit of documents for supplier invoices. +FIX: timezone must be tzserver and not tzuser as on contract card +FIX: token in barcode tools page missing +FIX: Bad name of trigger PROPAL_SUPPLIER_TRIGGER, should be PROPOSAL_SUPPLIER_TRIGGER +FIX: Type of contact for event does not exists and not supported +FIX: Type of contact not saved when creating a contact +FIX: typo on ckeck method +FIX: undefined function measuringUnitString in product list +FIX: Usage of project not available in export. +FIX: wrong test +FIX: z-index for moretabsList with constant MAIN_MAXTABS_IN_CARD +FIX: Use GETPOST instead of POST +FIX: HTML Injection +FIX: Visualization rights correction on last modified contacts box. +FIX: Vulnerability in module from modulebuilder. +FIX: Vulnerability reported by code16 + +***** ChangeLog for 11.0.1 compared to 11.0.0 ***** +FIX: advanced target emailing sql and ergonomy. +FIX: After import of a website template, home page was not set. +FIX: Avoid deletion of bank record if in accounting +FIX: compatibility with multicompany (avoid duplicate data) +FIX: Confusion between 'bank reconciled' and 'accounted'. Show both data. +FIX: Count of Stripe payment mode must take test/live into account +FIX: Creation of Stripe card from backoffice must return a clean message +FIX: CVE-2019–17223 +FIX: CVE-2019–17223 +FIX: CVE-2020-7994 +FIX: CVE Need permission to be able to develop modules +FIX: #13053 +FIX: Disable ticket status change if ticket closed +FIX: doc of dictionnary API +FIX: expedition ceate line new parameter is not required. +FIX: export ledger +FIX: FEC export have specific name +FIX: Filenames must not contains non ascii char or we will get non ascii +FIX: Filter on list of events were lost after "Back to list" +FIX: hasDelay for retained warranty +FIX: If we can change vendor status, we must be able to chane vendor code +FIX: links in products/services index +FIX: Log of authentication ok or ko + CVE-2020-7996 +FIX: Look and feel v11 +FIX: Mail smtps truncated if content has a line with single . +FIX: missing hook parameter +FIX: Missing include +FIX: need weight short label in shipping doc +FIX: Picture of contact not visible in tooltip +FIX: Problem with column label in subscription list +FIX: ref_client not visible in tooltip. +FIX: search filter on extrafields were not restored after "Back to list" +FIX: situation invoice: allow excess paid to be converted to discount +FIX: situation invoice: bad amount for previous payments because of local variable overwriting a more global one +FIX: situation invoice: can't convert excess received to discount & bad previous payment amount +FIX: SQL request and phpunit +FIX: Update export_files.php +FIX: Use ref into label of ticket message +FIX: use "usergroup" instead of "user" +FIX: Warning on admin/export_files +FIX: #10203 +FIX: default filtering for 'select' extrafields should use "=", not "LIKE" +FIX: #11975 When a product is split between multiple pages in a document, prices/quantity/etc appear on the last relevant page +FIX: #12760 #12763 #12755 #12765 #12751 +FIX: #12874 +FIX: #12892 +FIX: #12908 User login with credentials from self-subscription form fails +FIX: #12932 +FIX: #12966 +FIX: #12973 +FIX: #12974 +FIX: #12975 +FIX: #12978 +FIX: #12986 +FIX: #12991 +FIX: #12992 +FIX: #12995 +FIX: #13018 Extrafields Supplier invoice +FIX: #13019 +FIX: #13022 +FIX: #13028 +FIX: #13038 ExpenseReport PDF - custom category description is not correct +FIX: #13046 More complete +FIX: #13048 +FIX: #13050 +FIX: #13077 Replace left join with inner join (left join was useless) +FIX: #13085 +FIX: #13094 +FIX: #13096 +FIX: #13100 + - - ***** ChangeLog for 11.0.0 compared to 10.0.0 ***** For Users: diff --git a/README-FR.md b/README-FR.md index 94af10cb04f..bccb7b0143b 100644 --- a/README-FR.md +++ b/README-FR.md @@ -151,6 +151,7 @@ La documentation utilisateur, développeur et traducteur est disponible sous for ## CONTRIBUER 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 085ab808488..b8d067ffb7a 100644 --- a/README.md +++ b/README.md @@ -170,7 +170,8 @@ Administrator, user, developer and translator's documentations are available alo ## CONTRIBUTING -This project exists thanks to all the people who contribute. [[Contribute](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md)]. +This project exists thanks to all the people who contribute. [[Contribute](https://github.com/Dolibarr/dolibarr/blob/develop/.github/CONTRIBUTING.md)] + ## CREDITS diff --git a/build/README b/build/README index 07f0ebe3b55..67ceb05c8d2 100644 --- a/build/README +++ b/build/README @@ -45,9 +45,12 @@ Dolibarr working. It is here only to build Dolibarr packages, and those generated packages will not contains this "build" directory. -We can find in "build", following sub-directories: +You can find in "build", following sub-directories: -* debian: +* composer +To test an upgrade of a lib. + +* debian To build Debian package. * dmg: diff --git a/build/obs/README b/build/obs/README index c8a29e1dac4..44427c01d49 100644 --- a/build/obs/README +++ b/build/obs/README @@ -1,20 +1,24 @@ README (English) ################################################## OBS Package tools +OBE - openSUSE Build Service ################################################## -This directory contains files to explain how to publish -a package onto OBS +This directory contains an instruction to explain +how to publish a package onto OBS. -# Create a project onto OBS -#---------------------------------- -https://build.opensuse.org +# Create a project onto OBS +--------------------------- +https://build.opensuse.org -Packaging rules: http://en.opensuse.org/Portal:Packaging + +# Packaging rules: +------------------ +https://en.opensuse.org/Portal:Packaging Add attributes: -OBS:Screenshots URL of screenshot http://www.dolibarr.org/images/dolibarr_screenshot1.png +OBS:Screenshots URL of screenshot https://www.dolibarr.org/images/dolibarr_screenshot1.png OBS:QualityCategory Development|Testing|Stable|Private OBS:Maintained 1 @@ -28,22 +32,24 @@ To submit a snapshot for building, we should have a service file with content -How to have such a service file created automatically ? -Go into project you want to update. It mught be: +# How to have such a service file created automatically ? +--------------------------------------------------------- +Go into project you want to update. It might be: - openSUSE Build Service > Projects > Application:ERP:Dolibarr > dolibarr - or your private project Once logged, click on "Add file" in section "Source Files", then select mode "Upload From: Remote URL" Keep empty for "Filename", choose "Remote URL" and enter into last field, URL that should looks like this: -http://www.dolibarr.org/files/stable/package_rpm_generic/dolibarr-x.y.v-0.4.src.rpm +https://www.dolibarr.org/files/stable/package_rpm_generic/dolibarr-x.y.v-0.4.src.rpm Then add into Advanded - Attributes -OBS:Screenshots http://www.dolibarr.org/images/dolibarr_screenshot1.png -OBS:QualityCategory Stable|Testing|Development|Private +OBS:Screenshots https://www.dolibarr.org/images/dolibarr_screenshot1.png +OBS:QualityCategory Stable|Testing|Development|Private # Move project into official directory +-------------------------------------- - Enter a bug to ask to be a maintener of a category or to add a new one. For example: https://bugzilla.novell.com/show_bug.cgi?id=848083 to be a maintener of category https://build.opensuse.org/project/show/Application:ERP diff --git a/composer.json b/composer.json index 86acd2f8d60..d26bbb05ad9 100644 --- a/composer.json +++ b/composer.json @@ -28,11 +28,12 @@ "ext-curl" : "*", "ckeditor/ckeditor" : "4.12.1", "mike42/escpos-php" : "2.2", - "mobiledetect/mobiledetectlib" : "2.8.33", + "mobiledetect/mobiledetectlib" : "2.8.34", "phpoffice/phpexcel" : "1.8.1", "restler/framework" : "3.0.0-RC6", - "tecnickcom/tcpdf" : "^6.2", - "luracast/restler" : "^3.0" + "tecnickcom/tcpdf" : "6.3.2", + "nnnick/chartjs" : "^2.9", + "stripe/stripe-php" : "6.43.1" }, "require-dev" : { "jakub-onderka/php-parallel-lint" : "^0", @@ -56,4 +57,4 @@ "ext-zip" : "ODT, Excel and file compression support", "ext-xml" : "Excel support" } -} \ No newline at end of file +} diff --git a/composer.lock b/composer.lock index e9ea391bba2..09c71674512 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "16c94fd4f22ac17820d85ee57b0616e1", + "content-hash": "17e906996157e8a94564f686a6096dc5", "packages": [ { "name": "ckeditor/ckeditor", @@ -49,24 +49,31 @@ }, { "name": "mike42/escpos-php", - "version": "v1.2.1", + "version": "v2.2", "source": { "type": "git", "url": "https://github.com/mike42/escpos-php.git", - "reference": "cfea4c4fc95516ac953e1e5b623f854632afa2ee" + "reference": "e5496cf819b048b11877117bd14a9cea4fb17c03" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/mike42/escpos-php/zipball/cfea4c4fc95516ac953e1e5b623f854632afa2ee", - "reference": "cfea4c4fc95516ac953e1e5b623f854632afa2ee", + "url": "https://api.github.com/repos/mike42/escpos-php/zipball/e5496cf819b048b11877117bd14a9cea4fb17c03", + "reference": "e5496cf819b048b11877117bd14a9cea4fb17c03", "shasum": "" }, "require": { - "php": ">=5.3.0" + "ext-mbstring": "*", + "php": ">=5.4.0" }, "require-dev": { - "phpunit/phpunit": "4.5.*", - "squizlabs/php_codesniffer": "2.*" + "guzzlehttp/guzzle": "^5.3", + "phpunit/phpunit": "^4.8", + "squizlabs/php_codesniffer": "^3.2" + }, + "suggest": { + "ext-gd": "Used for image printing if present.", + "ext-imagick": "Will be used for image printing if present. Required for PDF printing or use of custom fonts.", + "guzzlehttp/guzzle": "Allows the use of the ApiConnector to send print jobs over HTTP." }, "type": "library", "autoload": { @@ -79,28 +86,12 @@ "MIT" ], "authors": [ - { - "name": "Roni Saha", - "email": "roni.cse@gmail.com" - }, { "name": "Michael Billington", "email": "michael.billington@gmail.com" - }, - { - "name": "Gergely Radics", - "email": "gerifield@ustream.tv" - }, - { - "name": "Warren Doyle", - "email": "w.doyle@fuelled.co" - }, - { - "name": "vharo", - "email": "vharo@geepok.com" } ], - "description": "Thermal receipt printer library, for use with ESC/POS compatible printers", + "description": "PHP receipt printer library for use with ESC/POS-compatible thermal and impact printers", "homepage": "https://github.com/mike42/escpos-php", "keywords": [ "ESC-POS", @@ -109,20 +100,20 @@ "print", "receipt" ], - "time": "2016-04-25T01:14:07+00:00" + "time": "2019-10-05T05:59:00+00:00" }, { "name": "mobiledetect/mobiledetectlib", - "version": "2.8.33", + "version": "2.8.34", "source": { "type": "git", "url": "https://github.com/serbanghita/Mobile-Detect.git", - "reference": "cd385290f9a0d609d2eddd165a1e44ec1bf12102" + "reference": "6f8113f57a508494ca36acbcfa2dc2d923c7ed5b" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/serbanghita/Mobile-Detect/zipball/cd385290f9a0d609d2eddd165a1e44ec1bf12102", - "reference": "cd385290f9a0d609d2eddd165a1e44ec1bf12102", + "url": "https://api.github.com/repos/serbanghita/Mobile-Detect/zipball/6f8113f57a508494ca36acbcfa2dc2d923c7ed5b", + "reference": "6f8113f57a508494ca36acbcfa2dc2d923c7ed5b", "shasum": "" }, "require": { @@ -161,7 +152,48 @@ "mobile detector", "php mobile detect" ], - "time": "2018-09-01T15:05:15+00:00" + "time": "2019-09-18T18:44:20+00:00" + }, + { + "name": "nnnick/chartjs", + "version": "v2.9.3", + "source": { + "type": "git", + "url": "https://github.com/chartjs/Chart.js.git", + "reference": "06f73dc3590084b2c464bf08189c7aee2b6b92d2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/chartjs/Chart.js/zipball/06f73dc3590084b2c464bf08189c7aee2b6b92d2", + "reference": "06f73dc3590084b2c464bf08189c7aee2b6b92d2", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "type": "library", + "extra": { + "branch-alias": { + "release/2.0": "v2.0-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "NICK DOWNIE", + "email": "hello@nickdownie.com" + } + ], + "description": "Simple HTML5 charts using the canvas element.", + "homepage": "https://www.chartjs.org/", + "keywords": [ + "JS", + "chart" + ], + "time": "2019-11-14T18:37:30+00:00" }, { "name": "phpoffice/phpexcel", @@ -282,6 +314,62 @@ ], "time": "2019-05-12T15:15:11+00:00" }, + { + "name": "stripe/stripe-php", + "version": "v6.43.1", + "source": { + "type": "git", + "url": "https://github.com/stripe/stripe-php.git", + "reference": "42fcdaf99c44bb26937223f8eae1f263491d5ab8" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stripe/stripe-php/zipball/42fcdaf99c44bb26937223f8eae1f263491d5ab8", + "reference": "42fcdaf99c44bb26937223f8eae1f263491d5ab8", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "php-coveralls/php-coveralls": "1.*", + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0", + "symfony/process": "~2.8" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "psr-4": { + "Stripe\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Stripe and contributors", + "homepage": "https://github.com/stripe/stripe-php/contributors" + } + ], + "description": "Stripe PHP Library", + "homepage": "https://stripe.com/", + "keywords": [ + "api", + "payment processing", + "stripe" + ], + "time": "2019-08-29T16:56:12+00:00" + }, { "name": "tecnickcom/tcpdf", "version": "6.3.2", @@ -1815,7 +1903,7 @@ "prefer-stable": false, "prefer-lowest": false, "platform": { - "php": ">=5.3.0", + "php": ">=5.5.0", "ext-curl": "*" }, "platform-dev": [] diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 107f561eca6..81a273d102a 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -253,6 +253,24 @@ PARSEDOWN $shortage = 4 - $len % 4; + +OAUTH +----- +Add into Class Google of file OAuth2/Service/Google: + + // LDR CHANGE Add approval_prompt to force the prompt if value is set to 'force' so it force return of a "refresh token" in addition to "standard token" + public $approvalPrompt='auto'; + public function setApprouvalPrompt($prompt) + { + if (!in_array($prompt, array('auto', 'force'), true)) { + // @todo Maybe could we rename this exception + throw new InvalidAccessTypeException('Invalid approuvalPrompt, expected either auto or force.'); + } + $this->approvalPrompt = $prompt; + } + + + JEDITABLE.JS ------------ diff --git a/dev/examples/code/create_invoice.php b/dev/examples/code/create_invoice.php index dbbe9d84c1c..1b212e0a5d7 100755 --- a/dev/examples/code/create_invoice.php +++ b/dev/examples/code/create_invoice.php @@ -66,8 +66,9 @@ $obj = new Facture($db); $obj->ref = 'ABCDE'; $obj->socid = 4; // Put id of third party (rowid in llx_societe table) -$obj->date = mktime(); -$obj->note = 'A comment'; +$obj->date = dol_now(); +$obj->note_public = 'A public comment'; +$obj->note_private = 'A private comment'; $obj->cond_reglement_id = 1; $line1=new FactureLigne($db); diff --git a/dev/examples/code/create_order.php b/dev/examples/code/create_order.php index 30265d5462e..703254ad5e9 100755 --- a/dev/examples/code/create_order.php +++ b/dev/examples/code/create_order.php @@ -66,8 +66,9 @@ $com = new Commande($db); $com->ref = 'ABCDE'; $com->socid = 4; // Put id of third party (rowid in llx_societe table) -$com->date_commande = mktime(); -$com->note = 'A comment'; +$com->date = dol_now(); +$com->note_public = 'A public comment'; +$com->note_private = 'A private comment'; $com->source = 1; $com->remise_percent = 0; diff --git a/dev/examples/ldap/ldapadd_sample1.txt b/dev/examples/ldap/ldapadd_sample1.txt index 8a28529acb8..e998d6013a3 100644 --- a/dev/examples/ldap/ldapadd_sample1.txt +++ b/dev/examples/ldap/ldapadd_sample1.txt @@ -11,4 +11,4 @@ objectclass: dcObject objectClass: organization objectClass: top dc: my-domain -o: Mon organisation \ No newline at end of file +o: my organisation diff --git a/dev/examples/ldap/ldapmodify_sample1.txt b/dev/examples/ldap/ldapmodify_sample1.txt index e3a8361ca31..e95d1dc03a7 100644 --- a/dev/examples/ldap/ldapmodify_sample1.txt +++ b/dev/examples/ldap/ldapmodify_sample1.txt @@ -12,4 +12,4 @@ objectclass: dcObject objectClass: organization objectClass: top dc: my-domain -o: Mon organisation \ No newline at end of file +o: my organisation diff --git a/dev/initdata/generate-invoice.php b/dev/initdata/generate-invoice.php index 220144f2a7d..3fe058e8d3e 100755 --- a/dev/initdata/generate-invoice.php +++ b/dev/initdata/generate-invoice.php @@ -23,6 +23,10 @@ * \brief Script example to inject random customer invoices (for load tests) */ +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdata/generate-order.php b/dev/initdata/generate-order.php index 129313c70fd..1dc56aa5582 100755 --- a/dev/initdata/generate-order.php +++ b/dev/initdata/generate-order.php @@ -24,6 +24,10 @@ * \brief Script example to inject random orders (for load tests) */ +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdata/generate-product.php b/dev/initdata/generate-product.php index 49fd9860467..a82c0262360 100755 --- a/dev/initdata/generate-product.php +++ b/dev/initdata/generate-product.php @@ -24,6 +24,10 @@ * \brief Script example to inject random products (for load tests) */ +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdata/generate-proposal.php b/dev/initdata/generate-proposal.php index d0b2cd4aa56..4c5d70aadc4 100755 --- a/dev/initdata/generate-proposal.php +++ b/dev/initdata/generate-proposal.php @@ -24,6 +24,10 @@ * \brief Script example to inject random proposals (for load tests) */ +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdata/generate-thirdparty.php b/dev/initdata/generate-thirdparty.php index 91c7c969b75..05ac6416aa3 100755 --- a/dev/initdata/generate-thirdparty.php +++ b/dev/initdata/generate-thirdparty.php @@ -24,6 +24,10 @@ * \brief Script example to inject random thirdparties (for load tests) */ +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path=dirname(__FILE__).'/'; + // Test si mode batch $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') { diff --git a/dev/initdata/import-users.php b/dev/initdata/import-users.php index 60a672adf12..4247415288c 100755 --- a/dev/initdata/import-users.php +++ b/dev/initdata/import-users.php @@ -20,7 +20,7 @@ */ /** - * \file dev/initdata/import-thirdparties.php + * \file dev/initdata/import-users.php * \brief Script example to insert thirdparties from a csv file. * To purge data, you can have a look at purge-data.php */ diff --git a/dev/resources/licence/Links on GPL.txt b/dev/resources/licence/Links on GPL.txt index bb9c1597f68..0fb3b63c851 100644 --- a/dev/resources/licence/Links on GPL.txt +++ b/dev/resources/licence/Links on GPL.txt @@ -1,7 +1,7 @@ -* Page with licence compatibility +* Page with license compatibility https://www.gnu.org/licenses/quick-guide-gplv3.fr.html -* FAQ on GPL licence +* FAQ on GPL license https://www.fsf.org/licensing/licenses/gpl-faq.html * Questions/Answers on Fork for using Dolibarr as a SaaS diff --git a/dev/resources/sepa/text.txt b/dev/resources/sepa/text.txt index 0a5336a128e..e6c05276be2 100644 --- a/dev/resources/sepa/text.txt +++ b/dev/resources/sepa/text.txt @@ -1,2 +1,2 @@ -To test a SEPA file: -http://www.mesfluxdepaiement.fr/testez-vos-fichiers-sepa \ No newline at end of file +To test a SEPA file: +https://www.mesfluxdepaiement.fr/testez-vos-fichiers-sepa diff --git a/dev/setup/codesniffer/ruleset.dtd b/dev/setup/codesniffer/ruleset.dtd index 276626a3a16..24aa32970ea 100644 --- a/dev/setup/codesniffer/ruleset.dtd +++ b/dev/setup/codesniffer/ruleset.dtd @@ -1,13 +1,18 @@ - + + + + - + + + diff --git a/dev/setup/codesniffer/ruleset.xml b/dev/setup/codesniffer/ruleset.xml index 460f815755e..8bd3ff8b319 100644 --- a/dev/setup/codesniffer/ruleset.xml +++ b/dev/setup/codesniffer/ruleset.xml @@ -2,6 +2,7 @@ Dolibarr coding standard. + build/html build/aps @@ -188,7 +189,6 @@ - diff --git a/dev/setup/eclipse/PSR-12 [built-in].xml b/dev/setup/eclipse/PSR-12 [built-in].xml new file mode 100644 index 00000000000..47925209682 --- /dev/null +++ b/dev/setup/eclipse/PSR-12 [built-in].xml @@ -0,0 +1,215 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dev/tools/dolibarr-postgres2mysql.php b/dev/tools/dolibarr-postgres2mysql.php new file mode 100644 index 00000000000..f2794455ca3 --- /dev/null +++ b/dev/tools/dolibarr-postgres2mysql.php @@ -0,0 +1,578 @@ +#!/usr/bin/env php + Lightbox Technologies Inc. + * Copyright (C) 2020 Laurent Destailleur + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 . + * + * This file is base on pg2mysql provided as Open source by lightbox.org. + * It was enhanced and updated by the Dolibarr team. + */ + +/** + * \file dev/tools/dolibarr-postgres2mysql.php + * \brief Script to migrate a postgresql dump into a mysql dump + */ + +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path = dirname(__FILE__) . '/'; + +// Test si mode batch +$sapi_type = php_sapi_name(); +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n"; + exit(); +} + +error_reporting(E_ALL & ~ E_DEPRECATED); +define('PRODUCT', "pg2mysql"); +define('VERSION', "2.0"); + +// this is the default, it can be overridden here, or specified as the third parameter on the command line +$config['engine'] = "InnoDB"; + +if (! ($argv[1] && $argv[2])) { + echo "Usage: php pg2mysql_cli.php [engine]\n"; + exit(); +} else { + if (isset($argv[3])) + $config['engine'] = $argv[3]; + pg2mysql_large($argv[1], $argv[2]); + + echo <<=0 if OK + */ +function pg2mysql_large($infilename, $outfilename) +{ + $infp = fopen($infilename, "rt"); + $outfp = fopen($outfilename, "wt"); + + $outputatend = ''; + $arrayofprimaryalreadyintabledef = array(); + + // we read until we get a semicolon followed by a newline (;\n); + $pgsqlchunk = array(); + $chunkcount = 1; + $linenum = 0; + $inquotes = false; + $first = true; + + if (empty($infp)) { + print 'Failed to open file '.$infilename."\n"; + return -1; + } + + $fs = filesize($infilename); + echo "Filesize: " . formatsize($fs) . "\n"; + + while ($instr = fgets($infp)) { + $linenum ++; + $memusage = round(memory_get_usage(true) / 1024 / 1024); + $len = strlen($instr); + $pgsqlchunk[] = $instr; + $c = substr_count($instr, "'"); + // we have an odd number of ' marks + if ($c % 2 != 0) { + if ($inquotes) + $inquotes = false; + else + $inquotes = true; + } + + if ($linenum % 10000 == 0) { + $currentpos = ftell($infp); + $percent = round($currentpos / $fs * 100); + $position = formatsize($currentpos); + printf("Reading progress: %3d%% position: %7s line: %9d sql chunk: %9d mem usage: %4dM\r", $percent, $position, $linenum, $chunkcount, $memusage); + } + + if (strlen($instr) > 3 && ($instr[$len - 3] == ")" && $instr[$len - 2] == ";" && $instr[$len - 1] == "\n") && $inquotes == false) { + $chunkcount ++; + + if ($linenum % 10000 == 0) { + $currentpos = ftell($infp); + $percent = round($currentpos / $fs * 100); + $position = formatsize($currentpos); + printf("Processing progress: %3d%% position: %7s line: %9d sql chunk: %9d mem usage: %4dM\r", $percent, $position, $linenum, $chunkcount, $memusage); + } + /* + * echo "sending chunk:\n"; + * echo "=======================\n"; + * print_r($pgsqlchunk); + * echo "=======================\n"; + */ + + /* + * foreach ($pgsqlchunk as $aaa) { + * if (preg_match('/MAIN_ENABLE_DEFAULT|MAIN_MAIL_SMTP_SE/', $aaa)) { + * var_dump($pgsqlchunk); + * } + * } + */ + + $mysqlchunk = pg2mysql($pgsqlchunk, $arrayofprimaryalreadyintabledef, $first); + fputs($outfp, $mysqlchunk['output']); + + /* + * $break = false; + * foreach ($pgsqlchunk as $aaa) { + * if (preg_match('/MAIN_ENABLE_DEFAULT|MAIN_MAIL_SMTP_SE/', $aaa)) { + * var_dump($mysqlchunk); + * } + * if (preg_match('/MAIN_MAIL_SMTP_SE/', $aaa)) { + * $break = true; + * } + * } + * if ($break) break; + */ + + $outputatend .= $mysqlchunk['outputatend']; + + $first = false; + $pgsqlchunk = array(); + $mysqlchunk = ""; + } + } + echo "\n\n"; + + fputs($outfp, $outputatend); + + fputs($outfp, "\n"); + + fputs($outfp, '/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;' . "\n"); + fputs($outfp, '/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;' . "\n"); + fputs($outfp, '/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;' . "\n"); + fputs($outfp, '/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;' . "\n"); + fputs($outfp, '/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;' . "\n"); + fputs($outfp, '/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;' . "\n"); + fputs($outfp, '/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;' . "\n"); + + printf("Completed! %9d lines %9d sql chunks\n\n", $linenum, $chunkcount); + + fclose($infp); + fclose($outfp); + + return 0; +} + +/** + * pg2mysql + * + * @param array $input Array of input + * @param array $arrayofprimaryalreadyintabledef Array of table already output with a primary key set into definition + * @param boolean $header Boolean + * @return string[] Array of output + */ +function pg2mysql(&$input, &$arrayofprimaryalreadyintabledef, $header = true) +{ + global $config; + + if (is_array($input)) { + $lines = $input; + } else { + $lines = split("\n", $input); + } + + if ($header) { + $output = "-- Converted with " . PRODUCT . "-" . VERSION . "\n"; + $output .= "-- Converted on " . date("r") . "\n"; + $output .= "\n"; + + $output .= "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n"; + $output .= "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n"; + $output .= "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n"; + $output .= "/*!40101 SET NAMES utf8 */;\n"; + $output .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;\n"; + $output .= "/*!40103 SET TIME_ZONE='+00:00' */;\n"; + $output .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n"; + $output .= "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n"; + $output .= "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n"; + $output .= "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n"; + $output .= "\n"; + + $outputatend = ""; + } else { + $output = ""; + $outputatend = ""; + } + + $in_create_table = $in_insert = false; + + $linenumber = 0; + $tbl_extra = ""; + while (isset($lines[$linenumber])) { + $line = $lines[$linenumber]; + // $line =str_replace('ALTER TABLE public\.', '', $line); + + $reg = array(); + if (preg_match('/CREATE SEQUENCE (?:public\.)(.*)_(id|rowid|id_comment)_seq/', $line, $reg)) { + $outputatend .= '-- Make field ' . $reg[2] . ' auto_increment for table ' . $reg[1] . "\n"; + $outputatend .= 'ALTER TABLE ' . $reg[1] . ' CHANGE COLUMN ' . $reg[2] . ' ' . $reg[2] . ' INTEGER NOT NULL AUTO_INCREMENT;' . "\n\n"; + // var_dump($outputatend); + } + + if (substr($line, 0, 12) == "CREATE TABLE") { + $in_create_table = true; + $line = str_replace("\"", "`", $line); + $line = str_replace('public.', '', $line); + + $reg2 = array(); + if (preg_match('/CREATE TABLE ([^\s]+)/', $line, $reg2)) { + $in_create_table = $reg2[1]; + } + + $reg2 = array(); + if (preg_match('/CREATE TABLE ([^\s]+)/', $line, $reg2)) { + $output .= 'DROP TABLE IF EXISTS `' . $reg2[1] . '`;' . "\n"; + } + $output .= $line; + $linenumber ++; + continue; + } + + if (substr($line, 0, 2) == ");" && $in_create_table) { + $in_create_table = false; + $line = ") ENGINE={$config['engine']};\n\n"; + + $output .= $tbl_extra; + $output .= $line; + + $linenumber ++; + $tbl_extra = ""; + continue; + } + + if ($in_create_table) { + $regs = array(); + $line = str_replace("\"", "`", $line); + $line = str_replace(" integer", " int(11)", $line); + $line = str_replace(" int_unsigned", " int(11) UNSIGNED", $line); + $line = str_replace(" smallint_unsigned", " smallint UNSIGNED", $line); + $line = str_replace(" bigint_unsigned", " bigint UNSIGNED", $line); + $line = str_replace(" serial ", " int(11) auto_increment ", $line); + $line = str_replace(" bytea", " BLOB", $line); + $line = str_replace(" boolean", " bool", $line); + $line = str_replace(" bool DEFAULT true", " bool DEFAULT 1", $line); + $line = str_replace(" bool DEFAULT false", " bool DEFAULT 0", $line); + if (preg_match("/ character varying\(([0-9]*)\)/", $line, $regs)) { + $num = $regs[1]; + if ($num <= 255) + $line = preg_replace("/ character varying\([0-9]*\)/", " varchar($num)", $line); + else + $line = preg_replace("/ character varying\([0-9]*\)/", " text", $line); + } + // character varying with no size, we will default to varchar(255) + if (preg_match("/ character varying/", $line)) { + $line = preg_replace("/ character varying/", " varchar(255)", $line); + } + + if (preg_match("/ DEFAULT \('([0-9]*)'::int/", $line, $regs) || preg_match("/ DEFAULT \('([0-9]*)'::smallint/", $line, $regs) || preg_match("/ DEFAULT \('([0-9]*)'::bigint/", $line, $regs)) { + $num = $regs[1]; + $line = preg_replace("/ DEFAULT \('([0-9]*)'[^ ,]*/", " DEFAULT $num ", $line); + } + if (preg_match("/ DEFAULT \(([0-9\-]*)\)/", $line, $regs)) { + $num = $regs[1]; + $line = preg_replace("/ DEFAULT \(([0-9\-]*)\)/", " DEFAULT $num ", $line); + } + $line = preg_replace("/ DEFAULT nextval\(.*\) /", " auto_increment ", $line); + $line = preg_replace("/::.*,/", ",", $line); + $line = preg_replace("/::.*$/", "\n", $line); + if (preg_match("/character\(([0-9]*)\)/", $line, $regs)) { + $num = $regs[1]; + if ($num <= 255) + $line = preg_replace("/ character\([0-9]*\)/", " varchar($num)", $line); + else + $line = preg_replace("/ character\([0-9]*\)/", " text", $line); + } + // timestamps + $line = str_replace(" timestamp with time zone", " datetime", $line); + $line = str_replace(" timestamp without time zone", " datetime", $line); + + // time + $line = str_replace(" time with time zone", " time", $line); + $line = str_replace(" time without time zone", " time", $line); + + $line = str_replace(" timestamp DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); + $line = str_replace(" timestamp without time zone DEFAULT now()", " timestamp DEFAULT CURRENT_TIMESTAMP", $line); + + if (strstr($line, "auto_increment") || preg_match('/ rowid int/', $line) || preg_match('/ id int/', $line)) { + $field = getfieldname($line); + $tbl_extra .= ", PRIMARY KEY(`$field`)\n"; + $arrayofprimaryalreadyintabledef[$in_create_table] = $in_create_table; + } + + $specialfields = array("repeat","status","type","call"); + + $field = getfieldname($line); + if (in_array($field, $specialfields)) { + $line = str_replace("$field ", "`$field` ", $line); + } + + // text/blob fields are not allowed to have a default, so if we find a text DEFAULT, change it to varchar(255) DEFAULT + if (strstr($line, "text DEFAULT")) { + $line = str_replace(" text DEFAULT ", " varchar(255) DEFAULT ", $line); + } + + // just skip a CONSTRAINT line + if (strstr($line, " CONSTRAINT ")) { + $line = ""; + // and if the previous output ended with a , remove the , + $lastchr = substr($output, - 2, 1); + // echo "lastchr=$lastchr"; + if ($lastchr == ",") { + $output = substr($output, 0, - 2) . "\n"; + } + } + + $output .= $line; + } + + if (substr($line, 0, 11) == "INSERT INTO") { + $line = str_replace('public.', '', $line); + + if (substr($line, - 3, - 1) == ");") { + // we have a complete insert on one line + list ($before, $after) = explode(" VALUES ", $line, 2); + // we only replace the " with ` in what comes BEFORE the VALUES + // (ie, field names, like INSERT INTO table ("bla","bla2") VALUES ('s:4:"test"','bladata2'); + // should convert to INSERT INTO table (`bla`,`bla2`) VALUES ('s:4:"test"','bladata2'); + + $before = str_replace("\"", "`", $before); + + // in after, we need to watch out for escape format strings, ie (E'escaped \r in a string'), and ('bla',E'escaped \r in a string'), but could also be (number, E'string'); so we cant search for the previoous ' + // ugh i guess its possible these strings could exist IN the data as well, but the only way to solve that is to process these lines one character + // at a time, and thats just stupid, so lets just hope this doesnt appear anywhere in the actual data + $after = str_replace(" (E'", " ('", $after); + $after = str_replace(", E'", ", '", $after); + + $output .= $before . " VALUES " . $after; + $linenumber ++; + continue; + } else { + // this insert spans multiple lines, so keep dumping the lines until we reach a line + // that ends with ");" + + list ($before, $after) = explode(" VALUES ", $line, 2); + // we only replace the " with ` in what comes BEFORE the VALUES + // (ie, field names, like INSERT INTO table ("bla","bla2") VALUES ('s:4:"test"','bladata2'); + // should convert to INSERT INTO table (`bla`,`bla2`) VALUES ('s:4:"test"','bladata2'); + + $before = str_replace("\"", "`", $before); + + // in after, we need to watch out for escape format strings, ie (E'escaped \r in a string'), and ('bla',E'escaped \r in a string') + // ugh i guess its possible these strings could exist IN the data as well, but the only way to solve that is to process these lines one character + // at a time, and thats just stupid, so lets just hope this doesnt appear anywhere in the actual data + $after = str_replace(" (E'", " ('", $after); + $after = str_replace(", E'", ", '", $after); + + $c = substr_count($line, "'"); + // we have an odd number of ' marks + if ($c % 2 != 0) { + $inquotes = true; + } else { + $inquotes = false; + } + + $output .= $before . " VALUES " . $after; + do { + $linenumber ++; + + // in after, we need to watch out for escape format strings, ie (E'escaped \r in a string'), and ('bla',E'escaped \r in a string') + // ugh i guess its possible these strings could exist IN the data as well, but the only way to solve that is to process these lines one character + // at a time, and thats just stupid, so lets just hope this doesnt appear anywhere in the actual data + + // after the first line, we only need to check for it in the middle, not at the beginning of an insert (becuase the beginning will be on the first line) + // $after=str_replace(" (E'","' ('",$after); + $line = $lines[$linenumber]; + $line = str_replace("', E'", "', '", $line); + $output .= $line; + + // printf("inquotes: %d linenumber: %4d line: %s\n",$inquotes,$linenumber,$lines[$linenumber]); + + $c = substr_count($line, "'"); + // we have an odd number of ' marks + if ($c % 2 != 0) { + if ($inquotes) + $inquotes = false; + else + $inquotes = true; + // echo "inquotes=$inquotes\n"; + } + } while (substr($lines[$linenumber], - 3, - 1) != ");" || $inquotes); + } + } + if (substr($line, 0, 16) == "ALTER TABLE ONLY") { + $line = preg_replace('/ ONLY/', '', $line); + $line = str_replace("\"", "`", $line); + $line = str_replace("public.", "", $line); + $pkey = $line; + + $linenumber ++; + if (! empty($lines[$linenumber])) { + $line = $lines[$linenumber]; + } else { + $line = ''; + } + + if (strstr($line, " PRIMARY KEY ") && substr($line, - 3, - 1) == ");") { + $reg2 = array(); + if (preg_match('/ALTER TABLE ([^\s]+)/', $pkey, $reg2)) { + if (empty($arrayofprimaryalreadyintabledef[$reg2[1]])) { + // looks like we have a single line PRIMARY KEY definition, lets go ahead and add it + $output .= str_replace("\n", "", $pkey); + // the postgres and mysql syntax for this is (at least, in the example im looking at) + // identical, so we can just add it as is. + $output .= $line . "\n"; + } else { + $output .= '-- ' . str_replace("\n", "", $pkey); + $output .= '-- ' . $line . "\n"; + } + } else { + $output .= '-- ' . str_replace("\n", "", $pkey); + $output .= '-- ' . $line . "\n"; + } + } + } + + // while we're here, we might as well catch CREATE INDEX as well + if (substr($line, 0, 12) == "CREATE INDEX") { + $matches = array(); + preg_match('/CREATE INDEX "?([a-zA-Z0-9_]*)"? ON "?([a-zA-Z0-9_\.]*)"? USING btree \((.*)\);/', $line, $matches); + if (! empty($matches[3])) { + $indexname = $matches[1]; + $tablename = str_replace('public.', '', $matches[2]); + $columns = $matches[3]; + if ($tablename && $columns) { + $output .= "ALTER TABLE `" . $tablename . "` ADD INDEX " . $indexname . "( {$columns} ) ;\n"; + } + } + } + if (substr($line, 0, 19) == "CREATE UNIQUE INDEX") { + $matches = array(); + preg_match('/CREATE UNIQUE INDEX "?([a-zA-Z0-9_]*)"? ON "?([a-zA-Z0-9_\.]*)"? USING btree \((.*)\);/', $line, $matches); + if (! empty($matches[3])) { + $indexname = $matches[1]; + $tablename = str_replace('public.', '', $matches[2]); + $columns = str_replace('"', '', $matches[3]); + if ($tablename && $columns) { + $output .= "ALTER TABLE `" . $tablename . "` ADD UNIQUE INDEX " . $indexname . " ( {$columns} ) ;\n"; + } + } + } + + if (substr($line, 0, 13) == 'DROP DATABASE') + $output .= $line; + + if (substr($line, 0, 15) == 'CREATE DATABASE') { + $matches = array(); + preg_match('/CREATE DATABASE ([a-zA-Z0-9_]*) .* ENCODING = \'(.*)\'/', $line, $matches); + $output .= "CREATE DATABASE `$matches[1]` DEFAULT CHARACTER SET $matches[2];\n\n"; + } + + if (substr($line, 0, 8) == '\\connect') { + $matches = array(); + preg_match('/connect ([a-zA-Z0-9_]*)/', $line, $matches); + $output .= "USE `$matches[1]`;\n\n"; + } + + if (substr($line, 0, 5) == 'COPY ') { + $matches = array(); + preg_match('/COPY (.*) FROM stdin/', $line, $matches); + $heads = str_replace('"', "`", $matches[1]); + $values = array(); + $in_insert = true; + } elseif ($in_insert) { + if ($line == "\\.\n") { + $in_insert = false; + if ($values) { + $output .= "INSERT INTO $heads VALUES\n" . implode(",\n", $values) . ";\n\n"; + } + } else { + $vals = explode(' ', $line); + foreach ($vals as $i => $val) { + $vals[$i] = ($val == '\\N') ? 'NULL' : "'" . str_replace("'", "\\'", trim($val)) . "'"; + } + $values[] = '(' . implode(',', $vals) . ')'; + if (count($values) >= 1000) { + $output .= "INSERT INTO $heads VALUES\n" . implode(",\n", $values) . ";\n"; + $values = array(); + } + } + } + + $linenumber ++; + } + + return array('output' => $output,'outputatend' => $outputatend); +} diff --git a/dev/translation/README b/dev/translation/README index b470e4228d8..9727f91e2e6 100644 --- a/dev/translation/README +++ b/dev/translation/README @@ -3,11 +3,12 @@ README (English) This directory contains tools to generate translation files for a new languages or to update translation files for existing languages. See Dolibarr Wiki page: -http://wiki.dolibarr.org/index.php/Translator_documentation +https://wiki.dolibarr.org/index.php/Translator_documentation For more information on how to use them. +for Linux OS: To install transifex client: sudo pip install --upgrade transifex-client To update transifex client: -sudo pip install --upgrade transifex-client \ No newline at end of file +sudo pip install --upgrade transifex-client diff --git a/dev/translation/erp_comparison_translation.txt b/dev/translation/erp_comparison_translation.txt index c99a5f4cc1c..6cf7c4f7c60 100644 --- a/dev/translation/erp_comparison_translation.txt +++ b/dev/translation/erp_comparison_translation.txt @@ -1,17 +1,25 @@ +comparison of terms -Term Dolibarr SAP Odoo ... ----------------------------------------------------------------------------- -Thirdparty Contact partner Partner/Contact (company) -Contact/address Contact person Partner/Contact (individual) +Dolibarr SAP ERP Odoo +------------------------------------------------------------------------- +Thirdparty Contact partner Partner/Contact (company) +Contact/address Contact person Partner/Contact (individual) -Financial ?? Invoicing - -Income / Expense ?? Profit / Loss -Balance ?? Net profit -Subledger account Subledger account ?? +Financial Finance (FI) Accounting +Accounting -Proposal ?? Quotation Proposal is ok but proposition looks better (proposal is for a detailed proposition). We can say also "business proposition or business proposal". - Indian are using "Quotation". +Income / Expense ?? Profit / Loss +Balance ?? Net profit +Subledger account Subledger account ?? + +CRM Sales & Distribution Sales +Proposal ?? Quotation + + + +Proposal is ok but proposition looks better (proposal is for a detailed proposition). +We can say also "business proposition or business proposal". +In India they are using "Quotation". diff --git a/dev/translation/txpull.sh b/dev/translation/txpull.sh index 3f24bd0912d..fcccae98221 100755 --- a/dev/translation/txpull.sh +++ b/dev/translation/txpull.sh @@ -54,5 +54,5 @@ fi echo Think to launch also: echo "> dev/tools/fixaltlanguages.sh fix all" -echo "For v11: Replace also regex \(.*(sponge|cornas|eratosthene|cyan).*\) with ''" +echo "For v11: Replace also regex \(.*(sponge|cornas|eratosthene|cyan).*\) with '' on *.lang files" diff --git a/doc/images/README.md b/doc/images/README.md index 798cf599b4c..7422d246d40 100644 --- a/doc/images/README.md +++ b/doc/images/README.md @@ -10,7 +10,11 @@ https://github.com/Dolibarr/foundation -* Few icons are from http://led24.de/iconset/. This is original README file for this source: +* Few icons are / were from website led24.de + +* Attention: This website is no longer available! + +This is original README file for this source: ------------------------------------------------------- You can do whatever you want with these icons (use on web or in desktop applications) as long as you don’t pass them off as your own and remove this readme file. A credit statement and a link back to http://led24.de/iconset/ or http://led24.de/ would be appreciated. diff --git a/doc/user/README-DE.md b/doc/user/README-DE.md new file mode 100644 index 00000000000..ea9458f4563 --- /dev/null +++ b/doc/user/README-DE.md @@ -0,0 +1,12 @@ +README (german) +LiesMich (deutsch) + +-------------------------------- +Benutzeranleitung +-------------------------------- + +Alle Dolibarr-Informationen sind online verfuegbar ueber die Webseiten: +https://www.dolibarr.de +oder +https://www.dolibarr.org +https://wiki.dolibarr.org diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php index 9de858da26b..1afe2ecca18 100644 --- a/htdocs/accountancy/admin/account.php +++ b/htdocs/accountancy/admin/account.php @@ -45,7 +45,8 @@ $search_label = GETPOST('search_label', 'alpha'); $search_labelshort = GETPOST('search_labelshort', 'alpha'); $search_accountparent = GETPOST('search_accountparent', 'alpha'); $search_pcgtype = GETPOST('search_pcgtype', 'alpha'); -$search_pcgsubtype = GETPOST('search_pcgsubtype', 'alpha'); + +$chartofaccounts = GETPOST('chartofaccounts', 'int'); // Security check if ($user->socid > 0) accessforbidden(); @@ -55,7 +56,7 @@ if (!$user->rights->accounting->chartofaccount) accessforbidden(); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -69,10 +70,12 @@ $arrayfields = array( 'aa.labelshort'=>array('label'=>$langs->trans("LabelToShow"), 'checked'=>1), 'aa.account_parent'=>array('label'=>$langs->trans("Accountparent"), 'checked'=>1), 'aa.pcg_type'=>array('label'=>$langs->trans("Pcgtype"), 'checked'=>1, 'help'=>'PcgtypeDesc'), - 'aa.pcg_subtype'=>array('label'=>$langs->trans("Pcgsubtype"), 'checked'=>0, 'help'=>'PcgtypeDesc'), + 'aa.reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1), 'aa.active'=>array('label'=>$langs->trans("Activated"), 'checked'=>1) ); +if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['aa.reconcilable']); + $accounting = new AccountingAccount($db); @@ -101,14 +104,11 @@ if (empty($reshook)) $search_labelshort = ""; $search_accountparent = ""; $search_pcgtype = ""; - $search_pcgsubtype = ""; $search_array_options = array(); } - - if (GETPOST('change_chart', 'alpha') && (GETPOST('valid_change_chart', 'int') || empty($conf->use_javascript_ajax))) + if ((GETPOST('valid_change_chart', 'alpha') && GETPOST('chartofaccounts', 'int') > 0) // explicit click on button 'Change and load' with js on + || (GETPOST('chartofaccounts', 'int') > 0 && GETPOST('chartofaccounts', 'int') != $conf->global->CHARTOFACCOUNTS)) // a submit of form is done and chartofaccounts combo has been modified { - $chartofaccounts = GETPOST('chartofaccounts', 'int'); - if ($chartofaccounts > 0) { // Get language code for this $chartofaccounts @@ -160,7 +160,8 @@ if (empty($reshook)) if ($action == 'disable') { if ($accounting->fetch($id)) { - $result = $accounting->account_desactivate($id); + $mode = GETPOST('mode', 'int'); + $result = $accounting->account_desactivate($id, $mode); } $action = 'update'; @@ -169,7 +170,8 @@ if (empty($reshook)) } } elseif ($action == 'enable') { if ($accounting->fetch($id)) { - $result = $accounting->account_activate($id); + $mode = GETPOST('mode', 'int'); + $result = $accounting->account_activate($id, $mode); } $action = 'update'; if ($result < 0) { @@ -195,7 +197,7 @@ if ($action == 'delete') { $pcgver = $conf->global->CHARTOFACCOUNTS; -$sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.labelshort, aa.active, "; +$sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.account_number, aa.account_parent , aa.label, aa.labelshort, aa.reconcilable, aa.active, "; $sql .= " a2.rowid as rowid2, a2.label as label2, a2.account_number as account_number2"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version AND aa.entity = ".$conf->entity; @@ -241,7 +243,6 @@ if (strlen(trim($search_label))) $sql .= natural_search("aa.label", $search_la if (strlen(trim($search_labelshort))) $sql .= natural_search("aa.labelshort", $search_labelshort); if (strlen(trim($search_accountparent)) && $search_accountparent != '-1') $sql .= natural_search("aa.account_parent", $search_accountparent, 2); if (strlen(trim($search_pcgtype))) $sql .= natural_search("aa.pcg_type", $search_pcgtype); -if (strlen(trim($search_pcgsubtype))) $sql .= natural_search("aa.pcg_subtype", $search_pcgsubtype); $sql .= $db->order($sortfield, $sortorder); // Count total nb of records @@ -274,23 +275,17 @@ if ($resql) if ($search_labelshort) $param .= '&search_labelshort='.urlencode($search_labelshort); if ($search_accountparent > 0 || $search_accountparent == '0') $param .= '&search_accountparent='.urlencode($search_accountparent); if ($search_pcgtype) $param .= '&search_pcgtype='.urlencode($search_pcgtype); - if ($search_pcgsubtype) $param .= '&search_pcgsubtype='.urlencode($search_pcgsubtype); - if ($optioncss != '') $param .= '&optioncss='.$optioncss; + if ($optioncss != '') $param .= '&optioncss='.$optioncss; if (!empty($conf->use_javascript_ajax)) { - print ' + print ' '; @@ -337,8 +332,7 @@ if ($resql) else dol_print_error($db); print ""; print ajax_combobox("chartofaccounts"); - print ''; - print ''; + print ''; print '
'; print '
'; @@ -363,7 +357,7 @@ if ($resql) print ''; } if (!empty($arrayfields['aa.pcg_type']['checked'])) print ''; - if (!empty($arrayfields['aa.pcg_subtype']['checked'])) print ''; + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (! empty($arrayfields['aa.reconcilable']['checked'])) print ' '; } if (!empty($arrayfields['aa.active']['checked'])) print ' '; print ''; $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); @@ -377,7 +371,7 @@ if ($resql) if (!empty($arrayfields['aa.labelshort']['checked'])) print_liste_field_titre($arrayfields['aa.labelshort']['label'], $_SERVER["PHP_SELF"], "aa.labelshort", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['aa.account_parent']['checked'])) print_liste_field_titre($arrayfields['aa.account_parent']['label'], $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, '', $sortfield, $sortorder, 'left '); if (!empty($arrayfields['aa.pcg_type']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_type']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_type', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_type']['help']); - if (!empty($arrayfields['aa.pcg_subtype']['checked'])) print_liste_field_titre($arrayfields['aa.pcg_subtype']['label'], $_SERVER["PHP_SELF"], 'aa.pcg_subtype', '', $param, '', $sortfield, $sortorder, '', $arrayfields['aa.pcg_subtype']['help']); + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { if (! empty($arrayfields['aa.reconcilable']['checked'])) print_liste_field_titre($arrayfields['aa.reconcilable']['label'], $_SERVER["PHP_SELF"], 'aa.reconcilable', '', $param, '', $sortfield, $sortorder); } if (!empty($arrayfields['aa.active']['checked'])) print_liste_field_titre($arrayfields['aa.active']['label'], $_SERVER["PHP_SELF"], 'aa.active', '', $param, '', $sortfield, $sortorder); print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; @@ -454,25 +448,36 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } - // Chart of accounts subtype - if (!empty($arrayfields['aa.pcg_subtype']['checked'])) - { - print ""; - print $obj->pcg_subtype; - print "\n"; - if (!$i) $totalarray['nbfield']++; + if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { + // Activated or not reconciliation on accounting account + if (!empty($arrayfields['aa.reconcilable']['checked'])) { + print ''; + if (empty($obj->reconcilable)) { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } else { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } } // Activated or not if (!empty($arrayfields['aa.active']['checked'])) { - print ''; + print ''; if (empty($obj->active)) { - print ''; + print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); print ''; } else { - print ''; + print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; } diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 2e39105eb21..0ab42d582d1 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -39,31 +39,31 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.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")); +$langs->loadLangs(array("errors", "admin", "companies", "resource", "holiday", "compta", "accountancy", "hrm")); -$action=GETPOST('action', 'aZ09')?GETPOST('action', 'aZ09'):'view'; -$confirm=GETPOST('confirm', 'alpha'); -$id=31; -$rowid=GETPOST('rowid', 'alpha'); -$code=GETPOST('code', 'alpha'); +$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; +$confirm = GETPOST('confirm', 'alpha'); +$id = 31; +$rowid = GETPOST('rowid', 'alpha'); +$code = GETPOST('code', 'alpha'); $acts[0] = "activate"; $acts[1] = "disable"; $actl[0] = img_picto($langs->trans("Disabled"), 'switch_off'); $actl[1] = img_picto($langs->trans("Activated"), 'switch_on'); -$listoffset=GETPOST('listoffset', 'alpha'); -$listlimit=GETPOST('listlimit', 'int')>0?GETPOST('listlimit', 'int'):1000; +$listoffset = GETPOST('listoffset', 'alpha'); +$listlimit = GETPOST('listlimit', 'int') > 0 ?GETPOST('listlimit', 'int') : 1000; $active = 1; $sortfield = GETPOST("sortfield", 'aZ09comma'); $sortorder = GETPOST("sortorder", 'aZ09comma'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 -$offset = $listlimit * $page ; +$offset = $listlimit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -72,7 +72,7 @@ $search_country_id = GETPOST('search_country_id', 'int'); // Security check if ($user->socid > 0) accessforbidden(); -if (! $user->rights->accounting->chartofaccount) accessforbidden(); +if (!$user->rights->accounting->chartofaccount) accessforbidden(); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -82,56 +82,56 @@ $hookmanager->initHooks(array('admin')); // Put here declaration of dictionaries properties // Name of SQL tables of dictionaries -$tabname=array(); +$tabname = array(); -$tabname[31]= MAIN_DB_PREFIX."accounting_system"; +$tabname[31] = MAIN_DB_PREFIX."accounting_system"; // Dictionary labels -$tablib=array(); -$tablib[31]= "Pcg_version"; +$tablib = array(); +$tablib[31] = "Pcg_version"; // Requests to extract data -$tabsql=array(); -$tabsql[31]= "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1"; +$tabsql = array(); +$tabsql[31] = "SELECT s.rowid as rowid, pcg_version, s.label, s.fk_country as country_id, c.code as country_code, c.label as country, s.active FROM ".MAIN_DB_PREFIX."accounting_system as s, ".MAIN_DB_PREFIX."c_country as c WHERE s.fk_country=c.rowid and c.active=1"; // Criteria to sort dictionaries -$tabsqlsort=array(); -$tabsqlsort[31]="pcg_version ASC"; +$tabsqlsort = array(); +$tabsqlsort[31] = "pcg_version ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire -$tabfield=array(); -$tabfield[31]= "pcg_version,label,country_id,country"; +$tabfield = array(); +$tabfield[31] = "pcg_version,label,country_id,country"; // Nom des champs d'edition pour modification d'un enregistrement -$tabfieldvalue=array(); -$tabfieldvalue[31]= "pcg_version,label,country"; +$tabfieldvalue = array(); +$tabfieldvalue[31] = "pcg_version,label,country"; // Nom des champs dans la table pour insertion d'un enregistrement -$tabfieldinsert=array(); -$tabfieldinsert[31]= "pcg_version,label,fk_country"; +$tabfieldinsert = array(); +$tabfieldinsert[31] = "pcg_version,label,fk_country"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on // "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); -$tabrowid[31]= ""; +$tabrowid = array(); +$tabrowid[31] = ""; // Condition to show dictionary in setup page -$tabcond=array(); -$tabcond[31]= ! empty($conf->accounting->enabled); +$tabcond = array(); +$tabcond[31] = !empty($conf->accounting->enabled); // List of help for fields -$tabhelp=array(); +$tabhelp = array(); $tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode")); // List of check for fields (NOT USED YET) -$tabfieldcheck=array(); +$tabfieldcheck = array(); $tabfieldcheck[31] = array(); // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); -$sourceList=array(); +$sourceList = array(); @@ -147,38 +147,38 @@ if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', // Actions add or modify an entry into a dictionary if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield=explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert=explode(',', $tabfieldinsert[$id]); - $listfieldmodify=explode(',', $tabfieldinsert[$id]); - $listfieldvalue=explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); // Check that all fields are filled - $ok=1; + $ok = 1; foreach ($listfield as $f => $value) { - if ($value == 'country_id' && in_array($tablib[$id], array('Pcg_version'))) continue; // For some pages, country is not mandatory - if ((! isset($_POST[$value]) || $_POST[$value]=='')) + if ($value == 'country_id' && in_array($tablib[$id], array('Pcg_version'))) continue; // For some pages, country is not mandatory + if ((!GETPOSTISSET($value)) || GETPOST($value) == '') { - $ok=0; - $fieldnamekey=$listfield[$f]; + $ok = 0; + $fieldnamekey = $listfield[$f]; // We take translate key of field - if ($fieldnamekey == 'pcg_version') $fieldnamekey='Pcg_version'; - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey='Label'; + if ($fieldnamekey == 'pcg_version') $fieldnamekey = 'Pcg_version'; + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); } } // Other checks - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"], array('system','systemauto'))) { - $ok=0; + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && GETPOSTISSET("type") && in_array($_POST["type"], array('system', 'systemauto'))) { + $ok = 0; setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); } - if (isset($_POST["pcg_version"])) + if (GETPOSTISSET("pcg_version")) { - if ($_POST["pcg_version"]=='0') + if (GETPOST("pcg_version") == '0') { - $ok=0; + $ok = 0; setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); } /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base @@ -187,9 +187,9 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ } - if (isset($_POST["country"]) && ($_POST["country"]=='0') && ($id != 2)) + if (isset($_POST["country"]) && ($_POST["country"] == '0') && ($id != 2)) { - $ok=0; + $ok = 0; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors'); } @@ -199,13 +199,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($tabrowid[$id]) { // Recupere id libre pour insertion - $newid=0; + $newid = 0; $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; $result = $db->query($sql); if ($result) { $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + $newid = ($obj->newid + 1); } else { dol_print_error($db); } @@ -214,16 +214,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",active)"; - $sql.= " VALUES("; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",active)"; + $sql .= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $newid.","; - $i=0; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; foreach ($listfieldinsert as $f => $value) { if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') { @@ -232,19 +232,19 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) elseif ($value == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.=",1)"; + $sql .= ",1)"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); if ($result) // Add is ok { setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST=array('id'=>$id); // Clean $_POST array, we keep only + $_POST = array('id'=>$id); // Clean $_POST array, we keep only } else { @@ -260,16 +260,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify', 'alpha')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldmodify)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; } $i = 0; foreach ($listfieldmodify as $field) @@ -280,18 +280,18 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) elseif ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; $resql = $db->query($sql); - if (! $resql) + if (!$resql) { setEventMessages($db->error(), null, 'errors'); } @@ -306,14 +306,14 @@ if (GETPOST('actioncancel', 'alpha')) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } $sql = "DELETE from ".$tabname[$id]." WHERE ".$rowidcol."='".$rowid."'"; dol_syslog("delete", LOG_DEBUG); $result = $db->query($sql); - if (! $result) + if (!$result) { if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') { @@ -329,8 +329,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$rowid."'"; @@ -349,8 +349,8 @@ if ($action == $acts[0]) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$rowid."'"; @@ -369,8 +369,8 @@ if ($action == $acts[1]) // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$rowid."'"; @@ -389,8 +389,8 @@ if ($action == 'activate_favorite') // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$rowid."'"; @@ -412,12 +412,12 @@ if ($action == 'disable_favorite') */ $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); llxHeader(); -$titre=$langs->trans($tablib[$id]); -$linkback=''; +$titre = $langs->trans($tablib[$id]); +$linkback = ''; print load_fiche_titre($titre, $linkback, 'title_accountancy'); @@ -425,7 +425,7 @@ print load_fiche_titre($titre, $linkback, 'title_accountancy'); // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.urlencode($page).'&':'').'sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder).'&rowid='.urlencode($rowid).'&code='.urlencode($code).'&id='.urlencode($id), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.urlencode($page).'&' : '').'sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder).'&rowid='.urlencode($rowid).'&code='.urlencode($code).'&id='.urlencode($id), $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -435,22 +435,22 @@ if ($action == 'delete') if ($id) { // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; + $sql = $tabsql[$id]; if ($search_country_id > 0) { - if (preg_match('/ WHERE /', $sql)) $sql.= " AND "; - else $sql.=" WHERE "; - $sql.= " c.rowid = ".$search_country_id; + if (preg_match('/ WHERE /', $sql)) $sql .= " AND "; + else $sql .= " WHERE "; + $sql .= " c.rowid = ".$search_country_id; } // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield='country_code'; - $sql.=$db->order($sortfield, $sortorder); - $sql.=$db->plimit($listlimit+1, $offset); + if ($sortfield == 'country') $sortfield = 'country_code'; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($listlimit + 1, $offset); //print $sql; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); print '
'; print ''; @@ -461,10 +461,10 @@ if ($id) // Form to add a new line if ($tabname[$id]) { - $alabelisused=0; - $var=false; + $alabelisused = 0; + $var = false; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); // Line for title print ''; @@ -472,33 +472,33 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $class="left"; - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $class = "left"; + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { - $valuetoshow=$langs->trans("Label"); + $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field]=='country') { + if ($fieldlist[$field] == 'country') { if (in_array('region_id', $fieldlist)) { print ' '; continue; } // For region page, we do not show the country input - $valuetoshow=$langs->trans("Country"); + $valuetoshow = $langs->trans("Country"); } - if ($fieldlist[$field]=='country_id') { $valuetoshow=''; } - if ($fieldlist[$field]=='pcg_version' || $fieldlist[$field]=='fk_pcg_version') { $valuetoshow=$langs->trans("Pcg_version"); } + if ($fieldlist[$field] == 'country_id') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } if ($valuetoshow != '') { print ''; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) { + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) { print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - } elseif (! empty($tabhelp[$id][$value])) { + } elseif (!empty($tabhelp[$id][$value])) { print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); } else { print $valuetoshow; } print ''; } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; @@ -518,14 +518,14 @@ if ($id) foreach ($fieldlist as $key=>$val) { if (GETPOST($val)) - $obj->$val=GETPOST($val); + $obj->$val = GETPOST($val); } } $tmpaction = 'create'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { @@ -537,32 +537,32 @@ if ($id) print ''; print ""; - $colspan=count($fieldlist)+3; + $colspan = count($fieldlist) + 3; - print ' '; // Keep   to have a line with enough height + print ' '; // Keep   to have a line with enough height } // List of available values in database dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; $param = '&id='.$id; - if ($search_country_id > 0) $param.= '&search_country_id='.$search_country_id; + if ($search_country_id > 0) $param .= '&search_country_id='.$search_country_id; $paramwithsearch = $param; - if ($sortorder) $paramwithsearch.= '&sortorder='.$sortorder; - if ($sortfield) $paramwithsearch.= '&sortfield='.$sortfield; + if ($sortorder) $paramwithsearch .= '&sortorder='.$sortorder; + if ($sortfield) $paramwithsearch .= '&sortfield='.$sortfield; // There is several pages if ($num > $listlimit) { - print ''; - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print ''; + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); print ''; } @@ -570,9 +570,9 @@ if ($id) print ''; foreach ($fieldlist as $field => $value) { - $showfield=1; // By defaut + $showfield = 1; // By defaut - if ($fieldlist[$field]=='region_id' || $fieldlist[$field]=='country_id') { $showfield=0; } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } if ($showfield) { @@ -590,17 +590,17 @@ if ($id) } print ''; print ''; - $searchpicto=$form->showFilterAndCheckAddButtons(0); + $searchpicto = $form->showFilterAndCheckAddButtons(0); print $searchpicto; print ''; print ''; // Title of lines print ''; - print getTitleFieldOfList($langs->trans("Pcg_version"), 0, $_SERVER["PHP_SELF"], "pcg_version", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, ''); - print getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], "label", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, ''); - print getTitleFieldOfList($langs->trans("Country"), 0, $_SERVER["PHP_SELF"], "country_code", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, ''); - print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page?'page='.$page.'&':''), $param, '', $sortfield, $sortorder, 'center '); + print getTitleFieldOfList($langs->trans("Pcg_version"), 0, $_SERVER["PHP_SELF"], "pcg_version", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, ''); + print getTitleFieldOfList($langs->trans("Label"), 0, $_SERVER["PHP_SELF"], "label", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, ''); + print getTitleFieldOfList($langs->trans("Country"), 0, $_SERVER["PHP_SELF"], "country_code", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, ''); + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, 'center '); print getTitleFieldOfList(''); print getTitleFieldOfList(''); print ''; @@ -613,81 +613,81 @@ if ($id) $obj = $db->fetch_object($resql); //print_r($obj); print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) { print ''; print ''; print ''; print ''; - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) fieldListAccountModel($fieldlist, $obj, $tabname[$id], 'edit'); - print ' '; + print ' '; print ' '; } else { $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { foreach ($fieldlist as $field => $value) { - $showfield=1; - $class="left"; - $valuetoshow=$obj->{$fieldlist[$field]}; + $showfield = 1; + $class = "left"; + $valuetoshow = $obj->{$fieldlist[$field]}; if ($value == 'type_template') { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; } if ($value == 'element') { - $valuetoshow = isset($elementList[$valuetoshow])?$elementList[$valuetoshow]:$valuetoshow; + $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; } elseif ($value == 'source') { - $valuetoshow = isset($sourceList[$valuetoshow])?$sourceList[$valuetoshow]:$valuetoshow; + $valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow; } - elseif ($valuetoshow=='all') { - $valuetoshow=$langs->trans('All'); + elseif ($valuetoshow == 'all') { + $valuetoshow = $langs->trans('All'); } - elseif ($fieldlist[$field]=='country') { + elseif ($fieldlist[$field] == 'country') { if (empty($obj->country_code)) { - $valuetoshow='-'; + $valuetoshow = '-'; } else { - $key=$langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow=($key != "Country".strtoupper($obj->country_code)?$obj->country_code." - ".$key:$obj->country); + $key = $langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); } } - elseif ($fieldlist[$field]=='country_id') { - $showfield=0; + elseif ($fieldlist[$field] == 'country_id') { + $showfield = 0; } - $class='tddict'; - if ($fieldlist[$field] == 'tracking') $class.=' tdoverflowauto'; + $class = 'tddict'; + if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto'; // Show value for field if ($showfield) print ''.$valuetoshow.''; } } // Can an entry be erased or disabled ? - $iserasable=1;$canbedisabled=1;$canbemodified=1; // true by default + $iserasable = 1; $canbedisabled = 1; $canbemodified = 1; // true by default - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):''); + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); if ($param) $url .= '&'.$param; - $url.='&'; + $url .= '&'; // Active print ''; @@ -737,10 +737,10 @@ $db->close(); */ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context = '') { - global $conf,$langs,$db; + global $conf, $langs, $db; global $form; global $region_id; - global $elementList,$sourceList; + global $elementList, $sourceList; $formadmin = new FormAdmin($db); $formcompany = new FormCompany($db); @@ -758,15 +758,15 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context = continue; } // For state page, we do not show the country input (we link to region, not country) print ''; - $fieldname='country'; - print $form->select_country((! empty($obj->country_code)?$obj->country_code:(! empty($obj->country)?$obj->country:'')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); + $fieldname = 'country'; + print $form->select_country((!empty($obj->country_code) ? $obj->country_code : (!empty($obj->country) ? $obj->country : '')), $fieldname, '', 28, 'maxwidth200 maxwidthonsmartphone'); print ''; } elseif ($fieldlist[$field] == 'country_id') { - if (! in_array('country', $fieldlist)) // If there is already a field country, we don't show country_id (avoid duplicate) + if (!in_array('country', $fieldlist)) // If there is already a field country, we don't show country_id (avoid duplicate) { - $country_id = (! empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0); + $country_id = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]} : 0); print ''; print ''; print ''; @@ -776,24 +776,24 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context = if ($fieldlist[$field] == 'type_cdr') print ''; else print ''; if ($fieldlist[$field] == 'type_cdr') { - print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:'')); + print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'')); } else { - print $form->selectyesno($fieldlist[$field], (! empty($obj->{$fieldlist[$field]})?$obj->{$fieldlist[$field]}:''), 1); + print $form->selectyesno($fieldlist[$field], (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''), 1); } print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { - print ''; + print ''; } else { print ''; - $size=''; $class=''; - if ($fieldlist[$field]=='code') $size='size="8" '; - if ($fieldlist[$field]=='position') $size='size="4" '; - if ($fieldlist[$field]=='libelle') $size='centpercent'; - if ($fieldlist[$field]=='sortorder' || $fieldlist[$field]=='sens' || $fieldlist[$field]=='category_type') $size='size="2" '; - print ''; + $size = ''; $class = ''; + if ($fieldlist[$field] == 'code') $size = 'size="8" '; + if ($fieldlist[$field] == 'position') $size = 'size="4" '; + if ($fieldlist[$field] == 'libelle') $size = 'centpercent'; + if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') $size = 'size="2" '; + print ''; print ''; } } diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index f2bc1907c7c..7449750f958 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -92,7 +92,6 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $object->fk_pcg_version = $obj->pcg_version; $object->pcg_type = GETPOST('pcg_type', 'alpha'); - $object->pcg_subtype = GETPOST('pcg_subtype', 'alpha'); $object->account_number = $account_number; $object->account_parent = $account_parent; $object->account_category = GETPOST('account_category', 'alpha'); @@ -158,7 +157,6 @@ if ($action == 'add' && $user->rights->accounting->chartofaccount) $object->fk_pcg_version = $obj->pcg_version; $object->pcg_type = GETPOST('pcg_type', 'alpha'); - $object->pcg_subtype = GETPOST('pcg_subtype', 'alpha'); $object->account_number = $account_number; $object->account_parent = $account_parent; $object->account_category = GETPOST('account_category', 'alpha'); @@ -260,12 +258,6 @@ if ($action == 'create') { print ''; print ''; - // Chart of accounts subtype - print ''.$langs->trans("Pcgsubtype").''; - print ''; - print ''; - print ''; - print ''; dol_fiche_end(); @@ -329,12 +321,6 @@ elseif ($id > 0 || $ref) { print ''; print ''; - // Chart of accounts subtype - print ''.$langs->trans("Pcgsubtype").''; - print ''; - print ''; - print ''; - print ''; dol_fiche_end(); @@ -383,10 +369,6 @@ elseif ($id > 0 || $ref) { print ''.$langs->trans("Pcgtype").''; print ''.$object->pcg_type.''; - // Chart of accounts subtype - print ''.$langs->trans("Pcgsubtype").''; - print ''.$object->pcg_subtype.''; - print ''; print ''; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index dbe20bba99d..500a0d3cbba 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -56,7 +56,7 @@ $active = 1; $sortfield = GETPOST("sortfield", 'aZ09comma'); $sortorder = GETPOST("sortorder", 'aZ09comma'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page; $pageprev = $page - 1; @@ -153,7 +153,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($value == 'formula' && empty($_POST['formula'])) continue; if ($value == 'range_account' && empty($_POST['range_account'])) continue; if ($value == 'country' || $value == 'country_id') continue; - if (!isset($_POST[$value]) || $_POST[$value] == '') + if (!GETPOSTISSET($value) || GETPOST($value) == '') { $ok = 0; $fieldnamekey = $listfield[$f]; @@ -677,9 +677,6 @@ if ($id) } if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); - } - if ($fieldlist[$field] == 'pcg_subtype') { - $valuetoshow = $langs->trans("Pcg_subtype"); } if ($fieldlist[$field] == 'type_template') { $valuetoshow = $langs->trans("TypeOfTemplate"); diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 611aa8fc321..ad22a88f415 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2019 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2014-2015 Ari Elbaz (elarifr) * Copyright (C) 2014 Marcos García * Copyright (C) 2014 Juanjo Menent @@ -46,27 +46,35 @@ if (empty($user->rights->accounting->chartofaccount)) $action = GETPOST('action', 'aZ09'); -$list_account_main = array ( +$list_account_main = array( 'ACCOUNTING_ACCOUNT_CUSTOMER', 'ACCOUNTING_ACCOUNT_SUPPLIER', 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', ); -$list_account = array (); +$list_account = array(); $list_account[] = '---Product---'; -$list_account[] = 'ACCOUNTING_PRODUCT_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT'; if ($mysoc->isInEEC()) { $list_account[] = 'ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT'; } $list_account[] = 'ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT'; +$list_account[] = 'ACCOUNTING_PRODUCT_BUY_ACCOUNT'; +if ($mysoc->isInEEC()) { + $list_account[] = 'ACCOUNTING_PRODUCT_BUY_INTRA_ACCOUNT'; +} +$list_account[] = 'ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT'; $list_account[] = '---Service---'; -$list_account[] = 'ACCOUNTING_SERVICE_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_SERVICE_SOLD_ACCOUNT'; if ($mysoc->isInEEC()) { $list_account[] = 'ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT'; } $list_account[] = 'ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT'; +$list_account[] = 'ACCOUNTING_SERVICE_BUY_ACCOUNT'; +if ($mysoc->isInEEC()) { + $list_account[] = 'ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT'; +} +$list_account[] = 'ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT'; $list_account[] = '---Other---'; $list_account[] = 'ACCOUNTING_VAT_BUY_ACCOUNT'; $list_account[] = 'ACCOUNTING_VAT_SOLD_ACCOUNT'; @@ -112,25 +120,25 @@ if ($action == 'update') { foreach ($list_account_main as $constname) { $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; } } foreach ($list_account as $constname) { - $reg=array(); + $reg = array(); if (preg_match('/---(.*)---/', $constname, $reg)) { // This is a separator continue; } $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error ++; + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; } } - if (! $error) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { setEventMessages($langs->trans("Error"), null, 'errors'); @@ -161,6 +169,7 @@ print ''; // Define main accounts for thirdparty print ''; +print ''; foreach ($list_account_main as $key) { print ''; @@ -180,17 +189,8 @@ foreach ($list_account_main as $key) { } -print "
'.$langs->trans("ThirdParties").' | '.$langs->trans("Users").'
\n"; - - -print '
'; - -// Define default accounts - -print ''; - foreach ($list_account as $key) { - $reg=array(); + $reg = array(); if (preg_match('/---(.*)---/', $key, $reg)) { print ''; } @@ -198,9 +198,9 @@ foreach ($list_account as $key) { print ''; // Param $label = $langs->trans($key); - print ''; + print ''; // Value - print ''; print ''; diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php index edc73688389..b2262c603f9 100644 --- a/htdocs/accountancy/admin/export.php +++ b/htdocs/accountancy/admin/export.php @@ -134,13 +134,13 @@ if ($action == 'update') { $form = new Form($db); -$title = $langs->trans('ConfigAccountingExpert'); +$title = $langs->trans('ExportOptions'); llxHeader('', $title); $linkback = ''; // $linkback = '' . $langs->trans("BackToModuleList") . ''; -print load_fiche_titre($langs->trans('ConfigAccountingExpert'), $linkback, 'accountancy'); +print load_fiche_titre($langs->trans('ExportOptions'), $linkback, 'accountancy'); print "\n".''; print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $button, $result, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit); @@ -228,7 +237,7 @@ if ($action != 'export_csv') print '
'.$langs->trans($reg[1]).'
' . $label . ''.$label.''; // Do not force class=right, or it align also the content of the select box + print ''; // Do not force class=right, or it align also the content of the select box print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); print '
'; print ''; - print ''; print_liste_field_titre("AccountAccounting", $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre("OpeningBalance", $_SERVER['PHP_SELF'], "", $param, "", 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Debit", $_SERVER['PHP_SELF'], "t.debit", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Credit", $_SERVER['PHP_SELF'], "t.credit", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Balance", $_SERVER["PHP_SELF"], "", $param, "", 'class="right"', $sortfield, $sortorder); @@ -257,6 +267,16 @@ if ($action != 'export_csv') $sous_total_credit = 0; $displayed_account = ""; + $sql = "select t.numero_compte, (SUM(t.debit) - SUM(t.credit)) as opening_balance from ".MAIN_DB_PREFIX."accounting_bookkeeping as t where entity in ".$conf->entity; + $sql .= " AND t.doc_date < '".$db->idate($search_date_start)."' GROUP BY t.numero_compte"; + $resql = $db->query($sql); + $nrows = $resql->num_rows; + $opening_balances = array(); + for ($i = 0; $i < $nrows; $i++) { + $arr = $resql->fetch_array(); + $opening_balances["'".$arr['numero_compte']."'"] = $arr['opening_balance']; + } + foreach ($object->lines as $line) { $link = ''; @@ -274,14 +294,14 @@ if ($action != 'export_csv') { // Affiche un Sous-Total par compte comptable if ($displayed_account != "") { - print ''; + print ''; print "\n"; print ''; } // Show first line of a break print ''; - print ''; + print ''; print ''; $displayed_account = $root_account_description; @@ -293,6 +313,7 @@ if ($action != 'export_csv') print ''; print ''; + print ''; print ''; print ''; print ''; @@ -305,11 +326,11 @@ if ($action != 'export_csv') $sous_total_credit += $line->credit; } - print ''; + print ''; print "\n"; print ''; - print ''; + print ''; print "\n"; print ''; diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index bd5b780a0b6..e50112f7ff1 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -29,6 +29,7 @@ require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountancyexport.class.php'; 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.formfile.class.php'; 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'; @@ -92,7 +93,7 @@ $search_not_reconciled = GETPOST('search_reconciled_option', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; @@ -203,7 +204,7 @@ if (empty($reshook)) $search_debit = ''; $search_credit = ''; $search_lettering_code = ''; - $search_not_reconciled=''; + $search_not_reconciled = ''; } // Must be after the remove filter action, before the export. @@ -275,32 +276,32 @@ if (empty($reshook)) if (!empty($search_date_creation_start)) { $filter['t.date_creation>='] = $search_date_creation_start; $tmp = dol_getdate($search_date_creation_start); - $param .= '&date_creation_startmonth=' . urlencode($tmp['mon']) . '&date_creation_startday=' . urlencode($tmp['mday']) . '&date_creation_startyear=' . urlencode($tmp['year']); + $param .= '&date_creation_startmonth='.urlencode($tmp['mon']).'&date_creation_startday='.urlencode($tmp['mday']).'&date_creation_startyear='.urlencode($tmp['year']); } if (!empty($search_date_creation_end)) { $filter['t.date_creation<='] = $search_date_creation_end; $tmp = dol_getdate($search_date_creation_end); - $param .= '&date_creation_endmonth=' .urlencode($tmp['mon']) . '&date_creation_endday=' . urlencode($tmp['mday']) . '&date_creation_endyear=' . urlencode($tmp['year']); + $param .= '&date_creation_endmonth='.urlencode($tmp['mon']).'&date_creation_endday='.urlencode($tmp['mday']).'&date_creation_endyear='.urlencode($tmp['year']); } if (!empty($search_date_modification_start)) { $filter['t.tms>='] = $search_date_modification_start; $tmp = dol_getdate($search_date_modification_start); - $param .= '&date_modification_startmonth=' . urlencode($tmp['mon']) . '&date_modification_startday=' . urlencode($tmp['mday']) . '&date_modification_startyear=' . urlencode($tmp['year']); + $param .= '&date_modification_startmonth='.urlencode($tmp['mon']).'&date_modification_startday='.urlencode($tmp['mday']).'&date_modification_startyear='.urlencode($tmp['year']); } if (!empty($search_date_modification_end)) { $filter['t.tms<='] = $search_date_modification_end; $tmp = dol_getdate($search_date_modification_end); - $param .= '&date_modification_endmonth=' . urlencode($tmp['mon']) . '&date_modification_endday=' . urlencode($tmp['mday']) . '&date_modification_endyear=' . urlencode($tmp['year']); + $param .= '&date_modification_endmonth='.urlencode($tmp['mon']).'&date_modification_endday='.urlencode($tmp['mday']).'&date_modification_endyear='.urlencode($tmp['year']); } if (!empty($search_date_export_start)) { $filter['t.date_export>='] = $search_date_export_start; $tmp = dol_getdate($search_date_export_start); - $param .= '&date_export_startmonth=' . urlencode($tmp['mon']) . '&date_export_startday=' . urlencode($tmp['mday']) . '&date_export_startyear=' . urlencode($tmp['year']); + $param .= '&date_export_startmonth='.urlencode($tmp['mon']).'&date_export_startday='.urlencode($tmp['mday']).'&date_export_startyear='.urlencode($tmp['year']); } if (!empty($search_date_export_end)) { $filter['t.date_export<='] = $search_date_export_end; $tmp = dol_getdate($search_date_export_end); - $param .= '&date_export_endmonth=' . urlencode($tmp['mon']) . '&date_export_endday=' . urlencode($tmp['mday']) . '&date_export_endyear=' . urlencode($tmp['year']); + $param .= '&date_export_endmonth='.urlencode($tmp['mon']).'&date_export_endday='.urlencode($tmp['mday']).'&date_export_endyear='.urlencode($tmp['year']); } if (!empty($search_debit)) { $filter['t.debit'] = $search_debit; @@ -314,9 +315,9 @@ if (empty($reshook)) $filter['t.lettering_code'] = $search_lettering_code; $param .= '&search_lettering_code='.urlencode($search_lettering_code); } - if (! empty($search_not_reconciled)) { + if (!empty($search_not_reconciled)) { $filter['t.reconciled_option'] = $search_not_reconciled; - $param .= '&search_not_reconciled=' . urlencode($search_not_reconciled); + $param .= '&search_not_reconciled='.urlencode($search_not_reconciled); } } @@ -538,6 +539,7 @@ if ($action == 'export_file' && $user->rights->accounting->mouvements->export) { */ $formother = new FormOther($db); +$formfile = new FormFile($db); $title_page = $langs->trans("Bookkeeping"); @@ -766,7 +768,7 @@ if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; } // Code journal @@ -914,7 +916,69 @@ while ($i < min($num, $limit)) // Document ref if (!empty($arrayfields['t.doc_ref']['checked'])) { - print ''; + if ($line->doc_type == 'customer_invoice') + { + $langs->loadLangs(array('bills')); + + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $objectstatic = new Facture($db); + $objectstatic->fetch($line->fk_doc); + //$modulepart = 'facture'; + + $filename = dol_sanitizeFileName($line->doc_ref); + $filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; + $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + } + elseif ($line->doc_type == 'supplier_invoice') + { + $langs->loadLangs(array('bills')); + + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $objectstatic = new FactureFournisseur($db); + $objectstatic->fetch($line->fk_doc); + //$modulepart = 'invoice_supplier'; + + $filename = dol_sanitizeFileName($line->doc_ref); + $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($line->fk_doc, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref); + $subdir = get_exdir($objectstatic->id, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref); + $documentlink = $formfile->getDocumentsLink($objectstatic->element, $subdir, $filedir); + } + elseif ($line->doc_type == 'expense_report') + { + $langs->loadLangs(array('trips')); + + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $objectstatic = new ExpenseReport($db); + $objectstatic->fetch($line->fk_doc); + //$modulepart = 'expensereport'; + + $filename = dol_sanitizeFileName($line->doc_ref); + $filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); + $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; + $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); + } + else + { + // Other type + } + + print '\n"; if (!$i) $totalarray['nbfield']++; } diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index 2cb28b59584..bb6f95d9047 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -62,7 +62,7 @@ $search_credit = GETPOST('search_credit', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index 91ce9f5e31a..1dfb324599c 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -47,7 +47,7 @@ $socid = GETPOST('socid', 'int')?GETPOST('socid', 'int'):GETPOST('id', 'int $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == - 1) { $page = 0; } // If $page is not defined, or '' or -1 diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index 867f5303ff8..5a5a4d36c21 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -46,7 +46,7 @@ $socid = GETPOST('socid', 'int')?GETPOST('socid', 'int'):GETPOST('id', 'int $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == - 1) { $page = 0; } // If $page is not defined, or '' or -1 diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 46d3feae5b2..6c628ae52c3 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -54,6 +54,7 @@ class AccountancyExport public static $EXPORT_TYPE_QUADRATUS = 60; public static $EXPORT_TYPE_OPENCONCERTO = 100; public static $EXPORT_TYPE_LDCOMPTA = 110; + public static $EXPORT_TYPE_LDCOMPTA10 = 120; public static $EXPORT_TYPE_FEC = 1000; @@ -110,8 +111,9 @@ class AccountancyExport self::$EXPORT_TYPE_OPENCONCERTO => $langs->trans('Modelcsv_openconcerto'), self::$EXPORT_TYPE_SAGE50_SWISS => $langs->trans('Modelcsv_Sage50_Swiss'), self::$EXPORT_TYPE_LDCOMPTA => $langs->trans('Modelcsv_LDCompta'), + self::$EXPORT_TYPE_LDCOMPTA10 => $langs->trans('Modelcsv_LDCompta10'), self::$EXPORT_TYPE_FEC => $langs->trans('Modelcsv_FEC'), - self::$EXPORT_TYPE_CHARLEMAGNE => $langs->trans('Modelcsv_charlemagne'), + self::$EXPORT_TYPE_CHARLEMAGNE => $langs->trans('Modelcsv_charlemagne'), ); ksort($listofexporttypes, SORT_NUMERIC); @@ -140,6 +142,7 @@ class AccountancyExport self::$EXPORT_TYPE_OPENCONCERTO => 'openconcerto', self::$EXPORT_TYPE_SAGE50_SWISS => 'sage50ch', self::$EXPORT_TYPE_LDCOMPTA => 'ldcompta', + self::$EXPORT_TYPE_LDCOMPTA10 => 'ldcompta10', self::$EXPORT_TYPE_FEC => 'fec', ); @@ -201,6 +204,10 @@ class AccountancyExport self::$EXPORT_TYPE_LDCOMPTA => array( 'label' => $langs->trans('Modelcsv_LDCompta'), 'ACCOUNTING_EXPORT_FORMAT' => 'csv', + ), + self::$EXPORT_TYPE_LDCOMPTA10 => array( + 'label' => $langs->trans('Modelcsv_LDCompta10'), + 'ACCOUNTING_EXPORT_FORMAT' => 'csv', ), self::$EXPORT_TYPE_FEC => array( 'label' => $langs->trans('Modelcsv_FEC'), @@ -239,6 +246,7 @@ class AccountancyExport $filename = 'general_ledger-'.$this->getFormatCode($formatexportset); $type_export = 'general_ledger'; + global $db; // The tpl file use $db include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php'; @@ -279,6 +287,9 @@ class AccountancyExport case self::$EXPORT_TYPE_LDCOMPTA : $this->exportLDCompta($TData); break; + case self::$EXPORT_TYPE_LDCOMPTA10 : + $this->exportLDCompta10($TData); + break; case self::$EXPORT_TYPE_FEC : $this->exportFEC($TData); break; @@ -920,7 +931,7 @@ class AccountancyExport /** * Export format : LD Compta version 9 & higher - * http://www.ldsysteme.fr/fileadmin/telechargement/np/ldcompta/Documentation/IntCptW10.pdf + * http://www.ldsysteme.fr/fileadmin/telechargement/np/ldcompta/Documentation/IntCptW9.pdf * * @param array $objectLines data * @@ -935,6 +946,7 @@ class AccountancyExport foreach ($objectLines as $line) { $date_document = dol_print_date($line->doc_date, '%Y%m%d'); $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); + $date_lim_reglement = dol_print_date($line->date_lim_reglement, '%Y%m%d'); // TYPE $type_enregistrement = 'E'; // For write movement @@ -950,7 +962,7 @@ class AccountancyExport // LIBE print $line->label_operation.$separator; // DATH - print $line->date_lim_reglement.$separator; + print $date_lim_reglement.$separator; // CNPI if ($line->doc_type == 'supplier_invoice') { if ($line->montant < 0) { @@ -969,21 +981,19 @@ class AccountancyExport } print $nature_piece.$separator; // RACI - /* - if (! empty($line->subledger_account)) { - if ($line->doc_type == 'supplier_invoice') { - $racine_subledger_account = '40'; - } elseif ($line->doc_type == 'customer_invoice') { - $racine_subledger_account = '41'; - } else { - $nature_piece = ''; - } - print $racine_subledger_account . $separator; - } else { - print $separator; - } - */ - print $separator; // deprecated CPTG & CPTA use instead + // if (! empty($line->subledger_account)) { + // if ($line->doc_type == 'supplier_invoice') { + // $racine_subledger_account = '40'; + // } elseif ($line->doc_type == 'customer_invoice') { + // $racine_subledger_account = '41'; + // } else { + // $racine_subledger_account = ''; + // } + // } else { + $racine_subledger_account = ''; // for records of type E leave this field blank + // } + + print $racine_subledger_account.$separator; // deprecated CPTG & CPTA use instead // MONT print price(abs($line->montant), 0, '', 1, 2).$separator; // CODC @@ -1051,6 +1061,273 @@ class AccountancyExport } } + /** + * Export format : LD Compta version 10 & higher + * http://www.ldsysteme.fr/fileadmin/telechargement/np/ldcompta/Documentation/IntCptW10.pdf + * + * @param array $objectLines data + * + * @return void + */ + public function exportLDCompta10($objectLines) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; + + $separator = ';'; + $end_line = "\r\n"; + $last_codeinvoice = ''; + + foreach ($objectLines as $line) { + // TYPE C + if($last_codeinvoice != $line->doc_ref){ + //recherche societe en fonction de son code client + $sql = "SELECT code_client, fk_forme_juridique, nom, address, zip, town, fk_pays, phone, siret FROM ".MAIN_DB_PREFIX."societe WHERE code_client = '".$line->thirdparty_code ."'"; + $resql = $this->db->query($sql); + + if($resql && $this->db->num_rows($resql)>0) + { + $soc = $this->db->fetch_object($resql); + + $address=array('','',''); + if (strpos($soc->address, "\n")!==false) { + $address = explode("\n", $soc->address); + if (is_array($address) && count($address)>0) { + foreach($address as $key=>$data) { + $address[$key]=str_replace(array("\t", "\n", "\r"), "", $data); + $address[$key]=dol_trunc($address[$key], 40, 'right', 'UTF-8', 1); + } + } + } else { + $address[0] = substr(str_replace(array("\t", "\r"), " ", $soc->address), 0, 40); + $address[1] = substr(str_replace(array("\t", "\r"), " ", $soc->address), 41, 40); + $address[2] = substr(str_replace(array("\t", "\r"), " ", $soc->address), 82, 40); + } + + $type_enregistrement = 'C'; + //TYPE + print $type_enregistrement.$separator; + //NOCL + print $soc->code_client.$separator; + //NMCM + print $separator; + //LIBI + print $separator; + //TITR + print $separator; + //RSSO + print $soc->nom.$separator; + //CAD1 + print $address[0].$separator; + //CAD2 + print $address[1].$separator; + //CAD3 + print $address[2].$separator; + //COPO + print $soc->zip.$separator; + //BUDI + print substr($soc->town, 0, 40).$separator; + //CPAY + print $separator; + //PAYS + print substr(getCountry($soc->fk_pays), 0, 40).$separator; + //NTEL + print $soc->phone.$separator; + //TLEX + print $separator; + //TLPO + print $separator; + //TLCY + print $separator; + //NINT + print $separator; + //COMM + print $separator; + //SIRE + print str_replace(" ", "", $soc->siret).$separator; + //RIBP + print $separator; + //DOBQ + print $separator; + //IBBQ + print $separator; + //COBQ + print $separator; + //GUBQ + print $separator; + //CPBQ + print $separator; + //CLBQ + print $separator; + //BIBQ + print $separator; + //MOPM + print $separator; + //DJPM + print $separator; + //DMPM + print $separator; + //REFM + print $separator; + //SLVA + print $separator; + //PLCR + print $separator; + //ECFI + print $separator; + //CREP + print $separator; + //NREP + print $separator; + //TREP + print $separator; + //MREP + print $separator; + //GRRE + print $separator; + //LTTA + print $separator; + //CACT + print $separator; + //CODV + print $separator; + //GRTR + print $separator; + //NOFP + print $separator; + //BQAF + print $separator; + //BONP + print $separator; + //CESC + print $separator; + + print $end_line; + } + } + + $date_document = dol_print_date($line->doc_date, '%Y%m%d'); + $date_creation = dol_print_date($line->date_creation, '%Y%m%d'); + $date_lim_reglement = dol_print_date($line->date_lim_reglement, '%Y%m%d'); + + // TYPE E + $type_enregistrement = 'E'; // For write movement + print $type_enregistrement.$separator; + // JNAL + print substr($line->code_journal, 0, 2).$separator; + // NECR + print $line->id.$separator; + // NPIE + print $line->piece_num.$separator; + // DATP + print $date_document.$separator; + // LIBE + print dol_trunc($line->label_operation, 25, 'right', 'UTF-8', 1).$separator; + // DATH + print $date_lim_reglement.$separator; + // CNPI + if ($line->doc_type == 'supplier_invoice') { + if ($line->montant < 0) { + $nature_piece = 'AF'; + } else { + $nature_piece = 'FF'; + } + } elseif ($line->doc_type == 'customer_invoice') { + if ($line->montant < 0) { + $nature_piece = 'AC'; + } else { + $nature_piece = 'FC'; + } + } else { + $nature_piece = ''; + } + print $nature_piece.$separator; + // RACI + // if (! empty($line->subledger_account)) { + // if ($line->doc_type == 'supplier_invoice') { + // $racine_subledger_account = '40'; + // } elseif ($line->doc_type == 'customer_invoice') { + // $racine_subledger_account = '41'; + // } else { + // $racine_subledger_account = ''; + // } + // } else { + $racine_subledger_account = ''; // for records of type E leave this field blank + // } + + print $racine_subledger_account . $separator; // deprecated CPTG & CPTA use instead + // MONT + print price(abs($line->montant), 0, '', 1, 2).$separator; + // CODC + print $line->sens.$separator; + // CPTG + print length_accountg($line->numero_compte).$separator; + // DATE + print $date_document.$separator; + // CLET + print $line->lettering_code.$separator; + // DATL + print $line->date_lettering.$separator; + // CPTA + if (!empty($line->subledger_account)) { + print length_accounta($line->subledger_account).$separator; + } else { + print $separator; + } + // CNAT + if ($line->doc_type == 'supplier_invoice' && !empty($line->subledger_account)) { + print 'F'.$separator; + } elseif ($line->doc_type == 'customer_invoice' && !empty($line->subledger_account)) { + print 'C'.$separator; + } else { + print $separator; + } + // CTRE + print $separator; + // NORL + print $separator; + // DATV + print $separator; + // REFD + print $line->doc_ref.$separator; + // NECA + print '0'.$separator; + // CSEC + print $separator; + // CAFF + print $separator; + // CDES + print $separator; + // QTUE + print $separator; + // MTDV + print '0'.$separator; + // CODV + print $separator; + // TXDV + print '0'.$separator; + // MOPM + print $separator; + // BONP + print $separator; + // BQAF + print $separator; + // ECES + print $separator; + // TXTL + print $separator; + // ECRM + print $separator; + // DATK + print $separator; + // HEUK + print $separator; + + print $end_line; + + $last_codeinvoice = $line->doc_ref; + } + } + /** * Export format : Charlemagne * diff --git a/htdocs/accountancy/class/accountancysystem.class.php b/htdocs/accountancy/class/accountancysystem.class.php index c59e87dfd93..02d5f0bb183 100644 --- a/htdocs/accountancy/class/accountancysystem.class.php +++ b/htdocs/accountancy/class/accountancysystem.class.php @@ -53,11 +53,6 @@ class AccountancySystem */ public $pcg_type; - /** - * @var string pcg subtype - */ - public $pcg_subtype; - /** * @var string Accountancy System numero */ diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php index 1fc953af959..58e6bd600f6 100644 --- a/htdocs/accountancy/class/accountingaccount.class.php +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -90,11 +90,6 @@ class AccountingAccount extends CommonObject */ public $pcg_type; - /** - * @var string pcg subtype - */ - public $pcg_subtype; - /** * @var string account number */ @@ -140,6 +135,11 @@ class AccountingAccount extends CommonObject */ public $active; + /** + * @var int reconcilable + */ + public $reconcilable; + /** * Constructor * @@ -167,7 +167,7 @@ class AccountingAccount extends CommonObject global $conf; if ($rowid || $account_number) { - $sql = "SELECT a.rowid as rowid, a.datec, a.tms, a.fk_pcg_version, a.pcg_type, a.pcg_subtype, a.account_number, a.account_parent, a.label, a.labelshort, a.fk_accounting_category, a.fk_user_author, a.fk_user_modif, a.active"; + $sql = "SELECT a.rowid as rowid, a.datec, a.tms, a.fk_pcg_version, a.pcg_type, a.account_number, a.account_parent, a.label, a.labelshort, a.fk_accounting_category, a.fk_user_author, a.fk_user_modif, a.active, a.reconcilable"; $sql .= ", ca.label as category_label"; $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as ca ON a.fk_accounting_category = ca.rowid"; @@ -198,7 +198,6 @@ class AccountingAccount extends CommonObject $this->tms = $obj->tms; $this->fk_pcg_version = $obj->fk_pcg_version; $this->pcg_type = $obj->pcg_type; - $this->pcg_subtype = $obj->pcg_subtype; $this->account_number = $obj->account_number; $this->account_parent = $obj->account_parent; $this->label = $obj->label; @@ -209,6 +208,7 @@ class AccountingAccount extends CommonObject $this->fk_user_modif = $obj->fk_user_modif; $this->active = $obj->active; $this->status = $obj->active; + $this->reconcilable = $obj->reconcilable; return $this->id; } else { @@ -240,8 +240,6 @@ class AccountingAccount extends CommonObject $this->fk_pcg_version = trim($this->fk_pcg_version); if (isset($this->pcg_type)) $this->pcg_type = trim($this->pcg_type); - if (isset($this->pcg_subtype)) - $this->pcg_subtype = trim($this->pcg_subtype); if (isset($this->account_number)) $this->account_number = trim($this->account_number); if (isset($this->label)) @@ -253,10 +251,6 @@ class AccountingAccount extends CommonObject { $this->pcg_type = 'XXXXXX'; } - if (empty($this->pcg_subtype) || $this->pcg_subtype == '-1') - { - $this->pcg_subtype = 'XXXXXX'; - } // Check parameters // Put here code to add control on parameters values @@ -266,7 +260,6 @@ class AccountingAccount extends CommonObject $sql .= ", entity"; $sql .= ", fk_pcg_version"; $sql .= ", pcg_type"; - $sql .= ", pcg_subtype"; $sql .= ", account_number"; $sql .= ", account_parent"; $sql .= ", label"; @@ -274,12 +267,12 @@ class AccountingAccount extends CommonObject $sql .= ", fk_accounting_category"; $sql .= ", fk_user_author"; $sql .= ", active"; + $sql .= ", reconcilable"; $sql .= ") VALUES ("; $sql .= " '" . $this->db->idate($now) . "'"; $sql .= ", " . $conf->entity; $sql .= ", " . (empty($this->fk_pcg_version) ? 'NULL' : "'" . $this->db->escape($this->fk_pcg_version) . "'"); $sql .= ", " . (empty($this->pcg_type) ? 'NULL' : "'" . $this->db->escape($this->pcg_type) . "'"); - $sql .= ", " . (empty($this->pcg_subtype) ? 'NULL' : "'" . $this->db->escape($this->pcg_subtype) . "'"); $sql .= ", " . (empty($this->account_number) ? 'NULL' : "'" . $this->db->escape($this->account_number) . "'"); $sql .= ", " . (empty($this->account_parent) ? 0 : (int) $this->account_parent); $sql .= ", " . (empty($this->label) ? "''" : "'" . $this->db->escape($this->label) . "'"); @@ -287,6 +280,7 @@ class AccountingAccount extends CommonObject $sql .= ", " . (empty($this->account_category) ? 0 : (int) $this->account_category); $sql .= ", " . $user->id; $sql .= ", " . (int) $this->active; + $sql .= ", " . (int) $this->reconcilable; $sql .= ")"; $this->db->begin(); @@ -341,17 +335,12 @@ class AccountingAccount extends CommonObject { $this->pcg_type = 'XXXXXX'; } - if (empty($this->pcg_subtype) || $this->pcg_subtype == '-1') - { - $this->pcg_subtype = 'XXXXXX'; - } $this->db->begin(); $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_account "; $sql .= " SET fk_pcg_version = " . ($this->fk_pcg_version ? "'" . $this->db->escape($this->fk_pcg_version) . "'" : "null"); $sql .= " , pcg_type = " . ($this->pcg_type ? "'" . $this->db->escape($this->pcg_type) . "'" : "null"); - $sql .= " , pcg_subtype = " . ($this->pcg_subtype ? "'" . $this->db->escape($this->pcg_subtype) . "'" : "null"); $sql .= " , account_number = '" . $this->db->escape($this->account_number) . "'"; $sql .= " , account_parent = " . (int) $this->account_parent; $sql .= " , label = " . ($this->label ? "'" . $this->db->escape($this->label) . "'" : "''"); @@ -359,6 +348,7 @@ class AccountingAccount extends CommonObject $sql .= " , fk_accounting_category = " . (empty($this->account_category) ? 0 : (int) $this->account_category); $sql .= " , fk_user_modif = " . $user->id; $sql .= " , active = " . (int) $this->active; + $sql .= " , reconcilable = " . (int) $this->reconcilable; $sql .= " WHERE rowid = " . $this->id; dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); @@ -584,21 +574,31 @@ class AccountingAccount extends CommonObject * Account deactivated * * @param int $id Id + * @param int $mode 0=field active, 1=field active_customer_list, 2=field_active_supplier_list * @return int <0 if KO, >0 if OK */ - public function account_desactivate($id) + public function account_desactivate($id, $mode = 0) { // phpcs:enable $result = $this->checkUsage(); + if ($mode == 0) + { + $fieldtouse = 'active'; + } + elseif ($mode == 1) + { + $fieldtouse = 'reconcilable'; + } + if ($result > 0) { $this->db->begin(); $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_account "; - $sql .= "SET active = '0'"; + $sql .= "SET " . $fieldtouse . " = '0'"; $sql .= " WHERE rowid = " . $this->db->escape($id); - dol_syslog(get_class($this) . "::desactivate sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this) . "::account_desactivate " . $fieldtouse . " sql=" . $sql, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -619,18 +619,28 @@ class AccountingAccount extends CommonObject * Account activated * * @param int $id Id + * @param int $mode 0=field active, 1=field reconcilable * @return int <0 if KO, >0 if OK */ - public function account_activate($id) + public function account_activate($id, $mode = 0) { // phpcs:enable $this->db->begin(); + if ($mode == 0) + { + $fieldtouse = 'active'; + } + elseif ($mode == 1) + { + $fieldtouse = 'reconcilable'; + } + $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_account "; - $sql .= "SET active = '1'"; + $sql .= "SET " . $fieldtouse . " = '1'"; $sql .= " WHERE rowid = " . $this->db->escape($id); - dol_syslog(get_class($this) . "::activate sql=" . $sql, LOG_DEBUG); + dol_syslog(get_class($this) . "::account_activate " . $fieldtouse . " sql=" . $sql, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $this->db->commit(); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index ebc4a29793c..2da8e4e24e1 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -926,6 +926,7 @@ class BookKeeping extends CommonObject $sql .= " t.debit,"; $sql .= " t.credit,"; $sql .= " t.lettering_code,"; + $sql .= " t.date_lettering,"; $sql .= " t.montant,"; $sql .= " t.sens,"; $sql .= " t.fk_user_author,"; @@ -934,6 +935,7 @@ class BookKeeping extends CommonObject $sql .= " t.journal_label,"; $sql .= " t.piece_num,"; $sql .= " t.date_creation,"; + $sql .= " t.date_lim_reglement,"; $sql .= " t.tms as date_modification,"; $sql .= " t.date_export"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; @@ -1006,12 +1008,14 @@ class BookKeeping extends CommonObject $line->montant = $obj->montant; $line->sens = $obj->sens; $line->lettering_code = $obj->lettering_code; + $line->date_lettering = $obj->date_lettering; $line->fk_user_author = $obj->fk_user_author; $line->import_key = $obj->import_key; $line->code_journal = $obj->code_journal; $line->journal_label = $obj->journal_label; $line->piece_num = $obj->piece_num; $line->date_creation = $this->db->jdate($obj->date_creation); + $line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement); $line->date_modification = $this->db->jdate($obj->date_modification); $line->date_export = $this->db->jdate($obj->date_export); @@ -1550,7 +1554,7 @@ class BookKeeping extends CommonObject $sql .= " WHERE piece_num = ".$piecenum; $sql .= " AND entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $obj = $this->db->fetch_object($result); @@ -1564,7 +1568,7 @@ class BookKeeping extends CommonObject $this->date_creation = $obj->date_creation; } else { $this->error = "Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + dol_syslog(__METHOD__.$this->error, LOG_ERR); return -1; } @@ -1618,7 +1622,7 @@ class BookKeeping extends CommonObject $sql .= " WHERE piece_num = ".$piecenum; $sql .= " AND entity IN (".getEntity('accountancy').")"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if ($result) { while ($obj = $this->db->fetch_object($result)) { @@ -1650,7 +1654,7 @@ class BookKeeping extends CommonObject } } else { $this->error = "Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + dol_syslog(__METHOD__.$this->error, LOG_ERR); return -1; } diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 48df5ce374a..19a5adcca34 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -122,8 +122,8 @@ if ($action == 'validatehistory') { // Customer Invoice lines (must be same request than into page list.php for manual binding) $sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype,"; $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; - $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,"; - $sql .= " p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,"; + $sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; $sql .= " co.code as country_code, co.label as country_label,"; $sql .= " s.tva_intra"; @@ -154,14 +154,22 @@ if ($action == 'validatehistory') { $isBuyerInEEC = isInEEC($objp); - // Search suggested account for product/service + // Search suggested account for product/service (similar code exists in page list.php to make manual binding) $suggestedaccountingaccountfor = ''; if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_p = $objp->code_sell; $objp->aarowid_suggest = $objp->aarowid; $suggestedaccountingaccountfor = ''; } else { - if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; + $suggestedaccountingaccountfor = 'eecwithvat'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = 0; // There is a doubt, no automatic binding + $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale $objp->code_sell_p = $objp->code_sell_intra; $objp->aarowid_suggest = $objp->aarowid_intra; $suggestedaccountingaccountfor = 'eec'; diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index d52c4c51f07..55342a98c27 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -60,7 +60,7 @@ $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; $pageprev = $page - 1; $pagenext = $page + 1; diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index d964d348889..ec872726012 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -69,7 +69,7 @@ $btn_ventil = GETPOST('ventil', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; @@ -206,8 +206,10 @@ if (empty($chartaccountcode)) // Customer Invoice lines $sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype,"; $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; -$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_sell as code_sell, p.tva_tx as tva_tx_prod,"; -$sql .= " p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; +$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,"; +$sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; +$sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export,"; +$sql .= " p.tosell as status, p.tobuy as status_buy,"; $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; $sql .= " co.code as country_code, co.label as country_label,"; $sql .= " s.tva_intra"; @@ -399,7 +401,7 @@ if ($result) { print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Country", $_SERVER["PHP_SELF"], "co.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("VATIntra", $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'center '); + print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall '); print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', 'center '); $checkpicto = ''; if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1); @@ -423,6 +425,14 @@ if ($result) { $product_static->id = $objp->product_id; $product_static->type = $objp->type; $product_static->label = $objp->product_label; + $product_static->status = $objp->status; + $product_static->status_buy = $objp->status_buy; + $product_static->accountancy_code_sell = $objp->code_sell; + $product_static->accountancy_code_sell_intra = $objp->code_sell_intra; + $product_static->accountancy_code_sell_export = $objp->code_sell_export; + $product_static->accountancy_code_buy = $objp->code_buy; + $product_static->accountancy_code_buy_intra = $objp->code_buy_intra; + $product_static->accountancy_code_buy_export = $objp->code_buy_export; $facture_static->ref = $objp->ref; $facture_static->id = $objp->facid; @@ -433,13 +443,20 @@ if ($result) { $isBuyerInEEC = isInEEC($objp); + // Search suggested default account for product/service $suggestedaccountingaccountbydefaultfor = ''; if ($objp->type_l == 1) { if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = ''; } else { - if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithvat'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = 'eec'; } else { // Foreign sale @@ -452,7 +469,13 @@ if ($result) { $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = ''; } else { - if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with a VAT + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithvat'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale $objp->code_sell_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT : ''); $suggestedaccountingaccountbydefaultfor = 'eec'; } else { @@ -463,14 +486,22 @@ if ($result) { } if ($objp->code_sell_l == -1) $objp->code_sell_l = ''; - // Search suggested account for product/service + // Search suggested account for product/service (similar code exists in page index.php to make automatic binding) $suggestedaccountingaccountfor = ''; if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_p = $objp->code_sell; $objp->aarowid_suggest = $objp->aarowid; $suggestedaccountingaccountfor = ''; } else { - if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + if ($isSellerInEEC && $isBuyerInEEC && $objp->tva_tx_line != 0) { // European intravat sale, but with VAT + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; + $suggestedaccountingaccountfor = 'eecwithvat'; + } elseif ($isSellerInEEC && $isBuyerInEEC && empty($objp->tva_intra)) { // European intravat sale, without VAT intra community number + $objp->code_sell_p = $objp->code_sell; + $objp->aarowid_suggest = $objp->aarowid; // There is a doubt for this case. Is it an error on vat or we just forgot to fill vat number ? + $suggestedaccountingaccountfor = 'eecwithoutvatnumber'; + } elseif ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale $objp->code_sell_p = $objp->code_sell_intra; $objp->aarowid_suggest = $objp->aarowid_intra; $suggestedaccountingaccountfor = 'eec'; @@ -487,6 +518,7 @@ if ($result) { $code_sell_p_notset = 'color:orange'; } if (empty($objp->code_sell_l) && empty($objp->code_sell_p)) $code_sell_p_notset = 'color:red'; + if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber' && empty($code_sell_p_notset)) $code_sell_p_notset = 'color:orange'; // $objp->code_sell_l is now default code of product/service // $objp->code_sell_p is now code of product/service @@ -503,9 +535,10 @@ if ($result) { // Ref Product print ''; print ''; - // Current account - print ''; diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index cc606555b37..63b142e1bdd 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -55,7 +55,7 @@ $search_year = GETPOST("search_year", "int"); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; $pageprev = $page - 1; $pagenext = $page + 1; diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php index c0d9d1a03b5..e03c717039f 100644 --- a/htdocs/accountancy/expensereport/list.php +++ b/htdocs/accountancy/expensereport/list.php @@ -62,7 +62,7 @@ $search_year = GETPOST("search_year", "int"); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; @@ -313,8 +313,8 @@ if ($result) { print_liste_field_titre("Description", $_SERVER["PHP_SELF"], "erd.comments", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "erd.total_ht", "", $param, '', $sortfield, $sortorder, 'right maxwidth50 '); print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "erd.tva_tx", "", $param, '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("IntoAccount", '', '', '', '', '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall '); + print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', ''); $checkpicto = ''; if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1); print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center '); @@ -366,12 +366,12 @@ if ($result) { print ''; // Current account - print ''; // Suggested accounting account - print ''; diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php index 71fce0be43a..ec193b2922a 100644 --- a/htdocs/accountancy/index.php +++ b/htdocs/accountancy/index.php @@ -66,7 +66,7 @@ if ($conf->accounting->enabled) $resultboxes = FormOther::getBoxesArea($user, "27"); // Load $resultboxes (selectboxlist + boxactivated + boxlista + boxlistb) - $helpisexpanded = empty($resultboxes['boxactivated']); // If there is no widget, the tooltip help is expanded by default. + $helpisexpanded = empty($resultboxes['boxactivated']) || (empty($resultboxes['boxlista']) && empty($resultboxes['boxlistb'])); // If there is no widget, the tooltip help is expanded by default. $showtutorial = ''; if (!$helpisexpanded) @@ -222,10 +222,6 @@ if ($conf->accounting->enabled) $boxlist .= '
'; $boxlist .= '
'; - if (!empty($nbworkboardcount)) - { - $boxlist .= $boxwork; - } $boxlist .= $resultboxes['boxlista']; @@ -233,7 +229,6 @@ if ($conf->accounting->enabled) $boxlist .= '
'; - $boxlist .= $boxstat; $boxlist .= $resultboxes['boxlistb']; $boxlist .= '
'; diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index bab853c35b2..d849496d965 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -663,7 +663,7 @@ if (! $error && $action == 'writebookkeeping') { } elseif ($tabtype[$key] == 'payment_various') { $bookkeeping->subledger_account = $k; $bookkeeping->subledger_label = $tabcompany[$key]['name']; - $bookkeeping->numero_compte = $tabpay[$obj->rowid]["account_various"]; + $bookkeeping->numero_compte = $tabpay[$key]["account_various"]; $accountingaccount->fetch(null, $bookkeeping->numero_compte, true); $bookkeeping->label_compte = $accountingaccount->label; @@ -760,7 +760,7 @@ if (! $error && $action == 'writebookkeeping') { } } - if (price2num($totaldebit) != price2num($totalcredit)) + if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) { $error++; $errorforline++; @@ -968,8 +968,8 @@ if (empty($action) || $action == 'view') { journalHead($nom, '', $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink); - // Test that setup is complete - $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'bank_account WHERE fk_accountancy_journal IS NULL AND clos=0'; + // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed) + $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'bank_account WHERE entity = '.$conf->entity.' AND fk_accountancy_journal IS NULL AND clos=0'; $resql = $db->query($sql); if ($resql) { diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php index 1fbed52b9e3..29131274c7a 100644 --- a/htdocs/accountancy/journal/expensereportsjournal.php +++ b/htdocs/accountancy/journal/expensereportsjournal.php @@ -355,7 +355,7 @@ if ($action == 'writebookkeeping') { } // Protection against a bug on line before - if (price2num($totaldebit) != price2num($totalcredit)) + if (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT')) { $error++; $errorforline++; diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index 4d4368ede62..c7fb4c06304 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -513,7 +513,7 @@ if ($action == 'writebookkeeping') { } // Protection against a bug on lines before - if (!$errorforline && (price2num($totaldebit) != price2num($totalcredit))) + if (! $errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) { $error++; $errorforline++; diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index 6043d2bf857..878270d3687 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -471,7 +471,7 @@ if ($action == 'writebookkeeping') { } // Protection against a bug on lines before - if (!$errorforline && (price2num($totaldebit) != price2num($totalcredit))) + if (! $errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) { $error++; $errorforline++; diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php index 3bc44698029..07877378ce1 100644 --- a/htdocs/accountancy/supplier/index.php +++ b/htdocs/accountancy/supplier/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2015 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -119,8 +119,9 @@ if ($action == 'validatehistory') { // Supplier Invoice Lines (must be same request than into page list.php for manual binding) $sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef, f.type as ftype,"; $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; - $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_buy as code_buy, p.tva_tx as tva_tx_prod,"; - $sql .= " aa.rowid as aarowid,"; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type,"; + $sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export, p.tva_tx as tva_tx_prod,"; + $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; $sql .= " co.code as country_code, co.label as country_label,"; $sql .= " s.tva_intra"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; @@ -128,7 +129,9 @@ if ($action == 'validatehistory') { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn_det as l ON f.rowid = l.fk_facture_fourn"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_buy = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_buy = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_buy_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$chartaccountcode."' AND aa2.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_buy_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$chartaccountcode."' AND aa3.entity = ".$conf->entity; $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND l.product_type <= 2"; @@ -157,16 +160,12 @@ if ($action == 'validatehistory') { $suggestedaccountingaccountfor = ''; } else { if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale - //$objp->code_buy_p = $objp->code_buy_intra; - $objp->code_buy_p = $objp->code_buy; - //$objp->aarowid_suggest = $objp->aarowid_intra; - $objp->aarowid_suggest = $objp->aarowid; + $objp->code_buy_p = $objp->code_buy_intra; + $objp->aarowid_suggest = $objp->aarowid_intra; $suggestedaccountingaccountfor = 'eec'; } else { // Foreign sale - //$objp->code_buy_p = $objp->code_buy_export; - $objp->code_buy_p = $objp->code_buy; - //$objp->aarowid_suggest = $objp->aarowid_export; - $objp->aarowid_suggest = $objp->aarowid; + $objp->code_buy_p = $objp->code_buy_export; + $objp->aarowid_suggest = $objp->aarowid_export; $suggestedaccountingaccountfor = 'export'; } } diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php index a035aed2b1f..ef44222568f 100644 --- a/htdocs/accountancy/supplier/lines.php +++ b/htdocs/accountancy/supplier/lines.php @@ -62,7 +62,7 @@ $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php index ecd41f2f9da..302c4410111 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2014-2015 Ari Elbaz (elarifr) * Copyright (C) 2013-2014 Florian Henry * Copyright (C) 2014 Juanjo Menent s @@ -69,7 +69,7 @@ $btn_ventil = GETPOST('ventil', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) { $page = 0; } $offset = $limit * $page; $pageprev = $page - 1; @@ -210,8 +210,11 @@ if (empty($chartaccountcode)) // Supplier Invoice Lines $sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef, f.type as ftype,"; $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; -$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.accountancy_code_buy as code_buy, p.tva_tx as tva_tx_prod,"; -$sql .= " aa.rowid as aarowid,"; +$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,"; +$sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; +$sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export,"; +$sql .= " p.tosell as status, p.tobuy as status_buy,"; +$sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; $sql .= " co.code as country_code, co.label as country_label,"; $sql .= " s.tva_intra"; $parameters = array(); @@ -222,7 +225,9 @@ $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays "; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."facture_fourn_det as l ON f.rowid = l.fk_facture_fourn"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; -$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_buy = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_buy = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$chartaccountcode."' AND aa.entity = ".$conf->entity; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_buy_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$chartaccountcode."' AND aa2.entity = ".$conf->entity; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_buy_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$chartaccountcode."' AND aa3.entity = ".$conf->entity; $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND l.product_type <= 2"; // Add search filter like @@ -396,7 +401,7 @@ if ($result) { print_liste_field_titre("VATRate", $_SERVER["PHP_SELF"], "l.tva_tx", "", $param, '', $sortfield, $sortorder, 'right '); print_liste_field_titre("Country", $_SERVER["PHP_SELF"], "co.label", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("VATIntra", $_SERVER["PHP_SELF"], "s.tva_intra", "", $param, '', $sortfield, $sortorder); - print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'center '); + print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'nowraponall '); print_liste_field_titre("IntoAccount", '', '', '', '', '', '', '', 'center '); $checkpicto = ''; if ($massactionbutton) $checkpicto = $form->showCheckAddButtons('checkforselect', 1); @@ -406,6 +411,10 @@ if ($result) { $facturefourn_static = new FactureFournisseur($db); $product_static = new Product($db); + $isBuyerInEEC = isInEEC($mysoc); + + $accountingaccount_codetotid_cache = array(); + while ($i < min($num_lines, $limit)) { $objp = $db->fetch_object($result); @@ -414,40 +423,86 @@ if ($result) { // issue : if we change product_type value in product DB it should differ from the value stored in facturedet DB ! $objp->code_buy_l = ''; $objp->code_buy_p = ''; - $objp->aarowid_suggest = ''; $product_static->ref = $objp->product_ref; $product_static->id = $objp->product_id; $product_static->type = $objp->type; $product_static->label = $objp->product_label; + $product_static->status = $objp->status; + $product_static->status_buy = $objp->status_buy; + $product_static->accountancy_code_sell = $objp->code_sell; + $product_static->accountancy_code_sell_intra = $objp->code_sell_intra; + $product_static->accountancy_code_sell_export = $objp->code_sell_export; + $product_static->accountancy_code_buy = $objp->code_buy; + $product_static->accountancy_code_buy_intra = $objp->code_buy_intra; + $product_static->accountancy_code_buy_export = $objp->code_buy_export; $facturefourn_static->ref = $objp->ref; $facturefourn_static->id = $objp->facid; $facturefourn_static->type = $objp->type; $code_buy_p_notset = ''; - $objp->aarowid_suggest = $objp->aarowid; + $objp->aarowid_suggest = ''; // Will be set later + $isSellerInEEC = isInEEC($objp); + + $suggestedaccountingaccountbydefaultfor = ''; if ($objp->type_l == 1) { - $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : ''); - if ($objp->aarowid == '') - $objp->aarowid_suggest = $aarowid_s; + if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eec'; + } else { // Foreign sale + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'export'; + } + } } elseif ($objp->type_l == 0) { - $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : ''); - if ($objp->aarowid == '') - $objp->aarowid_suggest = $aarowid_p; + if ($objp->country_code == $mysoc->country_code || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_INTRA_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_INTRA_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'eec'; + } else { + $objp->code_buy_l = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT : ''); + $suggestedaccountingaccountbydefaultfor = 'export'; + } + } } - if ($objp->code_buy_l == -1) $objp->code_buy_l = ''; + if ($objp->code_sell_l == -1) $objp->code_sell_l = ''; - if (!empty($objp->code_buy)) { - $objp->code_buy_p = $objp->code_buy; // Code on product + // Search suggested account for product/service + $suggestedaccountingaccountfor = ''; + if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) + $objp->code_buy_p = $objp->code_buy; + $objp->aarowid_suggest = $objp->aarowid; + $suggestedaccountingaccountfor = ''; + } else { + if ($isSellerInEEC && $isBuyerInEEC) { // European intravat sale + $objp->code_buy_p = $objp->code_buy_intra; + $objp->aarowid_suggest = $objp->aarowid_intra; + $suggestedaccountingaccountfor = 'eec'; + } else { // Foreign sale + $objp->code_buy_p = $objp->code_buy_export; + $objp->aarowid_suggest = $objp->aarowid_export; + $suggestedaccountingaccountfor = 'export'; + } + } + + if (!empty($objp->code_buy_p)) { + // Value was defined previously } else { $code_buy_p_notset = 'color:orange'; } if (empty($objp->code_buy_l) && empty($objp->code_buy_p)) $code_buy_p_notset = 'color:red'; - // $objp->code_buy_p is now code of product/service // $objp->code_buy_l is now default code of product/service + // $objp->code_buy_p is now code of product/service print '
'; @@ -467,7 +522,7 @@ if ($result) { print ''; // Description @@ -497,9 +552,9 @@ if ($result) { // VAT Num print ''; - // Current account - print ''; @@ -540,6 +610,9 @@ if ($result) { } else { print $db->error(); } +if ($db->type == 'mysqli') { + $db->query("SET SQL_BIG_SELECTS=0"); // Enable MAX_JOIN_SIZE limitation +} // Add code to auto check the box when we select an account print ''; } - - /* - print ''; - print $_POST["formtestfield"]; - print ''; - print $conf->global->FCKEDITOR_TEST; - */ } // End of page diff --git a/htdocs/admin/ihm.php b/htdocs/admin/ihm.php index 3a9eed62fd0..2f33b3ab49b 100644 --- a/htdocs/admin/ihm.php +++ b/htdocs/admin/ihm.php @@ -36,12 +36,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; // Load translation files required by the page $langs->loadLangs(array('admin', 'languages', 'other', 'companies', 'products', 'members', 'projects', 'hrm', 'agenda')); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'aZ09'); -$contextpage=GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'adminihm'; // To manage different context of search +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'adminihm'; // To manage different context of search -if (! defined("MAIN_MOTD")) define("MAIN_MOTD", ""); +if (!defined("MAIN_MOTD")) define("MAIN_MOTD", ""); @@ -49,24 +49,31 @@ if (! defined("MAIN_MOTD")) define("MAIN_MOTD", ""); * Action */ -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$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 (GETPOST('cancel', 'alpha')) { - $action=''; + $action = ''; } -if ($action == 'removebackgroundlogin' && ! empty($conf->global->MAIN_LOGIN_BACKGROUND)) +// Convert action set_XXX and del_XXX to set var (this is used when no javascript on for ajax_constantonoff) +$regs = array(); +if (preg_match('/^(set|del)_([A-Z_]+)$/', $action, $regs)) { + if ($regs[1] == 'set') dolibarr_set_const($db, $regs[2], 1, 'chaine', 0, '', $conf->entity); + else dolibarr_del_const($db, $regs[2], $conf->entity); +} + +if ($action == 'removebackgroundlogin' && !empty($conf->global->MAIN_LOGIN_BACKGROUND)) { - dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV+1, 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $logofile=$conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; + $logofile = $conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND; dol_delete_file($logofile); dolibarr_del_const($db, "MAIN_LOGIN_BACKGROUND", $conf->entity); - $mysoc->logo=''; + $mysoc->logo = ''; /*$logosmallfile=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; dol_delete_file($logosmallfile); @@ -81,98 +88,99 @@ if ($action == 'removebackgroundlogin' && ! empty($conf->global->MAIN_LOGIN_BACK if ($action == 'update') { - dolibarr_set_const($db, "MAIN_LANG_DEFAULT", $_POST["MAIN_LANG_DEFAULT"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV+1, 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_LANG_DEFAULT", GETPOST("MAIN_LANG_DEFAULT", 'aZ09'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_IHM_PARAMS_REV", (int) $conf->global->MAIN_IHM_PARAMS_REV + 1, 'chaine', 0, '', $conf->entity); //dolibarr_set_const($db, "MAIN_MULTILANGS", $_POST["MAIN_MULTILANGS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_THEME", $_POST["main_theme"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_THEME", GETPOST("main_theme", 'aZ09'), 'chaine', 0, '', $conf->entity); - $val=GETPOST('THEME_TOPMENU_DISABLE_IMAGE'); + /*$val=GETPOST('THEME_TOPMENU_DISABLE_IMAGE'); if (! $val) dolibarr_del_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', $conf->entity); - else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'), 'chaine', 0, '', $conf->entity); + else dolibarr_set_const($db, 'THEME_TOPMENU_DISABLE_IMAGE', GETPOST('THEME_TOPMENU_DISABLE_IMAGE'), 'chaine', 0, '', $conf->entity);*/ - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_BACKBODY'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_BACKBODY'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_BACKBODY', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_BACKBODY', $val, 'chaine', 0, '', $conf->entity); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_TOPMENU_BACK1'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_TOPMENU_BACK1', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_TOPMENU_BACK1', $val, 'chaine', 0, '', $conf->entity); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_VERMENU_BACK1'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_VERMENU_BACK1'), array())))); 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())))); + $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())))); + $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())))); + $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())))); + $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); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEIMPAIR1'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEIMPAIR2', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_LINEIMPAIR2', $val, 'chaine', 0, '', $conf->entity); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_LINEPAIR1', $conf->entity); else dolibarr_set_const($db, 'THEME_ELDY_LINEPAIR1', $val, 'chaine', 0, '', $conf->entity); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_LINEPAIR1'), array())))); 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_TEXTLINK'), array())))); + $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); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_HOVER'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_HOVER'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_USE_HOVER', $conf->entity); else dolibarr_set_const($db, "THEME_ELDY_USE_HOVER", $val, 'chaine', 0, '', $conf->entity); - $val=(implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_CHECKED'), array())))); + $val = (implode(',', (colorStringToArray(GETPOST('THEME_ELDY_USE_CHECKED'), array())))); if ($val == '') dolibarr_del_const($db, 'THEME_ELDY_USE_CHECKED', $conf->entity); else dolibarr_set_const($db, "THEME_ELDY_USE_CHECKED", $val, '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); - dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", $_POST["MAIN_BUTTON_HIDE_UNAUTHORIZED"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_START_WEEK", $_POST["MAIN_START_WEEK"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", $_POST["MAIN_DEFAULT_WORKING_DAYS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", $_POST["MAIN_DEFAULT_WORKING_HOURS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_SHOW_LOGO", $_POST["MAIN_SHOW_LOGO"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", $_POST["MAIN_FIRSTNAME_NAME_POSITION"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_LISTE_LIMIT", GETPOST("main_size_liste_limit", 'int'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_SIZE_SHORTLIST_LIMIT", GETPOST("main_size_shortliste_limit", 'int'), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_HELPCENTER_DISABLELINK", $_POST["MAIN_HELPCENTER_DISABLELINK"], 'chaine', 0, '', 0); // Param for all entities - dolibarr_set_const($db, "MAIN_MOTD", dol_htmlcleanlastbr($_POST["main_motd"]), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_HOME", dol_htmlcleanlastbr($_POST["main_home"]), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_HELP_DISABLELINK", $_POST["MAIN_HELP_DISABLELINK"], 'chaine', 0, '', 0); // Param for all entities - dolibarr_set_const($db, "MAIN_BUGTRACK_ENABLELINK", $_POST["MAIN_BUGTRACK_ENABLELINK"], 'chaine', 0, '', $conf->entity); + //dolibarr_set_const($db, "MAIN_DISABLE_JAVASCRIPT", GETPOST("MAIN_DISABLE_JAVASCRIPT", 'aZ09'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_BUTTON_HIDE_UNAUTHORIZED", GETPOST("MAIN_BUTTON_HIDE_UNAUTHORIZED", 'aZ09'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_START_WEEK", GETPOST("MAIN_START_WEEK", 'int'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_DAYS", GETPOST("MAIN_DEFAULT_WORKING_DAYS", 'int'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_DEFAULT_WORKING_HOURS", GETPOST("MAIN_DEFAULT_WORKING_HOURS", 'int'), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_FIRSTNAME_NAME_POSITION", GETPOST("MAIN_FIRSTNAME_NAME_POSITION", 'aZ09'), 'chaine', 0, '', $conf->entity); - $varforimage='imagebackground'; $dirforimage=$conf->mycompany->dir_output.'/logos/'; + dolibarr_set_const($db, "MAIN_HELPCENTER_DISABLELINK", GETPOST('MAIN_HELPCENTER_DISABLELINK', 'aZ09'), 'chaine', 0, '', 0); // Param for all entities + dolibarr_set_const($db, "MAIN_MOTD", dol_htmlcleanlastbr(GETPOST("main_motd", 'none')), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_HOME", dol_htmlcleanlastbr(GETPOST("main_home", 'none')), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_HELP_DISABLELINK", GETPOST("MAIN_HELP_DISABLELINK", 'aZ09'), 'chaine', 0, '', 0); // Param for all entities + dolibarr_set_const($db, "MAIN_BUGTRACK_ENABLELINK", GETPOST('MAIN_BUGTRACK_ENABLELINK', 'aZ09'), 'chaine', 0, '', $conf->entity); + + $varforimage = 'imagebackground'; $dirforimage = $conf->mycompany->dir_output.'/logos/'; if ($_FILES[$varforimage]["tmp_name"]) { + $reg = array(); if (preg_match('/([^\\/:]+)$/i', $_FILES[$varforimage]["name"], $reg)) { - $original_file=$reg[1]; + $original_file = $reg[1]; - $isimage=image_format_supported($original_file); + $isimage = image_format_supported($original_file); if ($isimage >= 0) { dol_syslog("Move file ".$_FILES[$varforimage]["tmp_name"]." to ".$dirforimage.$original_file); - if (! is_dir($dirforimage)) + if (!is_dir($dirforimage)) { dol_mkdir($dirforimage); } - $result=dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"], $dirforimage.$original_file, 1, 0, $_FILES[$varforimage]['error']); + $result = dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"], $dirforimage.$original_file, 1, 0, $_FILES[$varforimage]['error']); if ($result > 0) { dolibarr_set_const($db, "MAIN_LOGIN_BACKGROUND", $original_file, 'chaine', 0, '', $conf->entity); @@ -181,7 +189,7 @@ if ($action == 'update') { $error++; $langs->load("errors"); - $tmparray=explode(':', $result); + $tmparray = explode(':', $result); setEventMessages($langs->trans('ErrorFileIsInfectedWithAVirus', $tmparray[1]), null, 'errors'); } else @@ -201,7 +209,7 @@ if ($action == 'update') - $_SESSION["mainmenu"]=""; // Le gestionnaire de menu a pu changer + $_SESSION["mainmenu"] = ""; // Le gestionnaire de menu a pu changer header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -212,12 +220,12 @@ if ($action == 'update') * View */ -$wikihelp='EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones'; +$wikihelp = 'EN:First_setup|FR:Premiers_paramétrages|ES:Primeras_configuraciones'; llxHeader('', $langs->trans("Setup"), $wikihelp); -$form=new Form($db); -$formother=new FormOther($db); -$formadmin=new FormAdmin($db); +$form = new Form($db); +$formother = new FormOther($db); +$formadmin = new FormAdmin($db); print load_fiche_titre($langs->trans("GUISetup"), '', 'title_setup'); @@ -248,8 +256,7 @@ print ''; // Multilingual GUI print ''; print ''; print ''; @@ -268,18 +275,18 @@ print ''; // Disable javascript and ajax print ''; print ''; print ''; // Max size of lists -print ''; +print ''; print ''; print ''; // Max size of short lists on customer card -print ''; +print ''; print ''; print ''; @@ -294,36 +301,36 @@ print ''; // First day for weeks print ''; print ''; print ''; // DefaultWorkingDays print ''; print ''; print ''; // DefaultWorkingHours print ''; print ''; print ''; // Firstname/Name print ''; print ''; print ''; // Hide unauthorized button print ''; print ''; print ''; @@ -346,28 +353,28 @@ print ''; print ''; // Hide wiki link on login page -$pictohelp=''; +$pictohelp = ''; print ''; print ''; print ''; // Message of the day on home page -$substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount')); +$substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'objectamount')); complete_substitutions_array($substitutionarray, $langs); print ''."\n"; @@ -384,23 +391,23 @@ print ''; print ''; // Message on login page -$substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount','user')); +$substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'objectamount', 'user')); complete_substitutions_array($substitutionarray, $langs); print ''."\n"; // Hide helpcenter link on login page print ''; print ''; print ''; @@ -409,13 +416,13 @@ print ''; print 'selectarray('MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS', $arraydetailsforpdffoot, $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS); print ''; +print ''; + + print '
'; + print ''; print $langs->trans('From'); print $formaccounting->select_account($search_accountancy_code_start, 'search_accountancy_code_start', 1, array(), 1, 1, ''); print ' '; @@ -245,6 +254,7 @@ if ($action != 'export_csv') print '
' . $langs->trans("SubTotal") . ':' . price($sous_total_debit) . '' . price($sous_total_credit) . '' . price(price2num($sous_total_credit - $sous_total_debit)) . '
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_credit - $sous_total_debit)).' 
' . $line->numero_compte . ($root_account_description ? ' - ' . $root_account_description : '') . ''.$line->numero_compte.($root_account_description ? ' - '.$root_account_description : '').'
'.length_accountg($line->numero_compte).''.$description.''.price($opening_balances["'".$line->numero_compte."'"]).''.price($line->debit).''.price($line->credit).''.price($line->debit - $line->credit).'
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_debit - $sous_total_credit)).'
'.$langs->trans("SubTotal").':'.price($sous_total_debit).''.price($sous_total_credit).''.price(price2num($sous_total_debit - $sous_total_credit)).' 
'.$langs->trans("AccountBalance").':'.price($total_debit).''.price($total_credit).''.price(price2num($total_debit - $total_credit)).'
'.$langs->trans("AccountBalance").':'.price($total_debit).''.price($total_credit).''.price(price2num($total_debit - $total_credit)).' 
'; print ''; - print '
'.$langs->trans("NotReconciled").''; + print '
'.$langs->trans("NotReconciled").''; print '
'.$line->doc_ref.''; + + print ''; + // Picto + Ref + print '
'; + + if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') + { + print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); + print $documentlink; + } else { + print $line->doc_ref; + } + print '
'; + + print "
'; - if ($product_static->id > 0) + if ($product_static->id > 0) { print $product_static->getNomUrl(1); - if ($objp->product_label) print '
'.$objp->product_label; + } + if ($objp->product_label) print '
'.$objp->product_label.''; print '
'; @@ -533,9 +566,9 @@ if ($result) { print ''.$objp->tva_intra.''; - $s = (($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; + // Found accounts + print ''; + $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; $shelp = ''; if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); @@ -544,9 +577,11 @@ if ($result) { if ($objp->product_id > 0) { print '
'; - $s = (($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; + $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; $shelp = ''; if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); + elseif ($suggestedaccountingaccountfor == 'eecwithvat') $shelp = $langs->trans("SaleEECWithVAT"); + elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $shelp = $langs->trans("SaleEECWithoutVATNumber"); elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); $s .= (empty($objp->code_sell_p) ? $langs->trans("NotDefined") : length_accountg($objp->code_sell_p)); print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1); @@ -582,6 +617,7 @@ if ($result) { print '
'; //var_dump($objp->aarowid);var_dump($objp->aarowid_intra);var_dump($objp->aarowid_export);var_dump($objp->aarowid_suggest); $ischecked = $objp->aarowid_suggest; + if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') $ischecked = 0; print ''; print ''; + print ''; print length_accountg(html_entity_decode($objp->code_buy)); print ''; + print ''; print $formaccounting->select_account($objp->aarowid_suggest, 'codeventil'.$objp->rowid, 1, array(), 0, 0, 'codeventil maxwidth300 maxwidthonsmartphone', 'cachewithshowemptyone'); print '
'; if ($product_static->id > 0) print $product_static->getNomUrl(1); - if ($objp->product_label) print '
'.$objp->product_label; + if ($objp->product_label) print '
'.$objp->product_label.''; print '
'.$objp->tva_intra.''; - $s = (($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; + // Found accounts + print ''; + $s = ''.(($objp->type_l == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")).': '; $shelp = ''; if ($suggestedaccountingaccountbydefaultfor == 'eec') $shelp .= $langs->trans("SaleEEC"); elseif ($suggestedaccountingaccountbydefaultfor == 'export') $shelp .= $langs->trans("SaleExport"); @@ -508,7 +563,7 @@ if ($result) { if ($objp->product_id > 0) { print '
'; - $s = (($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; + $s = ''.(($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")).': '; $shelp = ''; if ($suggestedaccountingaccountfor == 'eec') $shelp = $langs->trans("SaleEEC"); elseif ($suggestedaccountingaccountfor == 'export') $shelp = $langs->trans("SaleExport"); @@ -520,6 +575,21 @@ if ($result) { // Suggested accounting account print '
'; $suggestedid = $objp->aarowid_suggest; + if (empty($suggestedid) && empty($objp->code_buy_p) && !empty($objp->code_buy_l) && empty($conf->global->ACCOUNTANCY_DO_NOT_AUTOFILL_ACCOUNT_WITH_GENERIC)) + { + if (empty($accountingaccount_codetotid_cache[$objp->code_buy_l])) + { + $tmpaccount = new AccountingAccount($db); + $tmpaccount->fetch(0, $objp->code_buy_l, 1); + if ($tmpaccount->id > 0) { + $suggestedid = $tmpaccount->id; + } + $accountingaccount_codetotid_cache[$objp->code_buy_l] = $tmpaccount->id; + } + else { + $suggestedid = $accountingaccount_codetotid_cache[$objp->code_buy_l]; + } + } print $formaccounting->select_account($suggestedid, 'codeventil'.$objp->rowid, 1, array(), 0, 0, 'codeventil maxwidth200 maxwidthonsmartphone', 'cachewithshowemptyone'); print '
'.$langs->trans("EnableMultilangInterface").''; -//print $form->selectyesno('MAIN_MULTILANGS', $conf->global->MAIN_MULTILANGS, 1); -print ajax_constantonoff('MAIN_MULTILANGS'); +print ajax_constantonoff("MAIN_MULTILANGS", array(), $conf->entity, 0, 0, 1, 0); print ' 
'.$langs->trans("DisableJavascript").''; -print $form->selectyesno('MAIN_DISABLE_JAVASCRIPT', isset($conf->global->MAIN_DISABLE_JAVASCRIPT)?$conf->global->MAIN_DISABLE_JAVASCRIPT:0, 1); +print ajax_constantonoff("MAIN_DISABLE_JAVASCRIPT", array(), $conf->entity, 0, 0, 1, 0); print ' 
'.$langs->trans("DefaultMaxSizeList").'
'.$langs->trans("DefaultMaxSizeList").' 
'.$langs->trans("DefaultMaxSizeShortList").'
'.$langs->trans("DefaultMaxSizeShortList").' 
'.$langs->trans("WeekStartOnDay").''; -print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:'1'), 'MAIN_START_WEEK', 0); +print $formother->select_dayofweek((isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : '1'), 'MAIN_START_WEEK', 0); print ' 
'.$langs->trans("DefaultWorkingDays").''; -print ''; +print ''; print ' 
'.$langs->trans("DefaultWorkingHours").''; -print ''; +print ''; print ' 
'.$langs->trans("FirstnameNamePosition").''; -$array=array(0=>$langs->trans("Firstname").' '.$langs->trans("Lastname"), 1=>$langs->trans("Lastname").' '.$langs->trans("Firstname")); -print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION', $array, (isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?$conf->global->MAIN_FIRSTNAME_NAME_POSITION:0)); +$array = array(0=>$langs->trans("Firstname").' '.$langs->trans("Lastname"), 1=>$langs->trans("Lastname").' '.$langs->trans("Firstname")); +print $form->selectarray('MAIN_FIRSTNAME_NAME_POSITION', $array, (isset($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? $conf->global->MAIN_FIRSTNAME_NAME_POSITION : 0)); print ' 
'.$langs->trans("ButtonHideUnauthorized").''; -print $form->selectyesno('MAIN_BUTTON_HIDE_UNAUTHORIZED', isset($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)?$conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED:0, 1); +print $form->selectyesno('MAIN_BUTTON_HIDE_UNAUTHORIZED', isset($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) ? $conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED : 0, 1); print ' 
 
'.$langs->trans("DisableLinkToHelp", $pictohelp).''; -print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK)?$conf->global->MAIN_HELP_DISABLELINK:0, 1); +print $form->selectyesno('MAIN_HELP_DISABLELINK', isset($conf->global->MAIN_HELP_DISABLELINK) ? $conf->global->MAIN_HELP_DISABLELINK : 0, 1); print ' 
'; -$texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; -foreach($substitutionarray as $key => $val) +$texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
'; +foreach ($substitutionarray as $key => $val) { - $texthelp.=$key.'
'; + $texthelp .= $key.'
'; } print $form->textwithpicto($langs->trans("MessageOfDay"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessageofday'); print '
'; -$doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD)?$conf->global->MAIN_MOTD:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); +$doleditor = new DolEditor('main_motd', (isset($conf->global->MAIN_MOTD) ? $conf->global->MAIN_MOTD : ''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); $doleditor->Create(); print '
 
'; -$texthelp=$langs->trans("FollowingConstantsWillBeSubstituted").'
'; -foreach($substitutionarray as $key => $val) +$texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
'; +foreach ($substitutionarray as $key => $val) { - $texthelp.=$key.'
'; + $texthelp .= $key.'
'; } print $form->textwithpicto($langs->trans("MessageLogin"), $texthelp, 1, 'help', '', 0, 2, 'tooltipmessagelogin'); print '
'; -$doleditor = new DolEditor('main_home', (isset($conf->global->MAIN_HOME)?$conf->global->MAIN_HOME:''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); +$doleditor = new DolEditor('main_home', (isset($conf->global->MAIN_HOME) ? $conf->global->MAIN_HOME : ''), '', 142, 'dolibarr_notes', 'In', false, true, true, ROWS_4, '90%'); $doleditor->Create(); print '
'.$langs->trans("DisableLinkToHelpCenter").''; -print $form->selectyesno('MAIN_HELPCENTER_DISABLELINK', isset($conf->global->MAIN_HELPCENTER_DISABLELINK)?$conf->global->MAIN_HELPCENTER_DISABLELINK:0, 1); +print $form->selectyesno('MAIN_HELPCENTER_DISABLELINK', isset($conf->global->MAIN_HELPCENTER_DISABLELINK) ? $conf->global->MAIN_HELPCENTER_DISABLELINK : 0, 1); print ' 
'; print '
'; $disabled = ''; -if (! empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) $disabled = ' disabled="disabled"'; +if (!empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) $disabled = ' disabled="disabled"'; print ''; if ($disabled) { print '('.$langs->trans("DisabledByOptionADD_UNSPLASH_LOGIN_BACKGROUND").') '; } -if (! empty($conf->global->MAIN_LOGIN_BACKGROUND)) { +if (!empty($conf->global->MAIN_LOGIN_BACKGROUND)) { print ''.img_delete($langs->trans("Delete")).''; if (file_exists($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_LOGIN_BACKGROUND)) { print '   '; diff --git a/htdocs/admin/import.php b/htdocs/admin/import.php new file mode 100644 index 00000000000..37c9b205424 --- /dev/null +++ b/htdocs/admin/import.php @@ -0,0 +1,100 @@ + + * 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-2018 Philippe Grand + * Copyright (C) 2020 Floriazn Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/import.php + * \ingroup import + * \brief config page module import + */ + +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', 'other')); + +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action', 'alpha'); +$value = GETPOST('value', 'alpha'); + +/* + * Actions + */ + +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + + +/* + * View + */ + +$form = new Form($db); + +$page_name = "ImportSetup"; +llxHeader('', $langs->trans($page_name)); + +// Subheader +$linkback = ''.$langs->trans("BackToModuleList").''; + +print load_fiche_titre($langs->trans($page_name), $linkback); + +//$head = export_admin_prepare_head(); +$h = 0; +$head = array(); +$head[$h][0] = DOL_URL_ROOT.'/admin/import.php'; +$head[$h][1] = $langs->trans("Setup"); +$head[$h][2] = 'setup'; +$h++; + +dol_fiche_head($head, 'setup', $langs->trans("ImportArea"), -1, "technic"); + +print ''; +print ''; +print ''; +print ''; + +print ''; +print ''; +print ''."\n"; +print ''; +print ''."\n"; + +print ''; +print ''; +print '"; +print ''; +print ''; + +print '
'.$langs->trans("Parameters").' 
'.$langs->trans("ImportCsvSeparator").' ('.$langs->trans("ByDefault").')'."global->IMPORT_CSV_SEPARATOR_TO_USE) ? ',' : $conf->global->IMPORT_CSV_SEPARATOR_TO_USE)."\">
'; + +print ''; + +dol_fiche_end(); + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 194475ab32c..fb49c947411 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -51,14 +51,14 @@ if ($action == 'setvalue' && $user->admin) $error = 0; $db->begin(); - if (!dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_DN', GETPOST("group", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_OBJECT_CLASS', GETPOST("objectclass", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname"), 'chaine', 0, '', $conf->entity)) $error++; - //if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_NAME',$_POST["fieldname"],'chaine',0,'',$conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers"), 'chaine', 0, '', $conf->entity)) $error++; - if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid"), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_FULLNAME', GETPOST("fieldfullname", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + //if (! dolibarr_set_const($db, 'LDAP_GROUP_FIELD_NAME',GETPOST("fieldname", 'alphanohtml'),'chaine',0,'',$conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_DESCRIPTION', GETPOST("fielddescription", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPMEMBERS', GETPOST("fieldgroupmembers", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; + if (!dolibarr_set_const($db, 'LDAP_GROUP_FIELD_GROUPID', GETPOST("fieldgroupid", 'alphanohtml'), 'chaine', 0, '', $conf->entity)) $error++; // This one must be after the others $valkey = ''; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index f74ee2fac7d..abf526544ac 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -134,9 +134,8 @@ $head = email_admin_prepare_head(); // List of sending methods $listofmethods = array(); $listofmethods['mail'] = 'PHP mail function'; -//$listofmethods['simplemail']='Simplemail class'; $listofmethods['smtps'] = 'SMTP/SMTPS socket library'; -$listofmethods['swiftmailer'] = 'Swift Mailer socket library'; +if (version_compare(phpversion(), '7.0', '>=')) $listofmethods['swiftmailer'] = 'Swift Mailer socket library'; if ($action == 'edit') diff --git a/htdocs/admin/mails_senderprofile_list.php b/htdocs/admin/mails_senderprofile_list.php index 137d4129929..1c50ebf0949 100644 --- a/htdocs/admin/mails_senderprofile_list.php +++ b/htdocs/admin/mails_senderprofile_list.php @@ -48,7 +48,7 @@ $id = GETPOST('id', 'int'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index bb5fd72ec29..f2d27cf2849 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -58,6 +58,8 @@ $search_topic = GETPOST('search_topic', 'alpha'); if (!empty($user->socid)) accessforbidden(); +$acts = array(); +$actl = array(); $acts[0] = "activate"; $acts[1] = "disable"; $actl[0] = img_picto($langs->trans("Disabled"), 'switch_off'); @@ -69,7 +71,7 @@ $active = 1; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $listlimit * $page; $pageprev = $page - 1; @@ -160,8 +162,8 @@ if ($conf->expedition->enabled) $elementList['shipping_send'] = $langs->t if ($conf->reception->enabled) $elementList['reception_send'] = $langs->trans('MailToSendReception'); if ($conf->ficheinter->enabled) $elementList['fichinter_send'] = $langs->trans('MailToSendIntervention'); if ($conf->supplier_proposal->enabled) $elementList['supplier_proposal_send'] = $langs->trans('MailToSendSupplierRequestForQuotation'); -if ($conf->fournisseur->enabled) $elementList['order_supplier_send'] = $langs->trans('MailToSendSupplierOrder'); -if ($conf->fournisseur->enabled) $elementList['invoice_supplier_send'] = $langs->trans('MailToSendSupplierInvoice'); +if ($conf->fournisseur->enabled && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || $conf->supplier_order->enabled) $elementList['order_supplier_send'] = $langs->trans('MailToSendSupplierOrder'); +if ($conf->fournisseur->enabled && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || $conf->supplier_invoice->enabled) $elementList['invoice_supplier_send'] = $langs->trans('MailToSendSupplierInvoice'); 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'); @@ -261,28 +263,39 @@ if (empty($reshook)) $i = 0; foreach ($listfieldinsert as $f => $value) { - //var_dump($i.' - '.$listfieldvalue[$i].' - '.$_POST[$listfieldvalue[$i]].' - '.$value); $keycode = $listfieldvalue[$i]; - if ($value == 'label') $_POST[$keycode] = dol_escape_htmltag($_POST[$keycode]); if ($value == 'lang') $keycode = 'langcode'; + if (empty($keycode)) $keycode = $value; + if ($value == 'entity') $_POST[$keycode] = $conf->entity; - if ($i) $sql .= ","; 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 .= "''"; // lang must be '' if not defined so the unique key that include lang will work - else $sql .= "'".$db->escape($_POST[$keycode])."'"; + //var_dump($keycode.' '.$value); + + if ($i) $sql .= ", "; + if (GETPOST($keycode) == '' && $keycode != 'langcode') $sql .= "null"; // langcode must be '' if not defined so the unique key that include lang will work + elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } + elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } + else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } + $i++; } - $sql .= ",1)"; + $sql .= ", 1)"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); if ($result) // Add is ok { setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST = array('id'=>$id); // Clean $_POST array, we keep only + $_POST = array('id'=>$id); // Clean $_POST array, we keep only id } else { @@ -308,6 +321,7 @@ if (empty($reshook)) { $keycode = $listfieldvalue[$i]; if ($field == 'lang') $keycode = 'langcode'; + if (empty($keycode)) $keycode = $field; if ($field == 'fk_user' && !($_POST['fk_user'] > 0)) $_POST['fk_user'] = ''; if ($field == 'topic') $_POST['topic'] = $_POST['topic-'.$rowid]; @@ -315,15 +329,22 @@ if (empty($reshook)) if ($field == 'content') $_POST['content'] = $_POST['content-'.$rowid]; if ($field == 'content_lines') $_POST['content_lines'] = $_POST['content_lines-'.$rowid]; if ($field == 'entity') $_POST[$keycode] = $conf->entity; - if ($i) $sql .= ","; + + if ($i) $sql .= ", "; $sql .= $field."="; - //print $keycode.' - '.$_POST[$keycode].'
'; - if ($_POST[$keycode] == '' || ($keycode != 'langcode' && $keycode != 'position' && $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 - elseif ($keycode == 'position') $sql .= ((int) $_POST[$keycode]); - else $sql .= "'".$db->escape($_POST[$keycode])."'"; + if (GETPOST($keycode) == '' || ($keycode != 'langcode' && $keycode != 'position' && $keycode != 'private' && !GETPOST($keycode))) $sql .= "null"; // langcode,... must be '' if not defined so the unique key that include lang will work + elseif (GETPOST($keycode) == '0' && $keycode == 'langcode') $sql .= "''"; // langcode must be '' if not defined so the unique key that include lang will work + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } + elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } + else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } + $i++; } $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; diff --git a/htdocs/admin/menus/edit.php b/htdocs/admin/menus/edit.php index f82c423d438..ef58c1042d4 100644 --- a/htdocs/admin/menus/edit.php +++ b/htdocs/admin/menus/edit.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/menubase.class.php'; // Load translation files required by the page $langs->loadLangs(array("other", "admin")); +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button + if (!$user->admin) accessforbidden(); $dirstandard = array(); @@ -64,12 +66,12 @@ if (GETPOST("menu_handler")) $menu_handler = GETPOST("menu_handler"); if ($action == 'update') { - if (!$_POST['cancel']) + if (!$cancel) { $leftmenu = ''; $mainmenu = ''; - if (!empty($_POST['menuIdParent']) && !is_numeric($_POST['menuIdParent'])) + if (GETPOST('menuIdParent', 'alpha') && !is_numeric(GETPOST('menuIdParent', 'alpha'))) { - $tmp = explode('&', $_POST['menuIdParent']); + $tmp = explode('&', GETPOST('menuIdParent', 'alpha')); foreach ($tmp as $s) { if (preg_match('/fk_mainmenu=/', $s)) @@ -138,7 +140,7 @@ if ($action == 'update') if ($action == 'add') { - if ($_POST['cancel']) + if ($cancel) { header("Location: ".DOL_URL_ROOT."/admin/menus/index.php?menu_handler=".$menu_handler); exit; diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 21d54908cf1..72eb8240c10 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -930,7 +930,7 @@ if ($mode == 'marketplace') ?>
- +
trans('Keyword') ?>:
diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index ca75eee69ef..d8c65f9a2c5 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -24,7 +24,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // This define $list require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; use OAuth\Common\Storage\DoliStorage; @@ -59,9 +59,18 @@ if ($action == 'setconst' && $user->admin) { $error = 0; $db->begin(); - foreach ($_POST['setupdriver'] as $setupconst) { + + $setupconstarray = GETPOST('setupdriver', 'array'); + + foreach ($setupconstarray as $setupconst) { //print '
'.print_r($setupconst, true).'
'; - $result = dolibarr_set_const($db, $setupconst['varname'], $setupconst['value'], 'chaine', 0, '', $conf->entity); + + $constname = dol_escape_htmltag($setupconst['varname']); + $constvalue = dol_escape_htmltag($setupconst['value']); + $consttype = dol_escape_htmltag($setupconst['type']); + $constnote = dol_escape_htmltag($setupconst['note']); + + $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity); if (!$result > 0) $error++; } @@ -119,6 +128,9 @@ $head = oauthadmin_prepare_head(); dol_fiche_head($head, 'tokengeneration', '', -1, 'technic'); +if (GETPOST('error')) { + setEventMessages(GETPOST('error'), null, 'errors'); +} if ($mode == 'setup' && $user->admin) { @@ -135,17 +147,21 @@ if ($mode == 'setup' && $user->admin) if ($key[0] == 'OAUTH_GITHUB_NAME') { $OAUTH_SERVICENAME = 'GitHub'; - $state='user,public_repo'; // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service) - $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?state='.$state.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'user,public_repo'; + $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms = 'https://github.com/settings/applications/'; } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') { $OAUTH_SERVICENAME = 'Google'; - $state='userinfo_email,userinfo_profile,cloud_print'; // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service) - //$state.=',gmail_full'; - $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state='.$state.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'userinfo_email,userinfo_profile,cloud_print'; + //$scope.=',gmail_full'; + $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); $urltocheckperms = 'https://security.google.com/settings/security/permissions'; } diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index df62acee3a4..496a32923f7 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -58,12 +58,13 @@ if ($action == 'update') dolibarr_set_const($db, "MAIN_PDF_MARGIN_TOP", $_POST["MAIN_PDF_MARGIN_TOP"], 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_PDF_MARGIN_BOTTOM", $_POST["MAIN_PDF_MARGIN_BOTTOM"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID1_IN_ADDRESS", $_POST["MAIN_PROFID1_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID2_IN_ADDRESS", $_POST["MAIN_PROFID2_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID3_IN_ADDRESS", $_POST["MAIN_PROFID3_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID4_IN_ADDRESS", $_POST["MAIN_PROFID4_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID5_IN_ADDRESS", $_POST["MAIN_PROFID5_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_PROFID6_IN_ADDRESS", $_POST["MAIN_PROFID6_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID1_IN_ADDRESS", GETPOST("MAIN_PROFID1_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID2_IN_ADDRESS", GETPOST("MAIN_PROFID2_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID3_IN_ADDRESS", GETPOST("MAIN_PROFID3_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID4_IN_ADDRESS", GETPOST("MAIN_PROFID4_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID5_IN_ADDRESS", GETPOST("MAIN_PROFID5_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_PROFID6_IN_ADDRESS", GETPOST("MAIN_PROFID6_IN_ADDRESS", "nohtml"), 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT", $_POST["MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT"], 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_TVAINTRA_NOT_IN_ADDRESS", $_POST["MAIN_TVAINTRA_NOT_IN_ADDRESS"], 'chaine', 0, '', $conf->entity); @@ -79,6 +80,9 @@ if ($action == 'update') dolibarr_set_const($db, "MAIN_PDF_MAIN_HIDE_SECOND_TAX", $_POST["MAIN_PDF_MAIN_HIDE_SECOND_TAX"], 'chaine', 0, '', $conf->entity); dolibarr_set_const($db, "MAIN_PDF_MAIN_HIDE_THIRD_TAX", $_POST["MAIN_PDF_MAIN_HIDE_THIRD_TAX"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "PDF_USE_ALSO_LANGUAGE_CODE", GETPOST('PDF_USE_ALSO_LANGUAGE_CODE', 'alpha'), 'chaine', 0, '', $conf->entity); + + header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; } @@ -295,6 +299,16 @@ print '
'.$langs->trans("ShowDetailsInPDFPageFoot").'
'.$langs->trans("PDF_USE_ALSO_LANGUAGE_CODE").''; +//if (! empty($conf->global->MAIN_MULTILANGS)) +//{ +print $formadmin->select_language(GETPOSTISSET('PDF_USE_ALSO_LANGUAGE_CODE') ? GETPOST('PDF_USE_ALSO_LANGUAGE_CODE') : $conf->global->PDF_USE_ALSO_LANGUAGE_CODE, 'PDF_USE_ALSO_LANGUAGE_CODE', 0, null, 1); +//} else { +// print ''.$langs->trans("MultiLangNotEnabled").''; +//} +print '
'; print ''; diff --git a/htdocs/admin/security_other.php b/htdocs/admin/security_other.php index e85853541de..f0ad4352b60 100644 --- a/htdocs/admin/security_other.php +++ b/htdocs/admin/security_other.php @@ -29,12 +29,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; // Load translation files required by the page -$langs->loadLangs(array("users","admin","other")); +$langs->loadLangs(array("users", "admin", "other")); -if (! $user->admin) +if (!$user->admin) accessforbidden(); -$action=GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); @@ -44,8 +44,8 @@ $action=GETPOST('action', 'alpha'); if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { - $code=$reg[1]; - $value=(GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); + $code = $reg[1]; + $value = (GETPOST($code, 'alpha') ? GETPOST($code, 'alpha') : 1); if (dolibarr_set_const($db, $code, $value, 'chaine', 0, '', $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); @@ -56,7 +56,7 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) dol_print_error($db); } } elseif (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { - $code=$reg[1]; + $code = $reg[1]; if (dolibarr_del_const($db, $code, $conf->entity) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); @@ -70,8 +70,8 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) elseif ($action == 'updateform') { - $res1=dolibarr_set_const($db, "MAIN_APPLICATION_TITLE", $_POST["MAIN_APPLICATION_TITLE"], 'chaine', 0, '', $conf->entity); - $res2=dolibarr_set_const($db, "MAIN_SESSION_TIMEOUT", $_POST["MAIN_SESSION_TIMEOUT"], 'chaine', 0, '', $conf->entity); + $res1 = dolibarr_set_const($db, "MAIN_APPLICATION_TITLE", GETPOST("MAIN_APPLICATION_TITLE", 'alphanohtml'), 'chaine', 0, '', $conf->entity); + $res2 = dolibarr_set_const($db, "MAIN_SESSION_TIMEOUT", GETPOST("MAIN_SESSION_TIMEOUT", 'alphanohtml'), 'chaine', 0, '', $conf->entity); if ($res1 && $res2) setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs'); } @@ -83,7 +83,7 @@ elseif ($action == 'updateform') $form = new Form($db); -$wikihelp='EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; +$wikihelp = 'EN:Setup_Security|FR:Paramétrage_Sécurité|ES:Configuración_Seguridad'; llxHeader('', $langs->trans("Miscellaneous"), $wikihelp); print load_fiche_titre($langs->trans("SecuritySetup"), '', 'title_setup'); @@ -97,7 +97,7 @@ print ''; print ''; print ''; -$head=security_prepare_head(); +$head = security_prepare_head(); dol_fiche_head($head, 'misc', $langs->trans("Security"), -1); @@ -115,7 +115,7 @@ print ''.$langs->trans("UseCaptchaCode").''; print ''; if (function_exists("imagecreatefrompng")) { - if (! empty($conf->use_javascript_ajax)) + if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('MAIN_SECURITY_ENABLECAPTCHA'); } @@ -142,7 +142,7 @@ print ''; print ''; print ''.$langs->trans("UseAdvancedPerms").''; print ''; -if (! empty($conf->use_javascript_ajax)) +if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff('MAIN_USE_ADVANCED_PERMS'); } @@ -173,8 +173,8 @@ print ''.$langs->trans("Value").''; print "\n"; -$sessiontimeout=ini_get("session.gc_maxlifetime"); -if (empty($conf->global->MAIN_SESSION_TIMEOUT)) $conf->global->MAIN_SESSION_TIMEOUT=$sessiontimeout; +$sessiontimeout = ini_get("session.gc_maxlifetime"); +if (empty($conf->global->MAIN_SESSION_TIMEOUT)) $conf->global->MAIN_SESSION_TIMEOUT = $sessiontimeout; print ''; print ''.$langs->trans("SessionTimeOut").''; print $form->textwithpicto('', $langs->trans("SessionExplanation", ini_get("session.gc_probability"), ini_get("session.gc_divisor"))); @@ -185,8 +185,8 @@ print ''; print ''; -$sessiontimeout=ini_get("session.gc_maxlifetime"); -if (empty($conf->global->MAIN_APPLICATION_TITLE)) $conf->global->MAIN_APPLICATION_TITLE=""; +$sessiontimeout = ini_get("session.gc_maxlifetime"); +if (empty($conf->global->MAIN_APPLICATION_TITLE)) $conf->global->MAIN_APPLICATION_TITLE = ""; print ''; print ''.$langs->trans("MAIN_APPLICATION_TITLE").''; print ''; diff --git a/htdocs/admin/sms.php b/htdocs/admin/sms.php index b725a2e50ae..4a70104158b 100644 --- a/htdocs/admin/sms.php +++ b/htdocs/admin/sms.php @@ -28,6 +28,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page $langs->loadLangs(array("companies", "admin", "products", "sms", "other", "errors")); +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button + if (!$user->admin) accessforbidden(); @@ -46,14 +48,13 @@ $action = GETPOST('action', 'aZ09'); * Actions */ -if ($action == 'update' && empty($_POST["cancel"])) +if ($action == 'update' && !$cancel) { - dolibarr_set_const($db, "MAIN_DISABLE_ALL_SMS", $_POST["MAIN_DISABLE_ALL_SMS"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_DISABLE_ALL_SMS", GETPOST("MAIN_DISABLE_ALL_SMS", 'alphanohtml'), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_SMS_SENDMODE", $_POST["MAIN_SMS_SENDMODE"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_SMS_SENDMODE", GETPOST("MAIN_SMS_SENDMODE", 'alphahtml'), 'chaine', 0, '', $conf->entity); - dolibarr_set_const($db, "MAIN_MAIL_SMS_FROM", $_POST["MAIN_MAIL_SMS_FROM"], 'chaine', 0, '', $conf->entity); - //dolibarr_set_const($db, "MAIN_MAIL_AUTOCOPY_TO", $_POST["MAIN_MAIL_AUTOCOPY_TO"], 'chaine', 0, '', $conf->entity); + dolibarr_set_const($db, "MAIN_MAIL_SMS_FROM", GETPOST("MAIN_MAIL_SMS_FROM", 'alphanohtml'), 'chaine', 0, '', $conf->entity); header("Location: ".$_SERVER["PHP_SELF"]."?mainmenu=home&leftmenu=setup"); exit; @@ -68,15 +69,15 @@ if ($action == 'send' && !$_POST['cancel']) $error = 0; $smsfrom = ''; - if (!empty($_POST["fromsms"])) $smsfrom = GETPOST("fromsms"); - if (empty($smsfrom)) $smsfrom = GETPOST("fromname"); - $sendto = GETPOST("sendto"); - $body = GETPOST('message'); - $deliveryreceipt = GETPOST("deliveryreceipt"); - $deferred = GETPOST('deferred'); - $priority = GETPOST('priority'); - $class = GETPOST('class'); - $errors_to = GETPOST("errorstosms"); + if (!empty($_POST["fromsms"])) $smsfrom = GETPOST("fromsms", 'alphanohtml'); + if (empty($smsfrom)) $smsfrom = GETPOST("fromname", 'alphanohtml'); + $sendto = GETPOST("sendto", 'alphanohtml'); + $body = GETPOST('message', 'alphanohtml'); + $deliveryreceipt = GETPOST("deliveryreceipt", 'alphanohtml'); + $deferred = GETPOST('deferred', 'alphanohtml'); + $priority = GETPOST('priority', 'alphanohtml'); + $class = GETPOST('class', 'alphanohtml'); + $errors_to = GETPOST("errorstosms", 'alphanohtml'); // Create form object include_once DOL_DOCUMENT_ROOT.'/core/class/html.formsms.class.php'; diff --git a/htdocs/admin/spip.php b/htdocs/admin/spip.php index 5b5bf692e22..2ed43e97efd 100644 --- a/htdocs/admin/spip.php +++ b/htdocs/admin/spip.php @@ -35,10 +35,10 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "members", "mailmanspip")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); -$type=array('yesno','texte','chaine'); +$type = array('yesno', 'texte', 'chaine'); $action = GETPOST('action', 'aZ09'); @@ -50,25 +50,27 @@ $action = GETPOST('action', 'aZ09'); // Action mise a jour ou ajout d'une constante if ($action == 'update' || $action == 'add') { - $constname=GETPOST("constname"); - $constvalue=GETPOST("constvalue"); + $constnamearray = GETPOST("constname", 'array'); + $constvaluearray = GETPOST("constvalue", 'array'); + $consttypearray = GETPOST("consttype", 'array'); + $constnotearray = GETPOST("constnote", 'array'); // Action mise a jour ou ajout d'une constante if ($action == 'update' || $action == 'add') { - foreach($_POST['constname'] as $key => $val) + foreach ($constnamearray as $key => $val) { - $constname=$_POST["constname"][$key]; - $constvalue=$_POST["constvalue"][$key]; - $consttype=$_POST["consttype"][$key]; - $constnote=$_POST["constnote"][$key]; + $constname = dol_escape_htmltag($constnamearray[$key]); + $constvalue = dol_escape_htmltag($constvaluearray[$key]); + $consttype = dol_escape_htmltag($consttypearray[$key]); + $constnote = dol_escape_htmltag($constnotearray[$key]); - $res=dolibarr_set_const($db, $constname, $constvalue, $type[$consttype], 0, $constnote, $conf->entity); + $res = dolibarr_set_const($db, $constname, $constvalue, $type[$consttype], 0, $constnote, $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; } - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -82,7 +84,7 @@ if ($action == 'update' || $action == 'add') // Action activation d'un sous module du module adherent if ($action == 'set') { - $result=dolibarr_set_const($db, $_GET["name"], $_GET["value"], '', 0, '', $conf->entity); + $result = dolibarr_set_const($db, $_GET["name"], $_GET["value"], '', 0, '', $conf->entity); if ($result < 0) { dol_print_error($db); @@ -92,7 +94,7 @@ if ($action == 'set') // Action desactivation d'un sous module du module adherent if ($action == 'unset') { - $result=dolibarr_del_const($db, $_GET["name"], $conf->entity); + $result = dolibarr_del_const($db, $_GET["name"], $conf->entity); if ($result < 0) { dol_print_error($db); @@ -105,12 +107,12 @@ if ($action == 'unset') * View */ -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans("MailmanSpipSetup"), $help_url); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("MailmanSpipSetup"), $linkback, 'title_setup'); @@ -120,7 +122,7 @@ $head = mailmanspip_admin_prepare_head(); /* * Spip */ -if (! empty($conf->global->ADHERENT_USE_SPIP)) +if (!empty($conf->global->ADHERENT_USE_SPIP)) { print ''; print ''; @@ -129,12 +131,12 @@ if (! empty($conf->global->ADHERENT_USE_SPIP)) dol_fiche_head($head, 'spip', $langs->trans("Setup"), -1, 'user'); //$link=img_picto($langs->trans("Active"),'tick').' '; - $link=''; + $link = ''; //$link.=$langs->trans("Disable"); - $link.=img_picto($langs->trans("Activated"), 'switch_on'); - $link.=''; + $link .= img_picto($langs->trans("Activated"), 'switch_on'); + $link .= ''; // Edition des varibales globales - $constantes=array( + $constantes = array( 'ADHERENT_SPIP_SERVEUR', 'ADHERENT_SPIP_DB', 'ADHERENT_SPIP_USER', @@ -156,10 +158,10 @@ else { dol_fiche_head($head, 'spip', $langs->trans("Setup"), 0, 'user'); - $link=''; + $link = ''; //$link.=$langs->trans("Activate"); - $link.=img_picto($langs->trans("Disabled"), 'switch_off'); - $link.=''; + $link .= img_picto($langs->trans("Disabled"), 'switch_off'); + $link .= ''; print load_fiche_titre($langs->trans('SPIPTitle'), $link, ''); dol_fiche_end(); diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index f1cbea504d3..0b6987b1a9f 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -213,7 +213,7 @@ $found=0; print ''; print ''.$langs->trans("ReStockOnBill").''; print ''; -if (! empty($conf->fournisseur->enabled)) +if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || ! empty($conf->supplier_order->enabled) || ! empty($conf->supplier_invoice->enabled)) { if ($conf->use_javascript_ajax) { print ajax_constantonoff('STOCK_CALCULATE_ON_SUPPLIER_BILL'); @@ -234,7 +234,7 @@ $found++; print ''; print ''.$langs->trans("ReStockOnValidateOrder").''; print ''; -if (! empty($conf->fournisseur->enabled)) +if (! empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || ! empty($conf->supplier_order->enabled) || ! empty($conf->supplier_invoice->enabled)) { if ($conf->use_javascript_ajax) { print ajax_constantonoff('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER'); diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index 9a17916cb49..977b99d0c99 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -171,7 +171,7 @@ if ($action == 'setmod') if ($action == 'addcat') { $fourn = new Fournisseur($db); - $fourn->CreateCategory($user, $_POST["cat"]); + $fourn->CreateCategory($user, GETPOST('cat', 'alphanohtml')); } if ($action == 'set_SUPPLIER_INVOICE_FREE_TEXT') diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index 15e1a452dff..db9b3e257f6 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -54,6 +54,8 @@ $specimenthirdparty->initAsSpecimen(); * Actions */ +include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; + if ($action == 'updateMask') { $maskconstorder = GETPOST('maskconstorder', 'alpha'); @@ -163,7 +165,7 @@ elseif ($action == 'setmod') elseif ($action == 'addcat') { $fourn = new Fournisseur($db); - $fourn->CreateCategory($user, $_POST["cat"]); + $fourn->CreateCategory($user, GETPOST('cat', 'alphanohtml')); } elseif ($action == 'set_SUPPLIER_ORDER_OTHER') diff --git a/htdocs/admin/system/about.php b/htdocs/admin/system/about.php index 64f8fba72ad..3cfc18accc9 100644 --- a/htdocs/admin/system/about.php +++ b/htdocs/admin/system/about.php @@ -86,31 +86,31 @@ print ''; if (preg_match('/^fr_/i', $langs->getDefaultLang())) { print '
  • '; - print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("France")).''; + print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("France")).''; print '
  • '; } if (preg_match('/^el_/i', $langs->getDefaultLang())) { print '
  • '; - print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Greece")).''; + print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Greece")).''; print '
  • '; } if (preg_match('/^es_/i', $langs->getDefaultLang())) { print '
  • '; - print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Spain")).''; + print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Spain")).''; print '
  • '; } if (preg_match('/^it_/i', $langs->getDefaultLang())) { print '
  • '; - print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Italy")).''; + print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Italy")).''; print '
  • '; } if (preg_match('/^de_/i', $langs->getDefaultLang())) { print '
  • '; - print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Germany")).''; + print ''.$langs->trans("OfficialWebSiteLocal", $langs->transnoentitiesnoconv("Germany")).''; print '
  • '; } print '
  • '; diff --git a/htdocs/admin/system/perf.php b/htdocs/admin/system/perf.php index 3dae3c91f9d..42c66281450 100644 --- a/htdocs/admin/system/perf.php +++ b/htdocs/admin/system/perf.php @@ -53,10 +53,10 @@ print $langs->trans("YouMayFindPerfAdviceHere", 'https://wiki.dolibarr.org/index // Recupere la version de PHP $phpversion=version_php(); -print "
    PHP - ".$langs->trans("Version").": ".$phpversion."
    \n"; +print "
    PHP - ".$langs->trans("Version").": ".$phpversion."
    \n"; // Recupere la version du serveur web -print "
    Web server - ".$langs->trans("Version").": ".$_SERVER["SERVER_SOFTWARE"]."
    \n"; +print "
    Web server - ".$langs->trans("Version").": ".$_SERVER["SERVER_SOFTWARE"]."
    \n"; // XDebug print '
    '; @@ -65,8 +65,8 @@ $test=!function_exists('xdebug_is_enabled'); if ($test) print img_picto('', 'tick.png').' '.$langs->trans("NotInstalled"); else { - print img_picto('', 'warning').' '.$langs->trans("XDebugInstalled"); - print ' '.$langs->trans("MoreInformation").' XDebug admin page'; + print img_picto('', 'warning').' '.$langs->trans("ModuleActivated", $langs->transnoentities("XDebug")); + print ' - '.$langs->trans("MoreInformation").' XDebug admin page'; } print '
    '; diff --git a/htdocs/admin/ticket.php b/htdocs/admin/ticket.php index dba1f827748..cd982ef0f5c 100644 --- a/htdocs/admin/ticket.php +++ b/htdocs/admin/ticket.php @@ -197,6 +197,7 @@ dol_fiche_end(); print load_fiche_titre($langs->trans("TicketNumberingModules")); +print '
    '; print ''; print ''; print ''; @@ -287,7 +288,9 @@ foreach ($dirmodels as $reldir) { } } -print '
    '.$langs->trans("Name").'

    '; +print ''; +print '
    '; +print '
    '; if (!$conf->use_javascript_ajax) { print ''; diff --git a/htdocs/admin/ticket_public.php b/htdocs/admin/ticket_public.php index a4098e52247..6b8a23c94fc 100644 --- a/htdocs/admin/ticket_public.php +++ b/htdocs/admin/ticket_public.php @@ -167,7 +167,7 @@ $head = ticketAdminPrepareHead(); dol_fiche_head($head, 'public', $langs->trans("Module56000Name"), -1, "ticket"); -print ''.$langs->trans("TicketPublicAccess").' : '.dol_buildpath('/public/ticket/index.php', 2).''; +print ''.$langs->trans("TicketPublicAccess").' : '.dol_buildpath('/public/ticket/index.php', 2).''; dol_fiche_end(); @@ -176,14 +176,14 @@ $enabledisablehtml = $langs->trans("TicketsActivatePublicInterface").' '; if (empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) { // Button off, click to enable - $enabledisablehtml .= ''; + $enabledisablehtml .= ''; $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); $enabledisablehtml .= ''; } else { // Button on, click to disable - $enabledisablehtml .= ''; + $enabledisablehtml .= ''; $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); $enabledisablehtml .= ''; } @@ -200,6 +200,7 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) print ''; } + print '
    '; print ''; print ''; print ''; } - print '
    '.$langs->trans("Parameters").''; @@ -279,7 +280,9 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) print '

    '; + print ''; + print '
    '; + print '
    '; if (!$conf->use_javascript_ajax) { print ''; @@ -288,6 +291,7 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) // Admin var of module print load_fiche_titre($langs->trans("TicketParamMail")); + print '
    '; print ''; print ''; @@ -369,13 +373,14 @@ if (!empty($conf->global->TICKET_ENABLE_PUBLIC_INTERFACE)) $url_interface = $conf->global->TICKET_URL_PUBLIC_INTERFACE; print ''; + print ''; print ''; print ''; print '
    '.$langs->trans("TicketUrlPublicInterfaceLabelAdmin").''; print ''; - print ''; print $form->textwithpicto('', $langs->trans("TicketUrlPublicInterfaceHelpAdmin"), 1, 'help'); print '
    '; + print '
    '; print '
    '; diff --git a/htdocs/admin/tools/dolibarr_export.php b/htdocs/admin/tools/dolibarr_export.php index 854fd130bc5..05546fdee5a 100644 --- a/htdocs/admin/tools/dolibarr_export.php +++ b/htdocs/admin/tools/dolibarr_export.php @@ -33,7 +33,7 @@ $action = GETPOST('action', 'alpha'); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (!$sortorder) $sortorder = "DESC"; if (!$sortfield) $sortfield = "date"; if (empty($page) || $page == -1) { $page = 0; } diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index e05e4fc143d..f2e423d9174 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -39,7 +39,7 @@ $file=GETPOST('filename_template', 'alpha'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; if (! $sortorder) $sortorder="DESC"; diff --git a/htdocs/admin/tools/export_files.php b/htdocs/admin/tools/export_files.php index c1c641b82f2..dec8da6aa53 100644 --- a/htdocs/admin/tools/export_files.php +++ b/htdocs/admin/tools/export_files.php @@ -41,7 +41,7 @@ $file = preg_replace('/(\.zip|\.tar|\.tgz|\.gz|\.tar\.gz|\.bz2)$/i', '', $file); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (! $sortorder) $sortorder="DESC"; if (! $sortfield) $sortfield="date"; if ($page < 0) { $page = 0; } diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index 52717200bce..f57a16332df 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -48,7 +48,7 @@ $langs->loadLangs(array("companies", "admin", "users", "other")); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/admin/tools/listsessions.php b/htdocs/admin/tools/listsessions.php index d909dc8610b..28d4fc3d51f 100644 --- a/htdocs/admin/tools/listsessions.php +++ b/htdocs/admin/tools/listsessions.php @@ -43,7 +43,7 @@ if ($user->socid > 0) $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index c641be11a59..cad874d89b2 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -45,7 +45,7 @@ $mode = GETPOST('mode', 'aZ09') ?GETPOST('mode', 'aZ09') : 'overwrite'; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index d639b8d2a9b..dd7fd353ea2 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -34,13 +34,13 @@ require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; // Load translation files required by the page $langs->loadlangs(array('errors', 'admin', 'companies', 'website')); -$action=GETPOST('action', 'alpha')?GETPOST('action', 'alpha'):'view'; -$confirm=GETPOST('confirm', 'alpha'); +$action = GETPOST('action', 'alpha') ?GETPOST('action', 'alpha') : 'view'; +$confirm = GETPOST('confirm', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); -$rowid=GETPOST('rowid', 'alpha'); +$rowid = GETPOST('rowid', 'alpha'); -$id=1; +$id = 1; if (!$user->admin) accessforbidden(); @@ -52,10 +52,10 @@ $actl[1] = img_picto($langs->trans("Activated"), 'switch_on'); $status = 1; // Load variable for pagination -$limit = GETPOST('limit', 'int')?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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -65,55 +65,55 @@ $pagenext = $page + 1; $hookmanager->initHooks(array('website')); // Name of SQL tables of dictionaries -$tabname=array(); +$tabname = array(); $tabname[1] = MAIN_DB_PREFIX."website"; // Dictionary labels -$tablib=array(); +$tablib = array(); $tablib[1] = "Websites"; // Requests to extract data -$tabsql=array(); +$tabsql = array(); $tabsql[1] = "SELECT f.rowid as rowid, f.entity, f.ref, f.description, f.virtualhost, f.status FROM ".MAIN_DB_PREFIX.'website as f WHERE f.entity IN ('.getEntity('website').')'; // Criteria to sort dictionaries -$tabsqlsort=array(); -$tabsqlsort[1] ="ref ASC"; +$tabsqlsort = array(); +$tabsqlsort[1] = "ref ASC"; // Nom des champs en resultat de select pour affichage du dictionnaire -$tabfield=array(); +$tabfield = array(); $tabfield[1] = "ref,description,virtualhost"; // Nom des champs d'edition pour modification d'un enregistrement -$tabfieldvalue=array(); +$tabfieldvalue = array(); $tabfieldvalue[1] = "ref,description,virtualhost"; // Nom des champs dans la table pour insertion d'un enregistrement -$tabfieldinsert=array(); +$tabfieldinsert = array(); $tabfieldinsert[1] = "ref,description,virtualhost,entity"; // Nom du rowid si le champ n'est pas de type autoincrement // Example: "" if id field is "rowid" and has autoincrement on // "nameoffield" if id field is not "rowid" or has not autoincrement on -$tabrowid=array(); +$tabrowid = array(); $tabrowid[1] = ""; // Condition to show dictionary in setup page -$tabcond=array(); -$tabcond[1] = (! empty($conf->website->enabled)); +$tabcond = array(); +$tabcond[1] = (!empty($conf->website->enabled)); // List of help for fields -$tabhelp=array(); -$tabhelp[1] = array('ref'=>$langs->trans("EnterAnyCode"), 'virtualhost'=>$langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/websiteref')); +$tabhelp = array(); +$tabhelp[1] = array('ref'=>$langs->trans("EnterAnyCode"), 'virtualhost'=>$langs->trans("SetHereVirtualHost", DOL_DATA_ROOT.'/website/websiteref')); // List of check for fields (NOT USED YET) -$tabfieldcheck=array(); -$tabfieldcheck[1] = array(); +$tabfieldcheck = array(); +$tabfieldcheck[1] = array(); // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); -$sourceList=array(); +$sourceList = array(); /* @@ -123,35 +123,35 @@ $sourceList=array(); // Actions add or modify a website if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield=explode(',', $tabfield[$id]); - $listfieldinsert=explode(',', $tabfieldinsert[$id]); - $listfieldmodify=explode(',', $tabfieldinsert[$id]); - $listfieldvalue=explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', $tabfield[$id]); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); // Check that all fields are filled - $ok=1; + $ok = 1; foreach ($listfield as $f => $value) { - if ($value == 'ref' && (! isset($_POST[$value]) || $_POST[$value]=='')) + if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) { - $ok=0; - $fieldnamekey=$listfield[$f]; + $ok = 0; + $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); break; } - elseif ($value == 'ref' && ! preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) + elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) { - $ok=0; - $fieldnamekey=$listfield[$f]; + $ok = 0; + $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors'); break; } } // Clean parameters - if (! empty($_POST['ref'])) + if (!empty($_POST['ref'])) { - $websitekey=strtolower($_POST['ref']); + $websitekey = strtolower($_POST['ref']); } // Si verif ok et action add, on ajoute la ligne @@ -160,13 +160,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($tabrowid[$id]) { // Recupere id libre pour insertion - $newid=0; + $newid = 0; $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; $result = $db->query($sql); if ($result) { $obj = $db->fetch_object($result); - $newid=($obj->newid + 1); + $newid = ($obj->newid + 1); } else { dol_print_error($db); } @@ -181,16 +181,16 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Add new entry $sql = "INSERT INTO ".$tabname[$id]." ("; // List of fields - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $tabrowid[$id].","; - $sql.= $tabfieldinsert[$id]; - $sql.=",status)"; - $sql.= " VALUES("; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",status)"; + $sql .= " VALUES("; // List of values - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldinsert)) - $sql.= $newid.","; - $i=0; + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; foreach ($listfieldinsert as $f => $value) { if ($value == 'entity') { @@ -199,19 +199,19 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($value == 'ref') { $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); } - if ($i) $sql.=","; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.=",1)"; + $sql .= ",1)"; dol_syslog("actionadd", LOG_DEBUG); $result = $db->query($sql); if ($result) // Add is ok { setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - unset($_POST); // Clean $_POST array, we keep only + unset($_POST); // Clean $_POST array, we keep only } else { @@ -227,22 +227,22 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) // Si verif ok et action modify, on modifie la ligne if ($ok && GETPOST('actionmodify', 'alpha')) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } $db->begin(); - $website=new Website($db); - $rowid=GETPOST('rowid', 'int'); + $website = new Website($db); + $rowid = GETPOST('rowid', 'int'); $website->fetch($rowid); // Modify entry $sql = "UPDATE ".$tabname[$id]." SET "; // Modifie valeur des champs - if ($tabrowid[$id] && ! in_array($tabrowid[$id], $listfieldmodify)) + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) { - $sql.= $tabrowid[$id]."="; - $sql.= "'".$db->escape($rowid)."', "; + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; } $i = 0; foreach ($listfieldmodify as $field) @@ -250,13 +250,13 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) if ($field == 'entity') { $_POST[$listfieldvalue[$i]] = $conf->entity; } - if ($i) $sql.=","; - $sql.= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql.="null"; - else $sql.="'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; $i++; } - $sql.= " WHERE ".$rowidcol." = '".$rowid."'"; + $sql .= " WHERE ".$rowidcol." = '".$rowid."'"; dol_syslog("actionmodify", LOG_DEBUG); //print $sql; @@ -266,8 +266,8 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); if ($newname != $website->ref) { - $srcfile=DOL_DATA_ROOT.'/website/'.$website->ref; - $destfile=DOL_DATA_ROOT.'/website/'.$newname; + $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; + $destfile = DOL_DATA_ROOT.'/website/'.$newname; if (dol_is_dir($destfile)) { @@ -294,7 +294,7 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) setEventMessages($db->lasterror(), null, 'errors'); } - if (! $error) + if (!$error) { $db->commit(); } @@ -313,8 +313,8 @@ if (GETPOST('actioncancel', 'alpha')) if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } $website = new Website($db); $website->fetch($rowid); @@ -332,7 +332,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid ='".$rowid."'"; $result = $db->query($sql); - if (! $result) + if (!$result) { if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') { @@ -358,8 +358,8 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // delete // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid ='".$rowid."'"; @@ -375,8 +375,8 @@ if ($action == $acts[0]) // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol=$tabrowid[$id]; } - else { $rowidcol="rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } + else { $rowidcol = "rowid"; } if ($rowid) { $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid ='".$rowid."'"; @@ -396,16 +396,16 @@ if ($action == $acts[1]) */ $form = new Form($db); -$formadmin=new FormAdmin($db); +$formadmin = new FormAdmin($db); llxHeader('', $langs->trans("WebsiteSetup")); -$titre=$langs->trans("WebsiteSetup"); -$linkback=''.$langs->trans("BackToModuleList").''; +$titre = $langs->trans("WebsiteSetup"); +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($titre, $linkback, 'title_setup'); // Onglets -$head=array(); +$head = array(); $h = 0; $head[$h][0] = DOL_URL_ROOT."/admin/website.php"; @@ -428,7 +428,7 @@ print "
    \n"; // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -438,12 +438,12 @@ if ($action == 'delete') if ($id) { // Complete requete recherche valeurs avec critere de tri - $sql=$tabsql[$id]; - $sql.=$db->order($sortfield, $sortorder); - $sql.=$db->plimit($limit+1, $offset); + $sql = $tabsql[$id]; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit + 1, $offset); //print $sql; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); print ''; print ''; @@ -452,10 +452,10 @@ if ($id) // Form to add a new line if ($tabname[$id]) { - $alabelisused=0; - $var=false; + $alabelisused = 0; + $var = false; - $fieldlist=explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); // Line for title print ''; @@ -463,15 +463,15 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - $align=''; - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $align = ''; + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } if ($valuetoshow != '') { print ''; - if (! empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (! empty($tabhelp[$id][$value])) + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) { if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); @@ -479,7 +479,7 @@ if ($id) else print $valuetoshow; print ''; } - if ($fieldlist[$field]=='libelle' || $fieldlist[$field]=='label') $alabelisused=1; + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; @@ -496,7 +496,7 @@ if ($id) foreach ($fieldlist as $key=>$val) { if (GETPOST($val, 'alpha')) - $obj->$val=GETPOST($val); + $obj->$val = GETPOST($val); } } @@ -510,7 +510,7 @@ if ($id) print ''; print ""; - $colspan=count($fieldlist)+2; + $colspan = count($fieldlist) + 2; } print ''; @@ -518,7 +518,7 @@ if ($id) // List of websites in database - $resql=$db->query($sql); + $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); @@ -540,10 +540,10 @@ if ($id) { // Determine le nom du champ par rapport aux noms possibles // dans les dictionnaires de donnees - $showfield=1; // Par defaut - $align="left"; - $sortable=1; - $valuetoshow=''; + $showfield = 1; // Par defaut + $align = "left"; + $sortable = 1; + $valuetoshow = ''; /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; @@ -551,20 +551,20 @@ if ($id) $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow=ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow=$langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field]=='lang') { $valuetoshow=$langs->trans("Language"); } - if ($fieldlist[$field]=='type') { $valuetoshow=$langs->trans("Type"); } - if ($fieldlist[$field]=='code') { $valuetoshow=$langs->trans("Code"); } + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } // Affiche nom du champ if ($showfield) { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable?$fieldlist[$field]:''), ($page?'page='.$page.'&':''), "", "align=".$align, $sortfield, $sortorder); + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); } } - print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page?'page='.$page.'&':''), "", 'align="center"', $sortfield, $sortorder); + print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page ? 'page='.$page.'&' : ''), "", 'align="center"', $sortfield, $sortorder); print getTitleFieldOfList(''); print getTitleFieldOfList(''); print ''; @@ -575,34 +575,34 @@ if ($id) $obj = $db->fetch_object($resql); //print_r($obj); print ''; - if ($action == 'edit' && ($rowid == (! empty($obj->rowid)?$obj->rowid:$obj->code))) + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) { - $tmpaction='edit'; - $parameters=array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); - print ' '; + print ' '; print ' '; } else { $tmpaction = 'view'; - $parameters=array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook=$hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error=$hookmanager->error; $errors=$hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; if (empty($reshook)) { foreach ($fieldlist as $field => $value) { - $showfield=1; - $align="left"; - $fieldname=$fieldlist[$field]; - $valuetoshow=$obj->$fieldname; + $showfield = 1; + $align = "left"; + $fieldname = $fieldlist[$field]; + $valuetoshow = $obj->$fieldname; // Show value for field if ($showfield) print ''.$valuetoshow.''; @@ -610,14 +610,14 @@ if ($id) } // Can an entry be erased or disabled ? - $iserasable=1; $isdisable=1; // true by default - if ($obj->status) $iserasable=0; // We can't delete a website on. Disable it first. + $iserasable = 1; $isdisable = 1; // true by default + if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. - $url = $_SERVER["PHP_SELF"].'?'.($page?'page='.$page.'&':'').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(! empty($obj->rowid)?$obj->rowid:(! empty($obj->code)?$obj->code:'')).'&code='.(! empty($obj->code)?urlencode($obj->code):'').'&'; + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; // Active print ''; - print ''.$actl[($obj->status?1:0)].''; + print ''.$actl[($obj->status ? 1 : 0)].''; print ""; // Modify link @@ -660,10 +660,10 @@ $db->close(); */ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') { - global $conf,$langs,$db; + global $conf, $langs, $db; global $form; global $region_id; - global $elementList,$sourceList,$localtax_typeList; + global $elementList, $sourceList, $localtax_typeList; global $bc; $formadmin = new FormAdmin($db); @@ -678,18 +678,18 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->$fieldname)) { - print ''; + print ''; } else { print ''; - $size=''; - if ($fieldlist[$field]=='code') $size='size="8" '; - if ($fieldlist[$field]=='position') $size='size="4" '; - if ($fieldlist[$field]=='libelle') $size='size="32" '; - if ($fieldlist[$field]=='tracking') $size='size="92" '; - if ($fieldlist[$field]=='sortorder') $size='size="2" '; - print ''; + $size = ''; + if ($fieldlist[$field] == 'code') $size = 'size="8" '; + if ($fieldlist[$field] == 'position') $size = 'size="4" '; + if ($fieldlist[$field] == 'libelle') $size = 'size="32" '; + if ($fieldlist[$field] == 'tracking') $size = 'size="92" '; + if ($fieldlist[$field] == 'sortorder') $size = 'size="2" '; + print ''; print ''; } } diff --git a/htdocs/admin/website_options.php b/htdocs/admin/website_options.php index 92c16a1123e..7d16aa3963b 100644 --- a/htdocs/admin/website_options.php +++ b/htdocs/admin/website_options.php @@ -48,7 +48,7 @@ $status = 1; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/api/admin/explorer.php b/htdocs/api/admin/explorer.php index ac267d29bc3..22263b8b9ba 100644 --- a/htdocs/api/admin/explorer.php +++ b/htdocs/api/admin/explorer.php @@ -25,6 +25,8 @@ * \file htdocs/api/admin/explorer.php */ +use Luracast\Restler\Routes; + require_once '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php'; diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index 90bc9acd2fd..73041f6c386 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -96,7 +96,7 @@ llxHeader(); $linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($langs->trans("ApiSetup"), $linkback, 'title_setup'); -print $langs->trans("ApiDesc")."
    \n"; +print ''.$langs->trans("ApiDesc")."
    \n"; print "
    \n"; print ''; @@ -130,7 +130,9 @@ print ' '; print ''; print ''; -print ''.$langs->trans("RESTRICT_API_ON_IP").''; +print ''.$langs->trans("RESTRICT_ON_IP"); +print ' '.$langs->trans("Example").': '.$langs->trans("IPListExample"); +print ''; print ''; print ''; print ''; diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 4785ab78174..e58ebf7d280 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -60,10 +60,9 @@ class Documents extends DolibarrApi * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf) * @return array List of documents * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 200 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 * * @url GET /download */ @@ -81,7 +80,18 @@ class Documents extends DolibarrApi //--- Finds and returns the document $entity = $conf->entity; - $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, DolibarrApiAccess::$user, '', 'read'); + // Special cases that need to use get_exdir to get real dir of object + // If future, all object should use this to define path of documents. + /* + $tmpreldir = ''; + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } + + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ + $relativefile = $original_file; + + $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read'); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $original_file = $check_access['original_file']; @@ -118,12 +128,11 @@ class Documents extends DolibarrApi * @param string $langcode Language code like 'en_US', 'fr_FR', 'es_ES', ... (If not set, use the default language). * @return array List of documents * - * @throws 500 - * @throws 501 - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 200 + * @throws RestException 500 + * @throws RestException 501 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 * * @url PUT /builddoc */ @@ -148,7 +157,18 @@ class Documents extends DolibarrApi //--- Finds and returns the document $entity = $conf->entity; - $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, DolibarrApiAccess::$user, '', 'write'); + // Special cases that need to use get_exdir to get real dir of object + // If future, all object should use this to define path of documents. + /* + $tmpreldir = ''; + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } + + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ + $relativefile = $original_file; + + $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $original_file = $check_access['original_file']; @@ -230,18 +250,17 @@ class Documents extends DolibarrApi /** * Return the list of documents of a dedicated element (from its ID or Ref) * - * @param string $modulepart Name of module or area concerned ('thirdparty', 'member', 'proposal', 'order', 'invoice', 'shipment', 'project', ...) + * @param string $modulepart Name of module or area concerned ('thirdparty', 'member', 'proposal', 'order', 'invoice', 'supplier_invoice', 'shipment', 'project', ...) * @param int $id ID of element * @param string $ref Ref of element * @param string $sortfield Sort criteria ('','fullname','relativename','name','date','size') * @param string $sortorder Sort order ('asc' or 'desc') * @return array Array of documents with path * - * @throws 200 - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * * @url GET / */ @@ -275,6 +294,23 @@ class Documents extends DolibarrApi $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; } + elseif ($modulepart == 'user') + { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + + // Can get doc if has permission to read all user or if it is user itself + if (!DolibarrApiAccess::$user->rights->user->user->lire && DolibarrApiAccess::$user->id != $id) { + throw new RestException(401); + } + + $object = new User($this->db); + $result = $object->fetch($id, $ref); + if (!$result) { + throw new RestException(404, 'User not found'); + } + + $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; + } elseif ($modulepart == 'adherent' || $modulepart == 'member') { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; @@ -355,6 +391,24 @@ class Documents extends DolibarrApi $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); } + elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') + { + $modulepart = 'supplier_invoice'; + + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + + if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) { + throw new RestException(401); + } + + $object = new FactureFournisseur($this->db); + $result = $object->fetch($id, $ref); + if (!$result) { + throw new RestException(404, 'Invoice not found'); + } + + $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); + } elseif ($modulepart == 'produit' || $modulepart == 'product') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; @@ -387,6 +441,22 @@ class Documents extends DolibarrApi $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); } + elseif ($modulepart == 'expensereport') + { + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + + if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { + throw new RestException(401); + } + + $object = new ExpenseReport($this->db); + $result = $object->fetch($id, $ref); + if (!$result) { + throw new RestException(404, 'Expense report not found'); + } + + $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); + } else { throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); @@ -418,8 +488,9 @@ class Documents extends DolibarrApi /** * Upload a file. * - * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. - * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "image/mywebsite", "filecontent": "Y29udGVudCB0ZXh0Cg==", "fileencoding": "base64", "overwriteifexists": "0" }. + * Test sample for invoice: { "filename": "mynewfile.txt", "modulepart": "invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * Test sample for supplier invoice: { "filename": "mynewfile.txt", "modulepart": "supplier_invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. + * Test sample for medias file: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "image/mywebsite", "filecontent": "Y29udGVudCB0ZXh0Cg==", "fileencoding": "base64", "overwriteifexists": "0" }. * * @param string $filename Name of file to create ('FA1705-0123.txt') * @param string $modulepart Name of module or area concerned by file upload ('facture', 'project', 'project_task', ...) @@ -430,11 +501,10 @@ class Documents extends DolibarrApi * @param int $overwriteifexists Overwrite file if exists (1 by default) * @return string * - * @throws 200 - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * * @url POST /upload */ @@ -476,6 +546,13 @@ class Documents extends DolibarrApi require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($this->db); } + elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') + { + $modulepart = 'supplier_invoice'; + + require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; + $object = new FactureFournisseur($this->db); + } elseif ($modulepart == 'project') { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; @@ -510,6 +587,11 @@ class Documents extends DolibarrApi require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $object = new Product($this->db); } + elseif ($modulepart == 'expensereport') + { + require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; + $object = new ExpenseReport($this->db); + } // TODO Implement additional moduleparts else { @@ -535,6 +617,12 @@ class Documents extends DolibarrApi throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); } + // Special cases that need to use get_exdir to get real dir of object + // If future, all object should use this to define path of documents. + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); @@ -610,10 +698,9 @@ class Documents extends DolibarrApi * @param string $original_file Relative path with filename, relative to modulepart (for example: PRODUCT-REF-999/IMAGE-999.jpg) * @return array List of documents * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 200 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 * * @url DELETE / */ @@ -631,7 +718,18 @@ class Documents extends DolibarrApi //--- Finds and returns the document $entity = $conf->entity; - $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, DolibarrApiAccess::$user, '', 'read'); + // Special cases that need to use get_exdir to get real dir of object + // If future, all object should use this to define path of documents. + /* + $tmpreldir = ''; + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } + + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ + $relativefile = $original_file; + + $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read'); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $original_file = $check_access['original_file']; diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 59a527d251c..748d1f2ac31 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -48,9 +48,8 @@ class Login * @param int $reset Reset token (0=get current token, 1=ask a new token and canceled old token. This means access using current existing API token of user will fails: new token will be required for new access) * @return array Response status and user token * - * @throws 200 - * @throws 403 - * @throws 500 + * @throws RestException 403 + * @throws RestException 500 * * @url GET / * @url POST / diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 66c4c1358cb..2afca6aedb5 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -59,8 +59,7 @@ class Setup extends DolibarrApi * * @return array [List of ordering methods] * - * @throws 400 RestException - * @throws 200 OK + * @throws RestException 400 */ public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') { @@ -121,8 +120,7 @@ class Setup extends DolibarrApi * * @return array [List of payment types] * - * @throws 400 RestException - * @throws 200 OK + * @throws RestException 400 */ public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') { @@ -339,8 +337,7 @@ class Setup extends DolibarrApi * * @return array [List of availability] * - * @throws 400 RestException - * @throws 200 OK + * @throws RestException 400 */ public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') { @@ -557,6 +554,70 @@ class Setup extends DolibarrApi return $list; } + + /** + * Get the list of Expense Report types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of expense report types + * + * @url GET dictionary/expensereport_types + * + * @throws RestException + */ + public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, label, accountancy_code, active, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + + $sql .= $this->db->order($sortfield, $sortorder); + + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); + } + + return $list; + } + + /** * Get the list of contacts types. * @@ -908,8 +969,7 @@ class Setup extends DolibarrApi * * @return array List of payment terms * - * @throws 400 RestException - * @throws 200 OK + * @throws RestException 400 */ public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') { @@ -969,8 +1029,7 @@ class Setup extends DolibarrApi * * @return array List of shipping methods * - * @throws 400 RestException - * @throws 200 OK + * @throws RestException 400 */ public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') { @@ -1342,6 +1401,39 @@ class Setup extends DolibarrApi return $this->_cleanObjectDatas($mysoc); } + + /** + * Get value of a setup variables + * + * Note that conf variables that stores security key or password hashes can't be loaded with API. + * + * @url GET /conf + * + * @param string $confname Name of conf variable to get + * @return array|mixed Data without useless information + * + * @throws RestException 403 Forbidden + * @throws RestException 500 Error Bad or unknown value for constname + */ + public function getConf($confname) + { + global $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGIN_ALLOWED_FOR_ADMIN_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_ADMIN_CHECK)) { + throw new RestException(403, 'Error API open to admin users only or to the login user defined with constant API_LOGIN_ALLOWED_FOR_ADMIN_CHECK'); + } + + if (! preg_match('/[^a-zA-Z0-9_]/', $confname) || ! isset($conf->global->$confname)) { + throw new RestException(500, 'Error Bad or unknown value for constname'); + } + if (preg_match('/(_pass|password|secret|_key|key$)/i', $confname)) { + throw new RestException(403, 'Forbidden'); + } + + return $conf->global->$confname; + } + /** * Do a test of integrity for files and setup. * @@ -1350,7 +1442,9 @@ class Setup extends DolibarrApi * * @url GET checkintegrity * - * @throws RestException + * @throws RestException 404 Signature file not found + * @throws RestException 500 Technical error + * @throws RestException 503 Forbidden */ public function getCheckIntegrity($target) { @@ -1359,7 +1453,7 @@ class Setup extends DolibarrApi if (!DolibarrApiAccess::$user->admin && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) { - throw new RestException(503, 'Error API open to admin users only or to login user defined with constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); + throw new RestException(503, 'Error API open to admin users only or to the login user defined with constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; diff --git a/htdocs/asset/document.php b/htdocs/asset/document.php index c6488f9e0be..c6762c5c946 100644 --- a/htdocs/asset/document.php +++ b/htdocs/asset/document.php @@ -47,7 +47,7 @@ $ref = GETPOST('ref', 'alpha'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/asset/list.php b/htdocs/asset/list.php index 2a9657baf90..e414193fb83 100644 --- a/htdocs/asset/list.php +++ b/htdocs/asset/list.php @@ -49,7 +49,7 @@ $id = GETPOST('id', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/asset/type.php b/htdocs/asset/type.php index 9f5f8597663..8df5ffe8c40 100644 --- a/htdocs/asset/type.php +++ b/htdocs/asset/type.php @@ -43,7 +43,7 @@ $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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -609,37 +609,15 @@ if ($rowid > 0) print $object->showOptionals($extrafields, 'edit', $parameters); } - print ''; + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; - // Extra field - if (empty($reshook)) - { - print '

    '; - foreach ($extrafields->attributes[$object->element]['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 "


    '; - } + print ''; dol_fiche_end(); - print '
    '; - print ''; - print '     '; - print ''; + print '
    '; + print '   '; print '
    '; print ""; diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php index 828d2ecff50..5cd988a5bed 100644 --- a/htdocs/barcode/printsheet.php +++ b/htdocs/barcode/printsheet.php @@ -278,6 +278,7 @@ dol_htmloutput_errors($mesg); print '
    '; print ''; print ''; +print ''; print '
    '; diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index 065dd4cda9e..1ef35942d1e 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -28,9 +28,9 @@ 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")); +$langs->loadLangs(array("admin", "other", "blockedlog")); -if (! $user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); +if (!$user->admin || empty($conf->blockedlog->enabled)) accessforbidden(); $action = GETPOST('action', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); @@ -40,11 +40,12 @@ $backtopage = GETPOST('backtopage', 'alpha'); * Actions */ +$reg = array(); if (preg_match('/set_(.*)/', $action, $reg)) { - $code=$reg[1]; + $code = $reg[1]; $values = GETPOST($code); - if(is_array($values))$values = implode(',', $values); + if (is_array($values)) $values = implode(',', $values); if (dolibarr_set_const($db, $code, $values, 'chaine', 0, '', $conf->entity) > 0) { @@ -59,7 +60,7 @@ if (preg_match('/set_(.*)/', $action, $reg)) if (preg_match('/del_(.*)/', $action, $reg)) { - $code=$reg[1]; + $code = $reg[1]; if (dolibarr_del_const($db, $code, 0) > 0) { Header("Location: ".$_SERVER["PHP_SELF"]); @@ -76,22 +77,22 @@ if (preg_match('/del_(.*)/', $action, $reg)) * View */ -$form=new Form($db); +$form = new Form($db); $block_static = new BlockedLog($db); llxHeader('', $langs->trans("BlockedLogSetup")); -$linkback=''; +$linkback = ''; if (GETPOST('withtab', 'alpha')) { - $linkback=''.$langs->trans("BackToModuleList").''; + $linkback = ''.$langs->trans("BackToModuleList").''; } print load_fiche_titre($langs->trans("ModuleSetup").' '.$langs->trans('BlockedLog'), $linkback); if (GETPOST('withtab', 'alpha')) { - $head=blockedlogadmin_prepare_head(); + $head = blockedlogadmin_prepare_head(); dol_fiche_head($head, 'blockedlog', '', -1); } @@ -134,16 +135,16 @@ print ''; print ''; $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; -$sql.= " FROM ".MAIN_DB_PREFIX."c_country"; -$sql.= " WHERE active > 0"; +$sql .= " FROM ".MAIN_DB_PREFIX."c_country"; +$sql .= " WHERE active > 0"; -$countryArray=array(); -$resql=$db->query($sql); +$countryArray = array(); +$resql = $db->query($sql); if ($resql) { while ($obj = $db->fetch_object($resql)) { - $countryArray[$obj->code_iso] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); + $countryArray[$obj->code_iso] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : '')); } } @@ -159,8 +160,8 @@ print ''; print ''; print ''; print $langs->trans("ListOfTrackedEvents").''; -$arrayoftrackedevents=$block_static->trackedevents; -foreach($arrayoftrackedevents as $key => $val) +$arrayoftrackedevents = $block_static->trackedevents; +foreach ($arrayoftrackedevents as $key => $val) { print $key.' - '.$langs->trans($val).'
    '; } diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index becbbc3f151..3bd7f0097b9 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -58,7 +58,7 @@ if (($search_start == -1 || empty($search_start)) && ! GETPOSTISSET('search_star $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/bom/bom_agenda.php b/htdocs/bom/bom_agenda.php index 37197d641dc..a5b66b9886f 100644 --- a/htdocs/bom/bom_agenda.php +++ b/htdocs/bom/bom_agenda.php @@ -60,7 +60,7 @@ $search_agenda_label = GETPOST('search_agenda_label'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 3f1be6c7e4c..81b5f858c9b 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -520,7 +520,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ''."\n"; // Common attributes - $keyforbreak = 'efficiency'; + $keyforbreak = 'duration'; include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php'; // Other attributes diff --git a/htdocs/bom/bom_document.php b/htdocs/bom/bom_document.php index 6ac836fdcae..0fc68ed276e 100644 --- a/htdocs/bom/bom_document.php +++ b/htdocs/bom/bom_document.php @@ -48,7 +48,7 @@ $ref = GETPOST('ref', 'alpha'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 12602f9744a..e33394edcf7 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -47,7 +47,7 @@ $id = GETPOST('id', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index ddfb5e78d17..b53e2a7bc88 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -95,7 +95,7 @@ class BOM extends CommonObject 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,), 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1:(finished IS NULL or finished <> 0)', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'help'=>'ProductBOMHelp'), 'qty' => array('type'=>'real', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'default'=>1, 'position'=>55, 'notnull'=>1, 'isameasure'=>'1', 'css'=>'maxwidth75imp'), - 'efficiency' => array('type'=>'real', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>-1, 'default'=>1, 'position'=>100, 'notnull'=>0, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLoss'), + //'efficiency' => array('type'=>'real', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>-1, 'default'=>1, 'position'=>100, 'notnull'=>0, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLossForProductProduced'), 'duration' => array('type'=>'duration', 'label'=>'EstimatedDuration', 'enabled'=>1, 'visible'=>-1, 'position'=>101, 'notnull'=>-1, 'css'=>'maxwidth50imp', 'help'=>'EstimatedDurationDesc'), 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'enabled'=>1, 'visible'=>-1, 'position'=>102), 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>-2, 'position'=>161, 'notnull'=>-1,), @@ -561,7 +561,7 @@ class BOM extends CommonObject { $num = $this->ref; } - $this->newref = $num; + $this->newref = dol_sanitizeFileName($num); // Validate $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; @@ -1056,7 +1056,7 @@ class BOMLine extends CommonObjectLine 'qty' => array('type'=>'double(24,8)', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'notnull'=>1, 'isameasure'=>'1',), 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'), 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'), - //'efficiency' => array('type'=>'double(24,8)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'), + 'efficiency' => array('type'=>'double(24,8)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'), 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,), 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,), ); diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 7f3072d8051..445466a27a1 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -98,18 +98,18 @@ if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) { // hide products in closed warehouse, but show products for internal transfer - $form->select_produits(GETPOST('idprod'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); + $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); } else { - $form->select_produits(GETPOST('idprod'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, '', GETPOST('combinations', 'array')); + $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, '', GETPOST('combinations', 'array')); } echo ''; } $coldisplay++; -print ''; if ($conf->global->PRODUCT_USE_UNITS) @@ -128,11 +128,10 @@ $coldisplay++; print ''; -//$coldisplay++; -//print ''; - +$coldisplay++; +print ''; $coldisplay += $colspan; print ''; print ''; if (is_object($objectline)) { - print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); + print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', 1); } ?> diff --git a/htdocs/bom/tpl/objectline_edit.tpl.php b/htdocs/bom/tpl/objectline_edit.tpl.php index 17d01e07fd9..04c84f9c1b0 100644 --- a/htdocs/bom/tpl/objectline_edit.tpl.php +++ b/htdocs/bom/tpl/objectline_edit.tpl.php @@ -124,9 +124,9 @@ $coldisplay++; print ''; -//$coldisplay++; -//print ''; +$coldisplay++; +print ''; $coldisplay+=$colspan; print ''; print ''; if (is_object($objectline)) { - print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); + print $objectline->showOptionals($extrafields, 'edit', array('style'=>$bcnd[$var], 'colspan'=>$coldisplay), '', '', 1); } print "\n"; diff --git a/htdocs/bom/tpl/objectline_title.tpl.php b/htdocs/bom/tpl/objectline_title.tpl.php index 706f71af7ec..138a0b9aa58 100644 --- a/htdocs/bom/tpl/objectline_title.tpl.php +++ b/htdocs/bom/tpl/objectline_title.tpl.php @@ -66,7 +66,7 @@ print ''; // Efficiency -//print ''; +print ''; print ''; // No width to allow autodim diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index 16d7d427c75..16aa5382f53 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -98,10 +98,10 @@ $coldisplay++; echo $line->disable_stock_change ? yn($line->disable_stock_change) : ''; // Yes, it is a quantity, not a price, but we just want the formating role of function price print ''; -//print ''; +print ''; if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines' ) { print ''; //Line extrafield if (!empty($extrafields)) { - print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); + print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1); } print "\n"; diff --git a/htdocs/bookmarks/bookmarks.lib.php b/htdocs/bookmarks/bookmarks.lib.php index 8d772bf5b33..9e69eda2cd3 100644 --- a/htdocs/bookmarks/bookmarks.lib.php +++ b/htdocs/bookmarks/bookmarks.lib.php @@ -21,132 +21,6 @@ * \brief File with library for bookmark module */ -/** - * Add area with bookmarks in menu - * - * @return string - */ -function printBookmarksList() -{ - global $conf, $user, $db, $langs; - - $ret = ''."\n"; - - if (! empty($conf->use_javascript_ajax)) { // Bookmark autosubmit can't work when javascript is off. - require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; - if (! isset($conf->global->BOOKMARKS_SHOW_IN_MENU)) $conf->global->BOOKMARKS_SHOW_IN_MENU=5; - - $langs->load("bookmarks"); - - $url= $_SERVER["PHP_SELF"]; - - if (! empty($_SERVER["QUERY_STRING"])) - { - $url.=(dol_escape_htmltag($_SERVER["QUERY_STRING"])?'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]):''); - } - else - { - global $sortfield,$sortorder; - $tmpurl=''; - // No urlencode, all param $url will be urlencoded later - if ($sortfield) $tmpurl.=($tmpurl?'&':'').'sortfield='.$sortfield; - if ($sortorder) $tmpurl.=($tmpurl?'&':'').'sortorder='.$sortorder; - if (is_array($_POST)) - { - foreach($_POST as $key => $val) - { - if (preg_match('/^search_/', $key) && $val != '') $tmpurl.=($tmpurl?'&':'').$key.'='.$val; - } - } - $url.=($tmpurl?'?'.$tmpurl:''); - } - - // Menu bookmark - $ret = ''."\n"; - - $ret.= ''."\n"; - $ret.= ''; - $ret.= ''; - $ret.= ''; - $ret.= ''; - - $ret.=ajax_combobox('boxbookmark'); - - $ret.=''; - } - - $ret.= ''."\n"; - - return $ret; -} - - /** * Add area with bookmarks in top menu @@ -158,97 +32,91 @@ function printDropdownBookmarksList() global $conf, $user, $db, $langs; require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; - if (! isset($conf->global->BOOKMARKS_SHOW_IN_MENU)) $conf->global->BOOKMARKS_SHOW_IN_MENU=5; + require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; $langs->load("bookmarks"); - $url= $_SERVER["PHP_SELF"]; + $url = $_SERVER["PHP_SELF"]; - if (! empty($_SERVER["QUERY_STRING"])) + if (!empty($_SERVER["QUERY_STRING"])) { - $url.=(dol_escape_htmltag($_SERVER["QUERY_STRING"])?'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]):''); + $url .= (dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]) : ''); } else { - global $sortfield,$sortorder; - $tmpurl=''; + global $sortfield, $sortorder; + $tmpurl = ''; // No urlencode, all param $url will be urlencoded later - if ($sortfield) $tmpurl.=($tmpurl?'&':'').'sortfield='.$sortfield; - if ($sortorder) $tmpurl.=($tmpurl?'&':'').'sortorder='.$sortorder; + if ($sortfield) $tmpurl .= ($tmpurl ? '&' : '').'sortfield='.$sortfield; + if ($sortorder) $tmpurl .= ($tmpurl ? '&' : '').'sortorder='.$sortorder; if (is_array($_POST)) { - foreach($_POST as $key => $val) + foreach ($_POST as $key => $val) { - if (preg_match('/^search_/', $key) && $val != '') $tmpurl.=($tmpurl?'&':'').$key.'='.$val; + if (preg_match('/^search_/', $key) && $val != '') $tmpurl .= ($tmpurl ? '&' : '').$key.'='.$val; } } - $url.=($tmpurl?'?'.$tmpurl:''); + $url .= ($tmpurl ? '?'.$tmpurl : ''); } $searchForm = ''."\n"; - $searchForm.= ''; - $searchForm.= ''; - $searchForm.= ''; + $searchForm .= ''; + $searchForm .= ''; + $searchForm .= ''; + $searchForm .= ''; // Url to list bookmark $listbtn = ''; - $listbtn.= ' '.$langs->trans('Bookmarks').''; + $listbtn .= ''.$langs->trans('Bookmarks').''; // Url to go on create new bookmark page $newbtn = ''; - if (! empty($user->rights->bookmark->creer)) + if (!empty($user->rights->bookmark->creer)) { //$urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&urlsource='.urlencode($url).'&url='.urlencode($url); - $urltoadd=DOL_URL_ROOT.'/bookmarks/card.php?action=create&url='.urlencode($url); - $newbtn.= ''; - $newbtn.= img_picto('', 'bookmark').' '.dol_escape_htmltag($langs->trans('AddThisPageToBookmarks')).''; + $urltoadd = DOL_URL_ROOT.'/bookmarks/card.php?action=create&url='.urlencode($url); + $newbtn .= ''; + $newbtn .= img_picto('', 'bookmark', '', false, 0, 0, '', 'paddingright').dol_escape_htmltag($langs->trans('AddThisPageToBookmarks')).''; } - - $bookmarkList=''; - $html= ''; - if (! empty($conf->global->BOOKMARKS_SHOW_IN_MENU)) { - $html.= ' + $html = ' '; - } - $html.= ' + $html .= ' '; - $html.= ' + $html .= ' '; - if (! empty($conf->global->BOOKMARKS_SHOW_IN_MENU)) { - $html .= ''; - } return $html; } diff --git a/htdocs/bookmarks/list.php b/htdocs/bookmarks/list.php index 4e9d6851399..067e2abeaa9 100644 --- a/htdocs/bookmarks/list.php +++ b/htdocs/bookmarks/list.php @@ -44,7 +44,7 @@ $optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index f3b76cbaed6..f1e19b4df20 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -21,14 +21,14 @@ */ // Protection to avoid direct call of template -if (empty($langs) || ! is_object($langs)) +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } // Load translation files required by the page -$langs->loadLangs(array("main","bills","cashdesk")); +$langs->loadLangs(array("main", "bills", "cashdesk")); // Object $form must de defined @@ -64,7 +64,7 @@ $id = $obj_facturation->id(); // Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ... $nbtoshow = $nbr_enreg; -if (! empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; +if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; for ($i = 0; $i < $nbtoshow; $i++) { @@ -77,8 +77,8 @@ for ($i = 0; $i < $nbtoshow; $i++) $label = $tab_designations[$i]['label']; print ''."\n"; } @@ -101,23 +101,23 @@ for ($i = 0; $i < $nbtoshow; $i++) @@ -152,7 +152,7 @@ for ($i = 0; $i < $nbtoshow; $i++) diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index b7b37054d91..7783bf7137a 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -305,6 +305,7 @@ switch ($action) $payment->note=$langs->trans("Payment").' '.$langs->trans("Invoice").' '.$obj_facturation->numInvoice(); $payment->paiementid=$invoice->mode_reglement_id; $payment->num_paiement=''; + $payment->num_payment=''; $paiement_id = $payment->create($user); if ($paiement_id > 0) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 39f94db02eb..e8296b96beb 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -167,8 +167,9 @@ class Categorie extends CommonObject 'member' => 'adherent', 'contact' => 'socpeople', 'user' => 'user', - 'account' => 'bank_account', - 'project' => 'projet', + 'account' => 'bank_account', // old for bank account + 'bank_account' => 'bank_account', + 'project' => 'projet', 'warehouse'=> 'entrepot', 'actioncomm' => 'actioncomm', ); @@ -774,7 +775,7 @@ class Categorie extends CommonObject /** * Return list of fetched instance of elements having this category * - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') + * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member', ...) * @param int $onlyids Return only ids of objects (consume less memory) * @param int $limit Limit * @param int $offset Offset @@ -1911,8 +1912,8 @@ class Categorie extends CommonObject /** * Return label of contact status * - * @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 contact 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 contact status */ public function getLibStatut($mode) { @@ -1957,4 +1958,59 @@ class Categorie extends CommonObject return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables, 1); } + + /** + * Return the addtional SQL JOIN query for filtering a list by a category + * + * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE) + * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid") + * @return string A additional SQL JOIN query + */ + public static function getFilterJoinQuery($type, $rowIdName) + { + if ($type == 'bank_account') $type = 'account'; + + return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type; + } + + /** + * Return the addtional SQL SELECT query for filtering a list by a category + * + * @param string $type The category type (e.g Categorie::TYPE_WAREHOUSE) + * @param string $rowIdName The name of the row id inside the whole sql query (e.g. "e.rowid") + * @param Array $searchList A list with the selected categories + * @return string A additional SQL SELECT query + */ + public static function getFilterSelectQuery($type, $rowIdName, $searchList) + { + if ($type == 'bank_account') $type = 'account'; + + if (empty($searchList) && !is_array($searchList)) + { + return ""; + } + + foreach ($searchList as $searchCategory) + { + if (intval($searchCategory) == -2) + { + $searchCategorySqlList[] = " cp.fk_categorie IS NULL"; + } + elseif (intval($searchCategory) > 0) + { + $searchCategorySqlList[] = " ".$rowIdName + ." IN (SELECT fk_".$type." FROM ".MAIN_DB_PREFIX."categorie_".$type + ." WHERE fk_categorie = ".$searchCategory.")"; + } + } + + if (!empty($searchCategorySqlList)) + { + return " AND (".implode(' AND ', $searchCategorySqlList).")"; + } + else + { + return ""; + } + } } diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index c71be0cd919..d96fddca150 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -182,23 +182,13 @@ foreach ($fulltree as $key => $val) $li = $categstatic->getNomUrl(1, '', 60); $desc = dol_htmlcleanlastbr($val['description']); + $counter = ''; + if($conf->global->CATEGORY_SHOW_COUNTS) { // we need only a count of the elements, so it is enough to consume only the id's from the database - if ($type == Categorie::TYPE_PRODUCT) $elements = $categstatic->getObjectsInCateg("product", 1); - if ($type == Categorie::TYPE_SUPPLIER) $elements = $categstatic->getObjectsInCateg("supplier", 1); - if ($type == Categorie::TYPE_CUSTOMER) $elements = $categstatic->getObjectsInCateg("customer", 1); - if ($type == Categorie::TYPE_MEMBER) $elements = $categstatic->getObjectsInCateg("member", 1); - if ($type == Categorie::TYPE_CONTACT) $elements = $categstatic->getObjectsInCateg("contact", 1); - if ($type == Categorie::TYPE_ACCOUNT) $elements = $categstatic->getObjectsInCateg("account", 1); - if ($type == Categorie::TYPE_PROJECT) $elements = $categstatic->getObjectsInCateg("project", 1); - if ($type == Categorie::TYPE_USER) $elements = $categstatic->getObjectsInCateg("user", 1); - - $counter = ""; - } - else - { - $counter = ""; + $elements = $categstatic->getObjectsInCateg($type, 1); + $counter = ""; } $data[] = array( diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 5d81ccd7d63..62538da0273 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -55,7 +55,7 @@ $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always ' $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index c17f9cc9c1b..07cd885698e 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -840,7 +840,7 @@ if ($action == 'create') print ''; print ''; print ''; - if ($backtopage) print ''; + if ($backtopage) print ''; if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) print ''; if (GETPOST("actioncode", 'aZ09') == 'AC_RDV') print load_fiche_titre($langs->trans("AddActionRendezVous"), '', 'title_agenda'); @@ -1070,7 +1070,7 @@ if ($action == 'create') $numproject = $formproject->select_projects((!empty($societe->id) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1); print ' '; - $urloption = '?action=create'; + $urloption = '?action=create&donotclearsession=1'; $url = dol_buildpath('comm/action/card.php', 2).$urloption; // update task list @@ -1249,7 +1249,7 @@ if ($id > 0) print ''; print ''; print ''; - if ($backtopage) print ''; + if ($backtopage) print ''; if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) print ''; dol_fiche_head($head, 'card', $langs->trans("Action"), 0, 'action'); @@ -1479,10 +1479,10 @@ if ($id > 0) $langs->load("projects"); print ''; } @@ -1503,7 +1503,7 @@ if ($id > 0) { print ''; // Other attributes diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index f01f49921e7..31f608a9ee0 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -64,7 +64,7 @@ if ($id > 0) // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 31808d35991..b480586bc6a 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -58,7 +58,7 @@ if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", "int"); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 3ac82178810..e388bb25fb0 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -43,7 +43,7 @@ $action = GETPOST('action', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'actioncommlist'; // To manage different context of search $resourceid = GETPOST("search_resourceid", "int") ?GETPOST("search_resourceid", "int") : GETPOST("resourceid", "int"); $pid = GETPOST("search_projectid", 'int', 3) ?GETPOST("search_projectid", 'int', 3) : GETPOST("projectid", 'int', 3); -$status = (GETPOST("search_status", 'alpha') != '') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha'); +$search_status = (GETPOST("search_status", 'alpha') != '') ?GETPOST("search_status", 'alpha') : GETPOST("status", 'alpha'); $type = GETPOST('search_type', 'alphanohtml') ?GETPOST('search_type', 'alphanohtml') : GETPOST('type', 'alphanohtml'); $optioncss = GETPOST('optioncss', 'alpha'); $year = GETPOST("year", 'int'); @@ -67,8 +67,8 @@ $search_note = GETPOST('search_note', 'alpha'); $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); $datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int')); $dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int')); -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 ($search_status == '' && !GETPOSTISSET('search_status')) $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); $filter = GETPOST("search_filter", 'alpha', 3) ?GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filtert = GETPOST("search_filtert", "int", 3) ?GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); @@ -94,18 +94,18 @@ if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if ($page == -1 || $page == null) { $page = 0; } $offset = $limit * $page; if (!$sortorder) { $sortorder = "DESC,DESC"; - if ($status == 'todo') $sortorder = "DESC,DESC"; + if ($search_status == 'todo') $sortorder = "DESC,DESC"; } if (!$sortfield) { $sortfield = "a.datep,a.id"; - if ($status == 'todo') $sortfield = "a.datep,a.id"; + if ($search_status == 'todo') $sortfield = "a.datep,a.id"; } // Security check @@ -184,7 +184,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_note = ''; $datestart = ''; $dateend = ''; - $status = ''; + $search_status = ''; $search_array_options = array(); } @@ -218,7 +218,7 @@ if ($actioncode != '') { } else $param .= "&search_actioncode=".urlencode($actioncode); } if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); -if ($status != '' && $status > -1) $param .= "&search_status=".urlencode($status); +if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status); if ($filter) $param .= "&search_filter=".urlencode($filter); if ($filtert) $param .= "&search_filtert=".urlencode($filtert); if ($socid) $param .= "&search_socid=".urlencode($socid); @@ -309,12 +309,12 @@ if ($socid > 0) $sql .= " AND s.rowid = ".$socid; // We must filter on assignement table if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; if ($type) $sql .= " AND c.id = ".(int) $type; -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') { $sql .= " AND (a.percent = 100)"; } -if ($status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } +if ($search_status == '0') { $sql .= " AND a.percent = 0"; } +if ($search_status == '-1') { $sql .= " AND a.percent = -1"; } // Not applicable +if ($search_status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started +if ($search_status == '100') { $sql .= " AND a.percent = 100"; } +if ($search_status == 'done') { $sql .= " AND (a.percent = 100)"; } +if ($search_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); if ($search_note) $sql .= natural_search('a.note', $search_note); @@ -397,7 +397,7 @@ if ($resql) print $nav; dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); - print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); + print_actions_filter($form, $canedit, $search_status, $year, $month, $day, $showbirthday, 0, $filtert, 0, $pid, $socid, $action, -1, $actioncode, $usergroup, '', $resourceid); dol_fiche_end(); // Add link to show birthdays @@ -488,8 +488,8 @@ if ($resql) if (!empty($arrayfields['a.tms']['checked'])) print ''; if (!empty($arrayfields['a.percent']['checked'])) { print ''; } // Action column diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index 04f334a9551..b1d0ddc7ccc 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -56,7 +56,7 @@ if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", "int"); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php index f906c4cab45..e8f7be097fa 100644 --- a/htdocs/comm/action/peruser.php +++ b/htdocs/comm/action/peruser.php @@ -56,7 +56,7 @@ $showbirthday = 0; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", "int"); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index 92744da332c..b9ab38a734e 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -41,7 +41,7 @@ $year=GETPOST('year'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if ($page == -1 || $page == null) { $page = 0 ; } $offset = $limit * $page ; if (! $sortorder) $sortorder="DESC"; diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index b5164d6078c..f1ea3c0923d 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -67,7 +67,7 @@ $mode = GETPOST("mode"); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; @@ -666,7 +666,7 @@ if ($object->id > 0) $now = dol_now(); /* - * Last proposals + * Latest proposals */ if (!empty($conf->propal->enabled) && $user->rights->propal->lire) { @@ -738,7 +738,7 @@ if ($object->id > 0) } /* - * Last orders + * Latest orders */ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { @@ -751,7 +751,7 @@ if ($object->id > 0) $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= " AND s.rowid = ".$object->id; - $sql .= " AND c.entity = ".$conf->entity; + $sql .= " AND c.entity IN (".getEntity('commande').')'; $sql .= " ORDER BY c.date_commande DESC"; $resql = $db->query($sql); @@ -824,7 +824,7 @@ if ($object->id > 0) } /* - * Last shipments + * Latest shipments */ if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire) { @@ -897,7 +897,7 @@ if ($object->id > 0) } /* - * Last linked contracts + * Latest linked contracts */ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { @@ -905,7 +905,7 @@ if ($object->id > 0) $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; - $sql .= " AND c.entity = ".$conf->entity; + $sql .= " AND c.entity IN (".getEntity('contract').")"; $sql .= " ORDER BY c.datec DESC"; $resql = $db->query($sql); @@ -967,7 +967,7 @@ if ($object->id > 0) } /* - * Last interventions + * Latest interventions */ if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) { @@ -975,7 +975,7 @@ if ($object->id > 0) $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as f"; $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND s.rowid = ".$object->id; - $sql .= " AND f.entity = ".$conf->entity; + $sql .= " AND f.entity IN (".getEntity('intervention').")"; $sql .= " ORDER BY f.tms DESC"; $resql = $db->query($sql); @@ -1028,7 +1028,7 @@ if ($object->id > 0) } /* - * Last invoices templates + * Latest invoices templates */ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { @@ -1044,7 +1044,7 @@ if ($object->id > 0) $sql .= ', s.nom, s.rowid as socid'; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; $sql .= " WHERE f.fk_soc = s.rowid AND s.rowid = ".$object->id; - $sql .= " AND f.entity = ".$conf->entity; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= ' GROUP BY f.rowid, f.titre, f.total, f.tva, f.total_ttc,'; $sql .= ' f.date_last_gen, f.datec, f.frequency, f.unit_frequency,'; $sql .= ' f.suspended, f.date_when,'; @@ -1063,7 +1063,7 @@ if ($object->id > 0) print '
    '; +print ''; print ''; print ''; -//print ''; -//print ''; +print ''; +print ''; @@ -141,7 +140,7 @@ print '
    disable_stock_change?' checked="checked"':'')).'">'; print ''; -//print ''; +print ''; @@ -138,7 +138,7 @@ print '
    '.$form->textwithpicto($langs->trans('QtyFro print ''.$form->textwithpicto($langs->trans('DisableStockChange'), $langs->trans('DisableStockChangeHelp')).''.$form->textwithpicto($langs->trans('ManufacturingEfficiency'), $langs->trans('XXX')).''.$form->textwithpicto($langs->trans('ManufacturingEfficiency'), $langs->trans('ValueOfMeansLoss')).''; -//$coldisplay++; -//echo $line->efficiency; -//print ''; +$coldisplay++; +echo $line->efficiency; +print ''; @@ -156,7 +156,7 @@ print '
    - + - + vatrate; // To get vat rate we just have selected + $vatrate = $obj_facturation->vatrate; // To get vat rate we just have selected $buyer = new Societe($db); if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); - echo $form->load_tva('selTva', (isset($_POST["selTva"])?GETPOST("selTva", 'alpha', 2):$vatrate), $mysoc, $buyer, 0, 0, '', false, -1); + echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1); ?> - + ".count($elements)."".(is_countable($elements) ? count($elements) : '0')."
    '.$langs->trans("Project").''; - $numprojet = $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0); + $numprojet = $formproject->select_projects(($object->socid > 0 ? $object->socid : -1), $object->fk_project, 'projectid', 0, 0, 1, 0, 0, 0, 0, '', 0, 0, 'maxwidth500'); if ($numprojet == 0) { - print '   '.$langs->trans("AddProject").''; + print '   '; } print '
    '; - $urloption = '?action=create'; // we use create not edit for more flexibility + $urloption = '?action=create&donotclearsession=1'; // we use create not edit for more flexibility $url = DOL_URL_ROOT.'/comm/action/card.php'.$urloption; // update task list @@ -1825,7 +1825,7 @@ if ($id > 0) // Description print '
    '.$langs->trans("Description").''; - print dol_htmlentitiesbr($object->note); + print dol_string_onlythesehtmltags(dol_htmlentitiesbr($object->note_private)); print '
    '; - $formactions->form_select_status_action('formaction', $status, 1, 'status', 1, 2, 'minwidth100imp maxwidth125'); - print ajax_combobox('selectstatus'); + $formactions->form_select_status_action('formaction', $search_status, 1, 'search_status', 1, 2, 'minwidth100imp maxwidth125'); + print ajax_combobox('selectsearch_status'); print '
    '; print ''; - print ''; + print '
    '.$link.'
    '; - print ''; + print ''; - print ''; + print ''; // For year $prevyear = $year - 1; $nextyear = $year + 1; $link = "".img_previous('', 'class="valignbottom"')." ".$langs->trans("Year")." ".img_next('', 'class="valignbottom"').""; - print ''; - print ''; + print ''; - print ''; + print ''; } if ($mode == 'showalltime') { - print ''; + print ''; } -print '
    '; + print ''; print ''; } diff --git a/htdocs/comm/contact.php b/htdocs/comm/contact.php index 8b3f4cf4894..3121bc3f1b9 100644 --- a/htdocs/comm/contact.php +++ b/htdocs/comm/contact.php @@ -31,7 +31,7 @@ $langs->load("companies"); $sortfield=GETPOST('sortfield', 'alpha'); $sortorder=GETPOST('sortorder', 'alpha'); -$page=GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="p.name"; if ($page < 0) { $page = 0; } diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index f20197df4dd..0bb38aeaa38 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2019 Nicolas ZABOURI + * Copyright (C) 2020 Pierre Ardoin * * 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 @@ -149,6 +150,9 @@ if (!empty($conf->propal->enabled) && $user->rights->propal->lire) $sql = "SELECT p.rowid, p.ref, p.ref_client, p.total_ht, p.tva as total_tva, p.total as total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; $sql .= ", s.code_client"; + $sql .= ", s.email"; + $sql .= ", s.entity"; + $sql .= ", s.code_compta"; $sql .= " FROM ".MAIN_DB_PREFIX."propal as p"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -193,6 +197,9 @@ if (!empty($conf->propal->enabled) && $user->rights->propal->lire) $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->entity = $obj->entity; + $companystatic->email = $obj->email; + $companystatic->code_compta = $obj->code_compta; print $companystatic->getNomUrl(1, 'customer', 16); print ''; print ''; @@ -233,6 +240,9 @@ if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposa $sql = "SELECT p.rowid, p.ref, p.total_ht, p.tva as total_tva, p.total as total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; $sql .= ", s.code_client"; + $sql .= ", s.code_fournisseur"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as p"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -276,6 +286,8 @@ if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposa $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->entity = $obj->entity; + $companystatic->email = $obj->email; print $companystatic->getNomUrl(1, 'supplier', 16); print ''; print ''; @@ -315,6 +327,9 @@ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) $sql = "SELECT c.rowid, c.ref, c.ref_client, c.total_ht, c.tva as total_tva, c.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; $sql .= ", s.code_client"; + $sql .= ", s.email"; + $sql .= ", s.entity"; + $sql .= ", s.code_compta"; $sql .= " FROM ".MAIN_DB_PREFIX."commande as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -358,6 +373,8 @@ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->email = $obj->email; + $companystatic->entity = $obj->entity; print $companystatic->getNomUrl(1, 'customer', 16); print ''; if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { @@ -404,6 +421,8 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande- $sql = "SELECT cf.rowid, cf.ref, cf.ref_supplier, cf.total_ttc, s.rowid as socid, s.nom as name, s.client, s.canvas"; $sql .= ", s.code_client"; $sql .= ", s.code_fournisseur"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -447,6 +466,8 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->commande- $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->entity = $obj->entity; + $companystatic->email = $obj->email; print $companystatic->getNomUrl(1, 'supplier', 16); print ''; if (!empty($conf->global->MAIN_DASHBOARD_USE_TOTAL_HT)) { @@ -496,6 +517,9 @@ if (!empty($conf->societe->enabled) && $user->rights->societe->lire) $sql = "SELECT s.rowid, s.nom as name, s.client, s.datec, s.tms, s.canvas"; $sql .= ", s.code_client"; + $sql .= ", s.code_compta"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE s.client IN (1, 2, 3)"; @@ -532,6 +556,9 @@ if (!empty($conf->societe->enabled) && $user->rights->societe->lire) $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; $companystatic->canvas = $objp->canvas; + $companystatic->code_compta = $objp->code_compta; + $companystatic->entity = $objp->entity; + $companystatic->email = $objp->email; print ''; print ''; print ''; print ''; print ''; @@ -628,7 +659,7 @@ if ($user->rights->agenda->myactions->read) /* - * Last contracts + * Latest contracts */ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TODO A REFAIRE DEPUIS NOUVEAU CONTRAT { @@ -636,7 +667,9 @@ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TOD $sql = "SELECT s.nom as name, s.rowid, s.canvas, "; $sql .= ", s.code_client"; - $sql .= " c.statut, c.rowid as contratid, p.ref, c.fin_validite as datefin, c.date_cloture as dateclo"; + $sql .= ", s.entity"; + $sql .= ", s.email"; + $sql .= ", c.statut, c.rowid as contratid, p.ref, c.fin_validite as datefin, c.date_cloture as dateclo"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."product as p"; @@ -673,6 +706,8 @@ if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TOD $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; $companystatic->canvas = $objp->canvas; + $companystatic->entity = $objp->entity; + $companystatic->email = $objp->email; print $companystatic->getNomUrl(1, 'customer', 44); print ''."\n"; print "\n"; @@ -697,6 +732,8 @@ if (!empty($conf->propal->enabled) && $user->rights->propal->lire) $langs->load("propal"); $sql = "SELECT s.nom as name, s.rowid, s.code_client"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $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"; @@ -760,6 +797,8 @@ if (!empty($conf->propal->enabled) && $user->rights->propal->lire) $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->entity = $obj->entity; + $companystatic->email = $obj->email; print $companystatic->getNomUrl(1, 'customer', 44); print ''; print ''; print ''; - print ''; } else diff --git a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php index f5acafcfb19..b9782515735 100644 --- a/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php +++ b/htdocs/comm/mailing/class/html.formadvtargetemailing.class.php @@ -65,7 +65,7 @@ class FormAdvTargetEmailing extends Form $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectlevel"; $sql .= " WHERE active > 0"; $sql .= " ORDER BY sortorder"; - dol_syslog(get_class($this).'::multiselectProspectionStatus sql='.$sql, LOG_DEBUG); + $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -111,7 +111,6 @@ class FormAdvTargetEmailing extends Form $sql .= " WHERE active = 1 AND code<>''"; $sql .= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_country sql=".$sql); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -260,7 +259,6 @@ class FormAdvTargetEmailing extends Form } // $sql.= ' WHERE entity = '.$conf->entity; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); @@ -297,7 +295,7 @@ class FormAdvTargetEmailing extends Form $sql = "SELECT rowid, code, label as civilite, active FROM ".MAIN_DB_PREFIX."c_civility"; $sql .= " WHERE active = 1"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -385,7 +383,7 @@ class FormAdvTargetEmailing extends Form $sql = "SELECT rowid, label FROM ".MAIN_DB_PREFIX."categorie"; $sql .= " WHERE type=".$type; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -432,10 +430,10 @@ class FormAdvTargetEmailing extends Form $sql .= " WHERE type_element='$type_element'"; $sql .= " ORDER BY c.name"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - $out .= ''; if ($showempty) $out .= ''; $num = $this->db->num_rows($resql); diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php index 32637096910..553c5e79c15 100644 --- a/htdocs/comm/mailing/class/mailing.class.php +++ b/htdocs/comm/mailing/class/mailing.class.php @@ -662,10 +662,12 @@ class Mailing extends CommonObject $labelStatusShort = array(); $labelStatus[-1] = $langs->trans('MailingStatusError'); + $labelStatus[0] = $langs->trans('MailingStatusNotSent'); $labelStatus[1] = $langs->trans('MailingStatusSent'); $labelStatus[2] = $langs->trans('MailingStatusRead'); $labelStatus[3] = $langs->trans('MailingStatusNotContact'); $labelStatusShort[-1] = $langs->trans('MailingStatusError'); + $labelStatusShort[0] = $langs->trans('MailingStatusNotSent'); $labelStatusShort[1] = $langs->trans('MailingStatusSent'); $labelStatusShort[2] = $langs->trans('MailingStatusRead'); $labelStatusShort[3] = $langs->trans('MailingStatusNotContact'); diff --git a/htdocs/comm/mailing/list.php b/htdocs/comm/mailing/list.php index 7e2baa7274b..1eadb2d0da0 100644 --- a/htdocs/comm/mailing/list.php +++ b/htdocs/comm/mailing/list.php @@ -34,7 +34,7 @@ $result = restrictedArea($user, 'mailing'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/comm/propal/card.php b/htdocs/comm/propal/card.php index f55861b00cc..9430fce4634 100644 --- a/htdocs/comm/propal/card.php +++ b/htdocs/comm/propal/card.php @@ -1893,7 +1893,7 @@ 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->LibStatut(Propal::STATUS_SIGNED), 3=>$object->LibStatut(Propal::STATUS_NOTSIGNED))), + 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) ); diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 1337c62da94..87c91d0f621 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -1,6 +1,7 @@ * Copyright (C) 2016 Laurent Destailleur + * Copyright (C) 2020 Thibault FOUCART * * 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 @@ -64,16 +65,70 @@ class Proposals extends DolibarrApi */ public function get($id, $contact_list = 1) { - if(! DolibarrApiAccess::$user->rights->propal->lire) { + return $this->_fetch($id, '', '', $contact_list); + } + + /** + * Get properties of an proposal object by ref + * + * Return an array with proposal informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } + + /** + * Get properties of an proposal object by ref_ext + * + * Return an array with proposal informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } + + /** + * Get properties of an proposal object + * + * Return an array with proposal informations + * + * @param int $id ID of order + * @param string $ref Ref of object + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { + if (!DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - $result = $this->propal->fetch($id); - if( ! $result ) { + $result = $this->propal->fetch($id, $ref, $ref_ext); + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -107,18 +162,18 @@ class Proposals extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; $sql = "SELECT t.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql.= " FROM ".MAIN_DB_PREFIX."propal as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."propal as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale - $sql.= ' WHERE t.entity IN ('.getEntity('propal').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + $sql .= ' WHERE t.entity IN ('.getEntity('propal').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale // Insert sale filter if ($search_sale > 0) { @@ -127,23 +182,23 @@ class Proposals extends DolibarrApi // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { if ($page < 0) { $page = 0; } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); @@ -158,7 +213,7 @@ class Proposals extends DolibarrApi { $obj = $db->fetch_object($result); $proposal_static = new Propal($db); - if($proposal_static->fetch($obj->rowid)) { + 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); @@ -169,7 +224,7 @@ class Proposals extends DolibarrApi else { throw new RestException(503, 'Error when retrieve propal list : '.$db->lasterror()); } - if( ! count($obj_ret)) { + if (!count($obj_ret)) { throw new RestException(404, 'No proposal found'); } return $obj_ret; @@ -183,13 +238,13 @@ class Proposals extends DolibarrApi */ public function post($request_data = null) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401, "Insuffisant rights"); } // Check mandatory fields $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $this->propal->$field = $value; } /*if (isset($request_data["lines"])) { @@ -217,16 +272,16 @@ class Proposals extends DolibarrApi */ public function getLines($id) { - if(! DolibarrApiAccess::$user->rights->propal->lire) { + if (!DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->propal->getLinesArray(); @@ -249,16 +304,16 @@ class Proposals extends DolibarrApi */ public function postLine($id, $request_data = null) { - if (! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if (! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -313,16 +368,16 @@ class Proposals extends DolibarrApi */ public function putLine($id, $lineid, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if($result <= 0) { + if ($result <= 0) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -336,27 +391,27 @@ class Proposals extends DolibarrApi $updateRes = $this->propal->updateline( $lineid, - isset($request_data->subprice)?$request_data->subprice:$propalline->subprice, - isset($request_data->qty)?$request_data->qty:$propalline->qty, - isset($request_data->remise_percent)?$request_data->remise_percent:$propalline->remise_percent, - isset($request_data->tva_tx)?$request_data->tva_tx:$propalline->tva_tx, - isset($request_data->localtax1_tx)?$request_data->localtax1_tx:$propalline->localtax1_tx, - isset($request_data->localtax2_tx)?$request_data->localtax2_tx:$propalline->localtax2_tx, - isset($request_data->desc)?$request_data->desc:$propalline->desc, + isset($request_data->subprice) ? $request_data->subprice : $propalline->subprice, + isset($request_data->qty) ? $request_data->qty : $propalline->qty, + isset($request_data->remise_percent) ? $request_data->remise_percent : $propalline->remise_percent, + isset($request_data->tva_tx) ? $request_data->tva_tx : $propalline->tva_tx, + isset($request_data->localtax1_tx) ? $request_data->localtax1_tx : $propalline->localtax1_tx, + isset($request_data->localtax2_tx) ? $request_data->localtax2_tx : $propalline->localtax2_tx, + isset($request_data->desc) ? $request_data->desc : $propalline->desc, 'HT', - isset($request_data->info_bits)?$request_data->info_bits:$propalline->info_bits, - isset($request_data->special_code)?$request_data->special_code:$propalline->special_code, - isset($request_data->fk_parent_line)?$request_data->fk_parent_line:$propalline->fk_parent_line, + isset($request_data->info_bits) ? $request_data->info_bits : $propalline->info_bits, + isset($request_data->special_code) ? $request_data->special_code : $propalline->special_code, + isset($request_data->fk_parent_line) ? $request_data->fk_parent_line : $propalline->fk_parent_line, 0, - isset($request_data->fk_fournprice)?$request_data->fk_fournprice:$propalline->fk_fournprice, - isset($request_data->pa_ht)?$request_data->pa_ht:$propalline->pa_ht, - isset($request_data->label)?$request_data->label:$propalline->label, - isset($request_data->product_type)?$request_data->product_type:$propalline->product_type, - isset($request_data->date_start)?$request_data->date_start:$propalline->date_start, - isset($request_data->date_end)?$request_data->date_end:$propalline->date_end, - isset($request_data->array_options)?$request_data->array_options:$propalline->array_options, - isset($request_data->fk_unit)?$request_data->fk_unit:$propalline->fk_unit, - isset($request_data->multicurrency_subprice)?$request_data->multicurrency_subprice:$propalline->subprice + isset($request_data->fk_fournprice) ? $request_data->fk_fournprice : $propalline->fk_fournprice, + isset($request_data->pa_ht) ? $request_data->pa_ht : $propalline->pa_ht, + isset($request_data->label) ? $request_data->label : $propalline->label, + isset($request_data->product_type) ? $request_data->product_type : $propalline->product_type, + isset($request_data->date_start) ? $request_data->date_start : $propalline->date_start, + isset($request_data->date_end) ? $request_data->date_end : $propalline->date_end, + isset($request_data->array_options) ? $request_data->array_options : $propalline->array_options, + isset($request_data->fk_unit) ? $request_data->fk_unit : $propalline->fk_unit, + isset($request_data->multicurrency_subprice) ? $request_data->multicurrency_subprice : $propalline->subprice ); if ($updateRes > 0) { @@ -377,21 +432,22 @@ class Proposals extends DolibarrApi * @url DELETE {id}/lines/{lineid} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function deleteLine($id, $lineid) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -417,18 +473,19 @@ class Proposals extends DolibarrApi * @url POST {id}/contact/{contactid}/{type} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function postContact($id, $contactid, $type) { - if(!DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if(!$result) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } @@ -436,7 +493,7 @@ class Proposals extends DolibarrApi throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); } - if(!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -458,23 +515,24 @@ class Proposals extends DolibarrApi * @url DELETE {id}/contact/{rowid} * * @return int - * @throws 401 - * @throws 404 - * @throws 500 + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function deleteContact($id, $rowid) { - if(!DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if(!$result) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if(!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -497,16 +555,16 @@ class Proposals extends DolibarrApi */ public function put($id, $request_data = null) { - if (! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if ( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if ( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { @@ -521,7 +579,7 @@ class Proposals extends DolibarrApi } if (!empty($this->propal->fin_validite)) { - if($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite)<0) + if ($this->propal->set_echeance(DolibarrApiAccess::$user, $this->propal->fin_validite) < 0) { throw new RestException(500, $this->propal->error); } @@ -546,19 +604,19 @@ class Proposals extends DolibarrApi */ public function delete($id) { - if(! DolibarrApiAccess::$user->rights->propal->supprimer) { + if (!DolibarrApiAccess::$user->rights->propal->supprimer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! $this->propal->delete(DolibarrApiAccess::$user)) { + if (!$this->propal->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when delete Commercial Proposal : '.$this->propal->error); } @@ -581,15 +639,15 @@ class Proposals extends DolibarrApi */ public function settodraft($id) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -602,11 +660,11 @@ class Proposals extends DolibarrApi } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -629,24 +687,24 @@ class Proposals extends DolibarrApi * * @url POST {id}/validate * - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * * @return array */ public function validate($id, $notrigger = 0) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -659,11 +717,11 @@ class Proposals extends DolibarrApi } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -686,15 +744,15 @@ class Proposals extends DolibarrApi */ public function close($id, $status, $note_private = '', $notrigger = 0) { - if(! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -707,11 +765,11 @@ class Proposals extends DolibarrApi } $result = $this->propal->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -731,15 +789,15 @@ class Proposals extends DolibarrApi */ public function setinvoiced($id) { - if (! DolibarrApiAccess::$user->rights->propal->creer) { + if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } $result = $this->propal->fetch($id); - if ( ! $result ) { + if (!$result) { throw new RestException(404, 'Commercial Proposal not found'); } - if ( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -749,11 +807,11 @@ class Proposals extends DolibarrApi } $result = $this->propal->fetch($id); - if ( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } - if( ! DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index c6d1af1287e..ff3038e85d1 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -223,6 +223,90 @@ class Propal extends CommonObject public $oldcopy; + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15, 'index'=>1), + 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>20), + 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>22), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>40), + 'ref_int' =>array('type'=>'varchar(255)', 'label'=>'RefInt', 'enabled'=>1, 'visible'=>0, 'position'=>45), // deprecated + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>23), + 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk projet', 'enabled'=>1, 'visible'=>-1, 'position'=>24), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), + 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'datep' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'fin_validite' =>array('type'=>'datetime', 'label'=>'DateEnd', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>70), + 'date_cloture' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>80), + 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>85), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user cloture', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + 'price' =>array('type'=>'double', 'label'=>'Price', 'enabled'=>1, 'visible'=>-1, 'position'=>105), + 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115), + //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), + 'tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), + 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), + 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), + 'total' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1), + 'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>150), + 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>155), + 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>160), + 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>165), + 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>170), + 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>175), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'PDFTemplate', 'enabled'=>1, 'visible'=>0, 'position'=>180), + 'date_livraison' =>array('type'=>'date', 'label'=>'DateDeliveryPlanned', 'enabled'=>1, 'visible'=>-1, 'position'=>185), + 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'ShippingMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'fk_availability' =>array('type'=>'integer', 'label'=>'Availability', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>0, 'position'=>200), // deprecated + 'fk_input_reason' =>array('type'=>'integer', 'label'=>'InputReason', 'enabled'=>1, 'visible'=>-1, 'position'=>205), + 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>220), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>225), + 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>1, 'visible'=>-1, 'position'=>230), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>235), + 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>240, 'isameasure'=>1), + 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>245, 'isameasure'=>1), + 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>250, 'isameasure'=>1), + 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>255, 'isameasure'=>1), + 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>260), + 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), + ); + // END MODULEBUILDER PROPERTIES + /** * Draft status */ @@ -440,8 +524,8 @@ class Propal extends CommonObject * @param int $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object + * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'.... + * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id * @param double $pu_ht_devise Unit price in currency * @param int $fk_remise_except Id discount if line is from a discount * @return int >0 if OK, <0 if KO @@ -1099,6 +1183,14 @@ class Propal extends CommonObject $vatrate = $line->tva_tx; if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if(!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { + $originid=$line->origin_id; + $origintype=$line->origin; + } else { + $originid=$line->id; + $origintype=$this->element; + } + $result = $this->addline( $line->desc, $line->subprice, @@ -1122,8 +1214,8 @@ class Propal extends CommonObject $line->date_end, $line->array_options, $line->fk_unit, - $this->element, - $line->id + $origintype, + $originid ); if ($result < 0) @@ -1369,9 +1461,10 @@ class Propal extends CommonObject * * @param int $rowid id of object to load * @param string $ref Ref of proposal + * @param string $ref_ext Ref ext of proposal * @return int >0 if OK, <0 if KO */ - public function fetch($rowid, $ref = '') + public function fetch($rowid, $ref = '', $ref_ext = '') { $sql = "SELECT p.rowid, p.ref, p.entity, p.remise, p.remise_percent, p.remise_absolue, p.fk_soc"; $sql .= ", p.total, p.tva, p.localtax1, p.localtax2, p.total_ht"; @@ -1438,10 +1531,10 @@ class Propal extends CommonObject $this->total_ttc = $obj->total; $this->socid = $obj->fk_soc; - $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty + $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty $this->fk_project = $obj->fk_project; - $this->project = null; // Clear if another value was already set by fetch_projet + $this->project = null; // Clear if another value was already set by fetch_projet $this->modelpdf = $obj->model_pdf; $this->last_main_doc = $obj->last_main_doc; @@ -1803,7 +1896,7 @@ class Propal extends CommonObject { $num = $this->ref; } - $this->newref = $num; + $this->newref = dol_sanitizeFileName($num); $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql .= " SET ref = '".$this->db->escape($num)."',"; @@ -3249,8 +3342,8 @@ class Propal extends CommonObject $statusType = ''; if ($status == self::STATUS_DRAFT) $statusType = 'status0'; elseif ($status == self::STATUS_VALIDATED) $statusType = 'status1'; - elseif ($status == self::STATUS_SIGNED) $statusType = 'status3'; - elseif ($status == self::STATUS_NOTSIGNED) $statusType = 'status5'; + elseif ($status == self::STATUS_SIGNED) $statusType = 'status4'; + elseif ($status == self::STATUS_NOTSIGNED) $statusType = 'status9'; elseif ($status == self::STATUS_BILLED) $statusType = 'status6'; return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); diff --git a/htdocs/comm/propal/class/propalestats.class.php b/htdocs/comm/propal/class/propalestats.class.php index 0859bdb7974..d5c48006430 100644 --- a/htdocs/comm/propal/class/propalestats.class.php +++ b/htdocs/comm/propal/class/propalestats.class.php @@ -24,10 +24,10 @@ * \brief File of class to manage proposals statistics */ -include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; -include_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; -include_once DOL_DOCUMENT_ROOT . '/supplier_proposal/class/supplier_proposal.class.php'; -include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php'; +include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; /** @@ -66,36 +66,36 @@ class PropaleStats extends Stats if ($mode == 'customer') { - $object=new Propal($this->db); + $object = new Propal($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as p"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field_date='p.datep'; - $this->field='total_ht'; - $this->field_line='total_ht'; + $this->field_date = 'p.datep'; + $this->field = 'total_ht'; + $this->field_line = 'total_ht'; - $this->where.= " p.fk_statut > 0"; + $this->where .= " p.fk_statut > 0"; } if ($mode == 'supplier') { - $object=new SupplierProposal($this->db); + $object = new SupplierProposal($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as p"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field_date='p.date_valid'; - $this->field='total_ht'; - $this->field_line='total_ht'; + $this->field_date = 'p.date_valid'; + $this->field = 'total_ht'; + $this->field_line = 'total_ht'; - $this->where.= " p.fk_statut > 0"; // Validated, accepted, refused and closed + $this->where .= " p.fk_statut > 0"; // Validated, accepted, refused and closed } //$this->where.= " AND p.fk_soc = s.rowid AND p.entity = ".$conf->entity; - $this->where.= " AND p.entity IN (".getEntity('propal').")"; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; - if($this->socid) + $this->where .= " AND p.entity IN (".getEntity('propal').")"; + if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($this->socid) { - $this->where.=" AND p.fk_soc = ".$this->socid; + $this->where .= " AND p.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where.=' AND fk_user_author = '.$this->userid; + if ($this->userid > 0) $this->where .= ' AND fk_user_author = '.$this->userid; } @@ -111,14 +111,14 @@ class PropaleStats extends Stats global $user; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, COUNT(*) as nb"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getNbByMonth($year, $sql, $format); + $res = $this->_getNbByMonth($year, $sql, $format); return $res; } @@ -133,11 +133,11 @@ class PropaleStats extends Stats global $user; $sql = "SELECT date_format(".$this->field_date.",'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getNbByYear($sql); } @@ -154,14 +154,14 @@ class PropaleStats extends Stats global $user; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, SUM(p.".$this->field.")"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getAmountByMonth($year, $sql, $format); + $res = $this->_getAmountByMonth($year, $sql, $format); return $res; } @@ -176,12 +176,12 @@ class PropaleStats extends Stats global $user; $sql = "SELECT date_format(".$this->field_date.",'%m') as dm, AVG(p.".$this->field.")"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getAverageByMonth($year, $sql); } @@ -196,11 +196,11 @@ class PropaleStats extends Stats global $user; $sql = "SELECT date_format(".$this->field_date.",'%Y') as year, COUNT(*) as nb, SUM(".$this->field.") as total, AVG(".$this->field.") as avg"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY year"; - $sql.= $this->db->order('year', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY year"; + $sql .= $this->db->order('year', 'DESC'); return $this->_getAllByYear($sql); } @@ -210,23 +210,24 @@ class PropaleStats extends Stats /** * Return nb, amount of predefined product for year * - * @param int $year Year to scan - * @return array Array of values + * @param int $year Year to scan + * @param int $limit Limit + * @return array Array of values */ - public function getAllByProduct($year) + public function getAllByProduct($year, $limit = 10) { global $user; $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; - $sql.= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " AND p.rowid = tl.fk_propal AND tl.fk_product = product.rowid"; - $sql.= " AND ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; - $sql.= " GROUP BY product.ref"; - $sql.= $this->db->order('nb', 'DESC'); + $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " AND p.rowid = tl.fk_propal AND tl.fk_product = product.rowid"; + $sql .= " AND ".$this->field_date." BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " GROUP BY product.ref"; + $sql .= $this->db->order('nb', 'DESC'); //$sql.= $this->db->plimit(20); - return $this->_getAllByProduct($sql); + return $this->_getAllByProduct($sql, $limit); } } diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index c052c234eab..e396a5f8b92 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -21,7 +21,7 @@ /** * \file htdocs/comm/propal/contact.php * \ingroup propal - * \brief Onglet de gestion des contacts de propal + * \brief Tab to manage contacts/adresses of proposal */ require '../../main.inc.php'; diff --git a/htdocs/comm/propal/document.php b/htdocs/comm/propal/document.php index 9279da9b029..4ce7d10c9fd 100644 --- a/htdocs/comm/propal/document.php +++ b/htdocs/comm/propal/document.php @@ -55,7 +55,7 @@ $result = restrictedArea($user, 'propal', $id); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php index 11bb4292036..66f4aa94fd2 100644 --- a/htdocs/comm/propal/index.php +++ b/htdocs/comm/propal/index.php @@ -82,7 +82,7 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles * Statistics */ -$sql = "SELECT count(p.rowid), p.fk_statut"; +$sql = "SELECT count(p.rowid) as nb, p.fk_statut as status"; $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"; @@ -101,24 +101,26 @@ if ($resql) $total = 0; $totalinprocess = 0; $dataseries = array(); + $colorseries = array(); $vals = array(); + // -1=Canceled, 0=Draft, 1=Validated, (2=Accepted/On process not managed for customer orders), 3=Closed (Sent/Received, billed or not) while ($i < $num) { - $row = $db->fetch_row($resql); - if ($row) + $obj = $db->fetch_object($resql); + if ($obj) { - //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) - { - $vals[$row[1]] = $row[0]; - $totalinprocess += $row[0]; - } - $total += $row[0]; + $vals[$obj->status] = $obj->nb; + $totalinprocess += $obj->nb; + + $total += $obj->nb; } $i++; } $db->free($resql); + include_once DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/theme_vars.inc.php'; + print '
    '; print '
    '.$langs->trans("LatestCustomerTemplateInvoices", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllCustomerTemplateInvoices").''.$num.''; print '
    '.$langs->trans("LatestCustomerTemplateInvoices", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllCustomerTemplateInvoices").''.$num.'
    '.price($obj->total_ht).'
    '.price($obj->total_ht).'
    '.$companystatic->getNomUrl(1, 'customer', 48).''; @@ -560,6 +587,8 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->societe->lire) $sql = "SELECT s.nom as name, s.rowid, s.datec as dc, s.canvas, s.tms as dm"; $sql .= ", s.code_fournisseur"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE s.fournisseur = 1"; @@ -591,6 +620,8 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->societe->lire) $companystatic->code_client = $objp->code_client; $companystatic->code_fournisseur = $objp->code_fournisseur; $companystatic->canvas = $objp->canvas; + $companystatic->entity = $objp->entity; + $companystatic->email = $objp->email; print '
    '.$companystatic->getNomUrl(1, 'supplier', 44).''.dol_print_date($db->jdate($objp->dm), 'day').'".$staticcontrat->LibStatut($obj->statut, 3)."
    '; @@ -802,6 +841,8 @@ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) $sql = "SELECT s.nom as name, s.rowid, c.rowid as commandeid, c.total_ttc, c.total_ht, c.tva as total_tva, c.ref, c.ref_client, c.fk_statut, c.date_valid as dv, c.facture as billed"; $sql .= ", s.code_client"; + $sql .= ", s.entity"; + $sql .= ", s.email"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande as c"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -864,6 +905,8 @@ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->entity = $obj->entity; + $companystatic->email = $obj->email; print $companystatic->getNomUrl(1, 'customer', 44); print ''; diff --git a/htdocs/comm/mailing/advtargetemailing.php b/htdocs/comm/mailing/advtargetemailing.php index b85826339e5..b716790aa8f 100644 --- a/htdocs/comm/mailing/advtargetemailing.php +++ b/htdocs/comm/mailing/advtargetemailing.php @@ -48,7 +48,7 @@ if (!$user->rights->mailing->lire || $user->socid > 0) $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 3dcfdf9e451..d8d9873b88b 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -43,13 +43,13 @@ if (!$user->rights->mailing->lire || $user->socid > 0) accessforbidden(); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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 (!$sortfield) $sortfield = "email"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) $sortfield = "mc.statut,email"; +if (!$sortorder) $sortorder = "DESC,ASC"; $id = GETPOST('id', 'int'); $rowid = GETPOST('rowid', 'int'); @@ -673,7 +673,8 @@ if ($object->fetch($id) >= 0) // Date sent print ' '.$langs->trans("MailingStatusNotSent"); + print ''; + print $object::libStatutDest($obj->statut, 2, ''); print '
    '; print ''."\n"; @@ -126,7 +128,13 @@ if ($resql) foreach ($listofstatus as $status) { $dataseries[] = array($propalstatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if (!$conf->use_javascript_ajax) + if ($status == Propal::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; + if ($status == Propal::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; + if ($status == Propal::STATUS_SIGNED) $colorseries[$status] = $badgeStatus4; + if ($status == Propal::STATUS_NOTSIGNED) $colorseries[$status] = $badgeStatus9; + if ($status == Propal::STATUS_BILLED) $colorseries[$status] = $badgeStatus6; + + if (empty($conf->use_javascript_ajax)) { print ''; print ''; @@ -141,10 +149,11 @@ if ($resql) include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->SetDataColor(array_values($colorseries)); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphthirdparties'); print $dolgraph->show($total ? 0 : 1); diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index b9fefe3d78b..f41bdc4fc67 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -69,6 +69,11 @@ $search_societe = GETPOST('search_societe', 'alpha'); $search_montant_ht = GETPOST('search_montant_ht', 'alpha'); $search_montant_vat = GETPOST('search_montant_vat', 'alpha'); $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha'); +$search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha'); +$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha'); +$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha'); +$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha'); +$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $search_login = GETPOST('search_login', 'alpha'); $search_product_category = GETPOST('search_product_category', 'int'); $search_town = GETPOST('search_town', 'alpha'); @@ -98,7 +103,7 @@ $mesg = (GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; $pageprev = $page - 1; @@ -162,8 +167,15 @@ $arrayfields = array( 'p.total_ht'=>array('label'=>"AmountHT", 'checked'=>1), 'p.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0), 'p.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0), - 'p.total_ht_invoiced'=>array('label'=>$langs->trans("AmountInvoicedHT"), 'checked'=>0, 'enabled'=>$conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT), - 'p.total_invoiced'=>array('label'=>$langs->trans("AmountInvoicedTTC"), 'checked'=>0, 'enabled'=>$conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT), + 'p.total_ht_invoiced'=>array('label'=>"AmountInvoicedHT", 'checked'=>0, 'enabled'=>!empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), + 'p.total_invoiced'=>array('label'=>"AmountInvoicedTTC", 'checked'=>0, 'enabled'=>!empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), + 'p.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'p.multicurrency_total_ht_invoiced'=>array('label'=>'MulticurrencyAmountInvoicedHT', 'checked'=>0, 'enabled'=>!empty($conf->multicurrency->enabled) && !empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), + 'p.multicurrency_total_invoiced'=>array('label'=>'MulticurrencyAmountInvoicedTTC', 'checked'=>0, 'enabled'=>!empty($conf->multicurrency->enabled) && !empty($conf->global->PROPOSAL_SHOW_INVOICED_AMOUNT)), 'u.login'=>array('label'=>"Author", 'checked'=>1, 'position'=>10), 'sale_representative'=>array('label'=>"SaleRepresentativesOfThirdParty", 'checked'=>1), 'p.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), @@ -209,6 +221,11 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_montant_ht = ''; $search_montant_vat = ''; $search_montant_ttc = ''; + $search_multicurrency_code = ''; + $search_multicurrency_tx = ''; + $search_multicurrency_montant_ht = ''; + $search_multicurrency_montant_vat = ''; + $search_multicurrency_montant_ttc = ''; $search_login = ''; $search_product_category = ''; $search_town = ''; @@ -269,6 +286,7 @@ $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.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.fk_multicurrency, p.multicurrency_code, p.multicurrency_tx, p.multicurrency_total_ht, p.multicurrency_total_tva as multicurrency_total_vat, p.multicurrency_total_ttc,'; $sql .= ' p.datec as date_creation, p.tms as date_update, p.date_cloture as date_cloture,'; $sql .= ' p.note_public, p.note_private,'; $sql .= " pr.rowid as project_id, pr.ref as project_ref, pr.title as project_label,"; @@ -326,6 +344,11 @@ if ($search_login) $sql .= natural_search("u.login", $search_login); if ($search_montant_ht != '') $sql .= natural_search("p.total_ht", $search_montant_ht, 1); if ($search_montant_vat != '') $sql .= natural_search("p.tva", $search_montant_vat, 1); if ($search_montant_ttc != '') $sql .= natural_search("p.total", $search_montant_ttc, 1); +if ($search_multicurrency_code != '') $sql .= ' AND p.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +if ($search_multicurrency_tx != '') $sql .= natural_search('p.multicurrency_tx', $search_multicurrency_tx, 1); +if ($search_multicurrency_montant_ht != '') $sql .= natural_search('p.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +if ($search_multicurrency_montant_vat != '') $sql .= natural_search('p.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('p.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } @@ -428,6 +451,11 @@ if ($resql) if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); if ($search_montant_ht) $param .= '&search_montant_ht='.urlencode($search_montant_ht); + if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); if ($search_login) $param .= '&search_login='.urlencode($search_login); if ($search_town) $param .= '&search_town='.urlencode($search_town); if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); @@ -677,6 +705,53 @@ if ($resql) print ''; } + if (!empty($arrayfields['p.multicurrency_code']['checked'])) + { + // Currency + print ''; + } + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) + { + // Currency rate + print ''; + } + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) + { + // Amount invoiced + print ''; + } + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) + { + // Amount invoiced + print ''; + } if (!empty($arrayfields['u.login']['checked'])) { // Author @@ -750,6 +825,13 @@ if ($resql) if (!empty($arrayfields['p.total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.total_ttc']['label'], $_SERVER["PHP_SELF"], 'p.total', '', $param, 'class="right"', $sortfield, $sortorder); if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); if (!empty($arrayfields['p.total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_code', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'p.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_ht_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) print_liste_field_titre($arrayfields['p.multicurrency_total_invoiced']['label'], $_SERVER["PHP_SELF"], '', '', $param, 'class="right"', $sortfield, $sortorder); if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $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); // Extra fields @@ -776,8 +858,9 @@ if ($resql) $objectstatic->id = $obj->rowid; $objectstatic->ref = $obj->ref; - $objectstatic->note_private = $obj->note_private; + $objectstatic->ref_client = $obj->ref_client; $objectstatic->note_public = $obj->note_public; + $objectstatic->note_private = $obj->note_private; $companystatic->id = $obj->socid; $companystatic->name = $obj->name; @@ -789,6 +872,29 @@ if ($resql) $projectstatic->ref = $obj->project_ref; $projectstatic->title = $obj->project_label; + $totalInvoicedHT = 0; + $totalInvoicedTTC = 0; + $multicurrency_totalInvoicedHT = 0; + $multicurrency_totalInvoicedTTC = 0; + + $TInvoiceData = $objectstatic->InvoiceArrayList($obj->rowid); + + if (!empty($TInvoiceData)) + { + foreach ($TInvoiceData as $invoiceData) + { + $invoice = new Facture($db); + $invoice->fetch($invoiceData->facid); + + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $invoice->type == Facture::TYPE_DEPOSIT) continue; + + $totalInvoicedHT += $invoice->total_ht; + $totalInvoicedTTC += $invoice->total_ttc; + $multicurrency_totalInvoicedHT += $invoice->multicurrency_total_ht; + $multicurrency_totalInvoicedTTC += $invoice->multicurrency_total_ttc; + } + } + print ''; if (!empty($arrayfields['p.ref']['checked'])) @@ -824,7 +930,7 @@ if ($resql) if (!empty($arrayfields['p.ref_client']['checked'])) { // Customer ref - print ''; if (!$i) $totalarray['nbfield']++; @@ -974,46 +1080,66 @@ if ($resql) $totalarray['val']['p.total_ttc'] += $obj->total_ttc; } // Amount invoiced - if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) { - $totalInvoiced = 0; - $p = new Propal($db); - $TInvoiceData = $p->InvoiceArrayList($obj->rowid); - - if (!empty($TInvoiceData)) { - foreach ($TInvoiceData as $invoiceData) { - $invoice = new Facture($db); - $invoice->fetch($invoiceData->facid); - - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $invoice->type == Facture::TYPE_DEPOSIT) continue; - $totalInvoiced += $invoice->total_ht; - } - } - - print '\n"; + if (!empty($arrayfields['p.total_ht_invoiced']['checked'])) + { + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_ht_invoiced'; - $totalarray['val']['p.total_ht_invoiced'] += $obj->total_ht_invoiced; + $totalarray['val']['p.total_ht_invoiced'] += $totalInvoicedHT; } // Amount invoiced - if (!empty($arrayfields['p.total_invoiced']['checked'])) { - $totalInvoiced = 0; - $p = new Propal($db); - $TInvoiceData = $p->InvoiceArrayList($obj->rowid); - - if (!empty($TInvoiceData)) { - foreach ($TInvoiceData as $invoiceData) { - $invoice = new Facture($db); - $invoice->fetch($invoiceData->facid); - - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS) && $invoice->type == Facture::TYPE_DEPOSIT) continue; - $totalInvoiced += $invoice->total_ttc; - } - } - - print '\n"; + if (!empty($arrayfields['p.total_invoiced']['checked'])) + { + print '\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.total_invoiced'; - $totalarray['val']['p.total_invoiced'] += $obj->total_invoiced; + $totalarray['val']['p.total_invoiced'] += $totalInvoicedTTC; + } + + // Currency + if (!empty($arrayfields['p.multicurrency_code']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Currency rate + if (!empty($arrayfields['p.multicurrency_tx']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount HT + if (!empty($arrayfields['p.multicurrency_total_ht']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount VAT + if (!empty($arrayfields['p.multicurrency_total_vat']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount TTC + if (!empty($arrayfields['p.multicurrency_total_ttc']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount invoiced + if (!empty($arrayfields['p.multicurrency_total_ht_invoiced']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount invoiced + if (!empty($arrayfields['p.multicurrency_total_invoiced']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; } $userstatic->id = $obj->fk_user_author; @@ -1039,9 +1165,7 @@ if ($resql) $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 3) // We print only number { - print ''; print $nbofsalesrepresentative; - print ''; } elseif ($nbofsalesrepresentative > 0) { diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index 4a2b8dea419..030db477631 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -242,7 +242,9 @@ print '
    '; //{ // Show filter box print '
    '; + print ''; print ''; + print '
    '.$langs->trans("Statistics").' - '.$langs->trans("Proposals").'
    '.$propalstatic->LibStatut($status, 0).''; print ''; + print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print ''; print $obj->ref_client; print ''.price($totalInvoiced)."'.price($totalInvoicedHT)."'.price($totalInvoiced)."'.price($totalInvoicedTTC)."'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); + print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."'.price($multicurrency_totalInvoicedHT)."'.price($multicurrency_totalInvoicedTTC)."
    '; print ''; // Company diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 902b773735a..651fa556e8a 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -111,6 +111,7 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount1->description = $discount->description.' (1)'; $newdiscount2->description = $discount->description.' (2)'; } + $newdiscount1->fk_user = $discount->fk_user; $newdiscount2->fk_user = $discount->fk_user; $newdiscount1->fk_soc = $discount->fk_soc; @@ -121,7 +122,7 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') $newdiscount2->datec = $discount->datec; $newdiscount1->tva_tx = $discount->tva_tx; $newdiscount2->tva_tx = $discount->tva_tx; - $newdiscount1->amount_ttc = $_POST["amount_ttc_1"]; + $newdiscount1->amount_ttc = $amount_ttc_1; $newdiscount2->amount_ttc = price2num($discount->amount_ttc - $newdiscount1->amount_ttc); $newdiscount1->amount_ht = price2num($newdiscount1->amount_ttc / (1 + $newdiscount1->tva_tx / 100), 'MT'); $newdiscount2->amount_ht = price2num($newdiscount2->amount_ttc / (1 + $newdiscount2->tva_tx / 100), 'MT'); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 3c1bf672c0f..148fa427fff 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -93,24 +93,31 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('ordercard','globalcard')); +$hookmanager->initHooks(array('ordercard', 'globalcard')); $usercanread = $user->rights->commande->lire; $usercancreate = $user->rights->commande->creer; $usercanclose = $user->rights->commande->cloturer; $usercandelete = $user->rights->commande->supprimer; -$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->validate))); -$usercancancel = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->commande->order_advance->annuler))); +$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->validate))); +$usercancancel = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->commande->order_advance->annuler))); $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->commande->order_advance->send); $usercancreatepurchaseorder = $user->rights->fournisseur->commande->creer; -$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php -$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php -$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php +$permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php +$permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php +$permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php + +if (!empty($conf->expedition->enabled) && $conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER = 1){ + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $object->warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE; + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $object->warehouse_id = $user->fk_warehouse; +} + +$error = 0; /* @@ -1594,25 +1601,25 @@ if ($action == 'create' && $usercancreate) $note_public = $object->getDefaultCreateValueFor('note_public'); } - print ''; - print ''; + print ''; + print ''; print ''; - print '' . "\n"; - print ''; - print ''; - print ''; - if (!empty($currency_tx)) print ''; + print ''."\n"; + print ''; + print ''; + print ''; + if (!empty($currency_tx)) print ''; dol_fiche_head(''); print '
    '.$langs->trans("Filter").'
    '; // Reference - print ''; + print ''; // Reference client - print ''; else print ''; @@ -2556,7 +2563,7 @@ if ($action == 'create' && $usercancreate) } // Valid - if ($object->statut == Commande::STATUS_DRAFT && $object->total_ttc >= 0 && $numlines > 0 && $usercanvalidate) + if ($object->statut == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || !empty($conf->global->ORDER_ENABLE_NEGATIVE)) && $numlines > 0 && $usercanvalidate) { print ''.$langs->trans('Validate').''; } @@ -2631,7 +2638,7 @@ if ($action == 'create' && $usercancreate) // Create bill and Classify billed // Note: Even if module invoice is not enabled, we should be able to use button "Classified billed" - if ($object->statut > Commande::STATUS_DRAFT && !$object->billed) { + if ($object->statut > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) { if (!empty($conf->facture->enabled) && $user->rights->facture->creer && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) { print ''; } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 5069135dd88..289bbea2c7e 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -64,7 +64,7 @@ class Orders extends DolibarrApi */ public function get($id, $contact_list = 1) { - return $this->_fetch($id, '', '', '', $contact_list); + return $this->_fetch($id, '', '', $contact_list); } /** @@ -82,7 +82,7 @@ class Orders extends DolibarrApi */ public function getByRef($ref, $contact_list = 1) { - return $this->_fetch('', $ref, '', '', $contact_list); + return $this->_fetch('', $ref, '', $contact_list); } /** @@ -100,7 +100,7 @@ class Orders extends DolibarrApi */ public function getByRefExt($ref_ext, $contact_list = 1) { - return $this->_fetch('', '', $ref_ext, '', $contact_list); + return $this->_fetch('', '', $ref_ext, $contact_list); } /** @@ -111,24 +111,23 @@ class Orders extends DolibarrApi * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param string $ref_int Internal reference of other objec * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id * @return array|mixed data without useless information * * @throws RestException */ - private function _fetch($id, $ref = '', $ref_ext = '', $ref_int = '', $contact_list = 1) + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) { - if(! DolibarrApiAccess::$user->rights->commande->lire) { + if (!DolibarrApiAccess::$user->rights->commande->lire) { throw new RestException(401); } - $result = $this->commande->fetch($id, $ref, $ref_ext, $ref_int); - if( ! $result ) { + $result = $this->commande->fetch($id, $ref, $ref_ext); + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -151,7 +150,8 @@ class Orders extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @return array Array of order objects * - * @throws RestException + * @throws RestException 404 Not found + * @throws RestException 503 Error */ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { @@ -164,18 +164,18 @@ class Orders extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; $sql = "SELECT t.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql.= " FROM ".MAIN_DB_PREFIX."commande as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."commande as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale - $sql.= ' WHERE t.entity IN ('.getEntity('commande').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql.= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql.= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql.= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + $sql .= ' WHERE t.entity IN ('.getEntity('commande').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale // Insert sale filter if ($search_sale > 0) { @@ -184,23 +184,23 @@ class Orders extends DolibarrApi // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); - if ($limit) { + $sql .= $db->order($sortfield, $sortorder); + if ($limit) { if ($page < 0) { $page = 0; } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } dol_syslog("API Rest request"); @@ -210,12 +210,12 @@ class Orders extends DolibarrApi { $num = $db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - $i=0; + $i = 0; while ($i < $min) { $obj = $db->fetch_object($result); $commande_static = new Commande($db); - if($commande_static->fetch($obj->rowid)) { + 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); @@ -226,7 +226,7 @@ class Orders extends DolibarrApi else { throw new RestException(503, 'Error when retrieve commande list : '.$db->lasterror()); } - if( ! count($obj_ret)) { + if (!count($obj_ret)) { throw new RestException(404, 'No order found'); } return $obj_ret; @@ -240,13 +240,13 @@ class Orders extends DolibarrApi */ public function post($request_data = null) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401, "Insuffisant rights"); } // Check mandatory fields $result = $this->_validate($request_data); - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { $this->commande->$field = $value; } /*if (isset($request_data["lines"])) { @@ -275,16 +275,16 @@ class Orders extends DolibarrApi */ public function getLines($id) { - if(! DolibarrApiAccess::$user->rights->commande->lire) { + if (!DolibarrApiAccess::$user->rights->commande->lire) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->commande->getLinesArray(); @@ -307,16 +307,16 @@ class Orders extends DolibarrApi */ public function postLine($id, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $request_data = (object) $request_data; @@ -369,16 +369,16 @@ class Orders extends DolibarrApi */ public function putLine($id, $lineid, $request_data = null) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $request_data = (object) $request_data; @@ -425,21 +425,22 @@ class Orders extends DolibarrApi * @url DELETE {id}/lines/{lineid} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function deleteLine($id, $lineid) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -463,21 +464,22 @@ class Orders extends DolibarrApi * @url POST {id}/contact/{contactid}/{type} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function postContact($id, $contactid, $type) { - if (! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -499,22 +501,23 @@ class Orders extends DolibarrApi * @url DELETE {id}/contact/{rowid} * * @return int - * @throws 401 - * @throws 404 - * @throws 500 + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function deleteContact($id, $rowid) { - if (! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -537,19 +540,19 @@ class Orders extends DolibarrApi */ public function put($id, $request_data = null) { - if (! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if (! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - foreach($request_data as $field => $value) { + foreach ($request_data as $field => $value) { if ($field == 'id') continue; $this->commande->$field = $value; } @@ -578,19 +581,19 @@ class Orders extends DolibarrApi */ public function delete($id) { - if(! DolibarrApiAccess::$user->rights->commande->supprimer) { + if (!DolibarrApiAccess::$user->rights->commande->supprimer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! $this->commande->delete(DolibarrApiAccess::$user)) { + if (!$this->commande->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when deleting order : '.$this->commande->error); } @@ -617,24 +620,24 @@ class Orders extends DolibarrApi * * @url POST {id}/validate * - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * * @return array */ public function validate($id, $idwarehouse = 0, $notrigger = 0) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -646,11 +649,11 @@ class Orders extends DolibarrApi throw new RestException(500, 'Error when validating Order: '.$this->commande->error); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -670,30 +673,30 @@ class Orders extends DolibarrApi * * @return int * - * @throws 304 - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 304 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function reopen($id) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Order ID is mandatory'); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } $result = $this->commande->set_reopen(DolibarrApiAccess::$user); - if( $result < 0) { + if ($result < 0) { throw new RestException(405, $this->commande->error); - }elseif( $result == 0) { + }elseif ($result == 0) { throw new RestException(304); } @@ -709,36 +712,36 @@ class Orders extends DolibarrApi * * @return int * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function setinvoiced($id) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - if(empty($id)) { + if (empty($id)) { throw new RestException(400, 'Order ID is mandatory'); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } $result = $this->commande->classifyBilled(DolibarrApiAccess::$user); - if( $result < 0) { + if ($result < 0) { throw new RestException(400, $this->commande->error); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -759,15 +762,15 @@ class Orders extends DolibarrApi */ public function close($id, $notrigger = 0) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -780,11 +783,11 @@ class Orders extends DolibarrApi } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -805,15 +808,15 @@ class Orders extends DolibarrApi */ public function settodraft($id, $idwarehouse = -1) { - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -826,11 +829,11 @@ class Orders extends DolibarrApi } $result = $this->commande->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Order not found'); } - if( ! DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { + if (!DolibarrApi::_checkAccessToResource('commande', $this->commande->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -849,34 +852,34 @@ class Orders extends DolibarrApi * @url POST /createfromproposal/{proposalid} * * @return int - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function createOrderFromProposal($proposalid) { - require_once DOL_DOCUMENT_ROOT . '/comm/propal/class/propal.class.php'; + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - if(! DolibarrApiAccess::$user->rights->propal->lire) { + if (!DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } - if(! DolibarrApiAccess::$user->rights->commande->creer) { + if (!DolibarrApiAccess::$user->rights->commande->creer) { throw new RestException(401); } - if(empty($proposalid)) { + if (empty($proposalid)) { throw new RestException(400, 'Proposal ID is mandatory'); } $propal = new Propal($this->db); $result = $propal->fetch($proposalid); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Proposal not found'); } $result = $this->commande->createFromProposal($propal, DolibarrApiAccess::$user); - if( $result < 0) { + if ($result < 0) { throw new RestException(405, $this->commande->error); } $this->commande->fetchObjectLinked(); @@ -919,7 +922,7 @@ class Orders extends DolibarrApi $commande = array(); foreach (Orders::$FIELDS as $field) { if (!isset($data[$field])) - throw new RestException(400, $field ." field missing"); + throw new RestException(400, $field." field missing"); $commande[$field] = $data[$field]; } return $commande; diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index f095a814652..57eb78df405 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -101,6 +101,7 @@ class Commande extends CommonOrder /** * @var string Internal ref for order + * @deprecated */ public $ref_int; @@ -232,6 +233,94 @@ class Commande extends CommonOrder //! key of pos source ('0', '1', ...) public $pos_source; + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'enabled' is a condition when the field must be managed. + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields = array( + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1), + 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>25), + 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>26), + 'ref_int' =>array('type'=>'varchar(255)', 'label'=>'RefInt', 'enabled'=>1, 'visible'=>0, 'position'=>27), // deprecated + 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>28), + 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), + 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>25), + 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55), + 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>56), + 'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>60), + 'date_cloture' =>array('type'=>'datetime', 'label'=>'DateClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>65), + 'date_commande' =>array('type'=>'date', 'label'=>'Date', 'enabled'=>1, 'visible'=>-1, 'position'=>70), + 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>75), + 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>80), + 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>85), + 'fk_user_cloture' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'source' =>array('type'=>'smallint(6)', 'label'=>'Source', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + //'amount_ht' =>array('type'=>'double(24,8)', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>-1, 'position'=>105), + 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>110), + 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>115), + //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>120), + 'tva' =>array('type'=>'double(24,8)', 'label'=>'VAT', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), + 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LocalTax1', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), + 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LocalTax2', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), + 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), + 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>145, 'isameasure'=>1), + 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>150), + 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>155), + 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'PDFTemplate', 'enabled'=>1, 'visible'=>0, 'position'=>160), + //'facture' =>array('type'=>'tinyint(4)', 'label'=>'ParentInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>165), + 'fk_account' =>array('type'=>'integer', 'label'=>'BankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>170), + 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'MulticurrencyID', 'enabled'=>1, 'visible'=>-1, 'position'=>175), + 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'position'=>180), + 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>185), + 'date_livraison' =>array('type'=>'date', 'label'=>'DateDeliveryPlanned', 'enabled'=>1, 'visible'=>-1, 'position'=>190), + 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'ShippingMethod', 'enabled'=>1, 'visible'=>-1, 'position'=>195), + 'fk_warehouse' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Fk warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>200), + 'fk_availability' =>array('type'=>'integer', 'label'=>'Availability', 'enabled'=>1, 'visible'=>-1, 'position'=>205), + 'fk_input_reason' =>array('type'=>'integer', 'label'=>'InputReason', 'enabled'=>1, 'visible'=>-1, 'position'=>210), + //'fk_delivery_address' =>array('type'=>'integer', 'label'=>'DeliveryAddress', 'enabled'=>1, 'visible'=>-1, 'position'=>215), + 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>230), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>235), + 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>240), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>245), + 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>250, 'isameasure'=>1), + 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>255, 'isameasure'=>1), + 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>260, 'isameasure'=>1), + 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>265, 'isameasure'=>1), + 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270), + 'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>275), + 'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>280), + 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), + ); + // END MODULEBUILDER PROPERTIES + /** * ERR Not enough stock */ @@ -384,7 +473,7 @@ class Commande extends CommonOrder { $num = $this->ref; } - $this->newref = $num; + $this->newref = dol_sanitizeFileName($num); // Validate $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; @@ -927,6 +1016,14 @@ class Commande extends CommonOrder $vatrate = $line->tva_tx; if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if(!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { + $originid=$line->origin_id; + $origintype=$line->origin; + } else { + $originid=$line->id; + $origintype=$this->element; + } + $result = $this->addline( $line->desc, $line->subprice, @@ -951,8 +1048,8 @@ class Commande extends CommonOrder $line->label, $line->array_options, $line->fk_unit, - $this->element, - $line->id + $origintype, + $originid ); if ($result < 0) { @@ -1355,8 +1452,8 @@ class Commande extends CommonOrder * @param string $label Label * @param array $array_options extrafields array. Example array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...) * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object + * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'.... + * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id * @param double $pu_ht_devise Unit price in currency * @return int >0 if OK, <0 if KO * @@ -1685,13 +1782,13 @@ class Commande extends CommonOrder * @param int $id Id of object to load * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param string $ref_int Internal reference of other object + * @param string $notused Internal reference of other object * @return int >0 if OK, <0 if KO, 0 if not found */ - public function fetch($id, $ref = '', $ref_ext = '', $ref_int = '') + public function fetch($id, $ref = '', $ref_ext = '', $notused = '') { // Check parameters - if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1; + if (empty($id) && empty($ref) && empty($ref_ext)) return -1; $sql = 'SELECT c.rowid, c.entity, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, c.fk_user_valid, c.fk_statut'; $sql .= ', c.amount_ht, c.total_ht, c.total_ttc, c.tva as total_tva, c.localtax1 as total_localtax1, c.localtax2 as total_localtax2, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_availability, c.fk_input_reason'; @@ -1722,7 +1819,7 @@ class Commande extends CommonOrder 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)."'"; + if ($notused) $sql .= " AND c.ref_int='".$this->db->escape($notused)."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -1741,10 +1838,10 @@ class Commande extends CommonOrder $this->ref_int = $obj->ref_int; $this->socid = $obj->fk_soc; - $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty + $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty $this->fk_project = $obj->fk_project; - $this->project = null; // Clear if another value was already set by fetch_projet + $this->project = null; // Clear if another value was already set by fetch_projet $this->statut = $obj->fk_statut; $this->user_author_id = $obj->fk_user_author; @@ -3568,7 +3665,7 @@ class Commande extends CommonOrder * @param int $short ??? * @param int $notooltip 1=Disable tooltip * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking - * @param int $addlinktonotes Add linkt to notes + * @param int $addlinktonotes Add link to notes * @return string String with URL */ public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $notooltip = 0, $save_lastsearch_value = -1, $addlinktonotes = 0) diff --git a/htdocs/commande/class/commandestats.class.php b/htdocs/commande/class/commandestats.class.php index 0311f4c49ed..8b6dc4db6ec 100644 --- a/htdocs/commande/class/commandestats.class.php +++ b/htdocs/commande/class/commandestats.class.php @@ -23,10 +23,10 @@ * \ingroup commandes * \brief File of class to manage order statistics */ -include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; -include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php'; -include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php'; -include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php'; +include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; /** @@ -67,31 +67,31 @@ class CommandeStats extends Stats if ($mode == 'customer') { - $object=new Commande($this->db); + $object = new Commande($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field='total_ht'; - $this->field_line='total_ht'; - $this->where.= " c.fk_statut > 0"; // Not draft and not cancelled + $this->field = 'total_ht'; + $this->field_line = 'total_ht'; + $this->where .= " c.fk_statut > 0"; // Not draft and not cancelled } elseif ($mode == 'supplier') { - $object=new CommandeFournisseur($this->db); + $object = new CommandeFournisseur($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field='total_ht'; - $this->field_line='total_ht'; - $this->where.= " c.fk_statut > 2"; // Only approved & ordered + $this->field = 'total_ht'; + $this->field_line = 'total_ht'; + $this->where .= " c.fk_statut > 2"; // Only approved & ordered } //$this->where.= " AND c.fk_soc = s.rowid AND c.entity = ".$conf->entity; - $this->where.= ' AND c.entity IN ('.getEntity('commande').')'; + $this->where .= ' AND c.entity IN ('.getEntity('commande').')'; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; + if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; if ($this->socid) { - $this->where.=" AND c.fk_soc = ".$this->socid; + $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where.=' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; } /** @@ -106,14 +106,14 @@ class CommandeStats extends Stats global $user; $sql = "SELECT date_format(c.date_commande,'%m') as dm, COUNT(*) as nb"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getNbByMonth($year, $sql, $format); + $res = $this->_getNbByMonth($year, $sql, $format); return $res; } @@ -128,11 +128,11 @@ class CommandeStats extends Stats global $user; $sql = "SELECT date_format(c.date_commande,'%Y') as dm, COUNT(*) as nb, SUM(c.".$this->field.")"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getNbByYear($sql); } @@ -149,14 +149,14 @@ class CommandeStats extends Stats global $user; $sql = "SELECT date_format(c.date_commande,'%m') as dm, SUM(c.".$this->field.")"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getAmountByMonth($year, $sql, $format); + $res = $this->_getAmountByMonth($year, $sql, $format); return $res; } @@ -171,12 +171,12 @@ class CommandeStats extends Stats global $user; $sql = "SELECT date_format(c.date_commande,'%m') as dm, AVG(c.".$this->field.")"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getAverageByMonth($year, $sql); } @@ -191,11 +191,11 @@ class CommandeStats extends Stats global $user; $sql = "SELECT date_format(c.date_commande,'%Y') as year, COUNT(*) as nb, SUM(c.".$this->field.") as total, AVG(".$this->field.") as avg"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY year"; - $sql.= $this->db->order('year', 'DESC'); + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY year"; + $sql .= $this->db->order('year', 'DESC'); return $this->_getAllByYear($sql); } @@ -203,23 +203,24 @@ class CommandeStats extends Stats /** * Return nb, amount of predefined product for year * - * @param int $year Year to scan - * @return array Array of values + * @param int $year Year to scan + * @param int $limit Limit + * @return array Array of values */ - public function getAllByProduct($year) + public function getAllByProduct($year, $limit = 10) { global $user; $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; - $sql.= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " AND c.rowid = tl.fk_commande AND tl.fk_product = product.rowid"; - $sql.= " AND c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; - $sql.= " GROUP BY product.ref"; - $sql.= $this->db->order('nb', 'DESC'); + $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " AND c.rowid = tl.fk_commande AND tl.fk_product = product.rowid"; + $sql .= " AND c.date_commande BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " GROUP BY product.ref"; + $sql .= $this->db->order('nb', 'DESC'); //$sql.= $this->db->plimit(20); - return $this->_getAllByProduct($sql); + return $this->_getAllByProduct($sql, $limit); } } diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php index f6594b5694a..a3b754e0979 100644 --- a/htdocs/commande/customer.php +++ b/htdocs/commande/customer.php @@ -48,7 +48,7 @@ $langs->loadLangs(array("companies", "orders")); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index 6f71cf5c153..82d71dbe9d0 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -54,7 +54,7 @@ $result = restrictedArea($user, 'commande', $id, ''); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index b8866a7c487..072abe9625b 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -140,10 +140,10 @@ if ($resql) include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphstatus'); print $dolgraph->show($total ? 0 : 1); diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 0fa53f6c314..8448da5b022 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -74,7 +74,13 @@ $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_total_vat = GETPOST('search_total_vat', 'alpha'); $search_total_ttc = GETPOST('search_total_ttc', 'alpha'); +$search_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha'); +$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha'); +$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha'); +$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha'); +$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $search_login = GETPOST('search_login', 'alpha'); $search_categ_cus = trim(GETPOST("search_categ_cus", 'int')); $optioncss = GETPOST('optioncss', 'alpha'); @@ -96,7 +102,7 @@ $diroutputmassaction = $conf->commande->multidir_output[$conf->entity].'/temp/ma $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; $pageprev = $page - 1; @@ -141,6 +147,11 @@ $arrayfields = array( 'c.total_ht'=>array('label'=>"AmountHT", 'checked'=>1), 'c.total_vat'=>array('label'=>"AmountVAT", 'checked'=>0), 'c.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0), + 'c.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'c.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'c.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'c.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), + 'c.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1)), 'u.login'=>array('label'=>"Author", 'checked'=>1, 'position'=>10), 'c.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), 'c.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), @@ -197,6 +208,11 @@ if (empty($reshook)) $search_total_ht = ''; $search_total_vat = ''; $search_total_ttc = ''; + $search_multicurrency_code = ''; + $search_multicurrency_tx = ''; + $search_multicurrency_montant_ht = ''; + $search_multicurrency_montant_vat = ''; + $search_multicurrency_montant_ttc = ''; $search_login = ''; $search_dateorder_start = ''; $search_dateorder_end = ''; @@ -250,6 +266,7 @@ $sql .= ' s.rowid as socid, s.nom as name, s.email, s.town, s.zip, s.fk_pays, s. $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; $sql .= ' c.rowid, c.ref, c.total_ht, c.tva as total_tva, c.total_ttc, c.ref_client, c.fk_user_author,'; +$sql .= ' c.fk_multicurrency, c.multicurrency_code, c.multicurrency_tx, c.multicurrency_total_ht, c.multicurrency_total_tva as multicurrency_total_vat, c.multicurrency_total_ttc,'; $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, c.date_cloture as date_cloture,'; $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,"; @@ -314,25 +331,31 @@ if ($viewstatut <> '') } } -if ($search_dateorder_start) $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'"; -if ($search_dateorder_end) $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'"; -if ($search_datedelivery_start) $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; -if ($search_datedelivery_end) $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; -if ($search_total_ht != '') $sql .= natural_search('c.total_ht', $search_total_ht, 1); -if ($search_total_ttc != '') $sql .= natural_search('c.total_ttc', $search_total_ttc, 1); -if ($search_login) $sql .= natural_search("u.login", $search_login); -if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); -if ($search_project != '') $sql .= natural_search("p.title", $search_project); -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_dateorder_start) $sql .= " AND c.date_commande >= '".$db->idate($search_dateorder_start)."'"; +if ($search_dateorder_end) $sql .= " AND c.date_commande <= '".$db->idate($search_dateorder_end)."'"; +if ($search_datedelivery_start) $sql .= " AND c.date_livraison >= '".$db->idate($search_datedelivery_start)."'"; +if ($search_datedelivery_end) $sql .= " AND c.date_livraison <= '".$db->idate($search_datedelivery_end)."'"; +if ($search_town) $sql .= natural_search('s.town', $search_town); +if ($search_zip) $sql .= natural_search("s.zip", $search_zip); +if ($search_state) $sql .= natural_search("state.nom", $search_state); +if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; +if ($search_type_thirdparty) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +if ($search_company) $sql .= natural_search('s.nom', $search_company); +if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; +if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='commande' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +if ($search_total_ht != '') $sql .= natural_search('c.total_ht', $search_total_ht, 1); +if ($search_total_vat != '') $sql .= natural_search('c.tva', $search_total_vat, 1); +if ($search_total_ttc != '') $sql .= natural_search('c.total_ttc', $search_total_ttc, 1); +if ($search_multicurrency_code != '') $sql .= ' AND c.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +if ($search_multicurrency_tx != '') $sql .= natural_search('c.multicurrency_tx', $search_multicurrency_tx, 1); +if ($search_multicurrency_montant_ht != '') $sql .= natural_search('c.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +if ($search_multicurrency_montant_vat != '') $sql .= natural_search('c.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('c.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +if ($search_login) $sql .= natural_search("u.login", $search_login); +if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); +if ($search_project != '') $sql .= natural_search("p.title", $search_project); +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'; @@ -424,6 +447,11 @@ if ($resql) if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); 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_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); if ($search_login) $param .= '&search_login='.urlencode($search_login); if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); if ($search_town != '') $param .= '&search_town='.urlencode($search_town); @@ -697,6 +725,41 @@ if ($resql) print ''; print ''; } + if (!empty($arrayfields['c.multicurrency_code']['checked'])) + { + // Currency + print ''; + } + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) + { + // Currency rate + print ''; + } + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) + { + // Amount + print ''; + } if (!empty($arrayfields['u.login']['checked'])) { // Author @@ -775,6 +838,11 @@ if ($resql) if (!empty($arrayfields['c.total_ht']['checked'])) print_liste_field_titre($arrayfields['c.total_ht']['label'], $_SERVER["PHP_SELF"], 'c.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['c.total_vat']['checked'])) print_liste_field_titre($arrayfields['c.total_vat']['label'], $_SERVER["PHP_SELF"], 'c.tva', '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['c.total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.total_ttc']['label'], $_SERVER["PHP_SELF"], 'c.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['c.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_code', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['c.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'c.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); // Extra fields @@ -966,7 +1034,7 @@ if ($resql) // Ref customer if (!empty($arrayfields['c.ref_client']['checked'])) { - print ''; + print ''; if (!$i) $totalarray['nbfield']++; } @@ -1097,6 +1165,40 @@ if ($resql) $totalarray['val']['c.total_ttc'] += $obj->total_ttc; } + // Currency + if (!empty($arrayfields['c.multicurrency_code']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Currency rate + if (!empty($arrayfields['c.multicurrency_tx']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount HT + if (!empty($arrayfields['c.multicurrency_total_ht']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount VAT + if (!empty($arrayfields['c.multicurrency_total_vat']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount TTC + if (!empty($arrayfields['c.multicurrency_total_ttc']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; diff --git a/htdocs/commande/stats/index.php b/htdocs/commande/stats/index.php index e9eca9dafa9..c465cdcb8c9 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -255,7 +255,9 @@ print '
    '; // Show filter box print ''; +print ''; print ''; + print '
    ' . $langs->trans('Ref') . '' . $langs->trans("Draft") . '
    '.$langs->trans('Ref').''.$langs->trans("Draft").'
    ' . $langs->trans('RefCustomer') . ''; - if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && ! empty($origin) && ! empty($originid)) + print '
    '.$langs->trans('RefCustomer').''; + if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) print ''; + print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''.$obj->ref_client.''.$obj->ref_client.''.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); + print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."
    '; print ''; // Company diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index ac019de8088..318db920a52 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -16,11 +16,17 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ -/** + + /** * \file htdocs/compta/accounting-files.php * \ingroup compta * \brief Page to show portoflio and files of a thirdparty and download it */ + +if ($_GET['action'] == 'dl' || $_POST['action'] == 'dl') { // To not replace token when downloading file + if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); +} + require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -32,7 +38,7 @@ require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -$langs->loadLangs(array("accountancy", "bills", "companies", "salaries", "compta")); +$langs->loadLangs(array("accountancy", "bills", "companies", "salaries", "compta", "trips")); $date_start = GETPOST('date_start', 'alpha'); $date_startDay = GETPOST('date_startday', 'int'); @@ -54,7 +60,7 @@ $hookmanager->initHooks(array('comptafileslist', 'globallist')); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -66,7 +72,14 @@ if (!$sortorder) $sortorder = "DESC"; $arrayfields = array( 'type'=>array('label'=>"Type", 'checked'=>1), 'date'=>array('label'=>"Date", 'checked'=>1), - //... + 'date_due'=>array('label'=>"DateDue", 'checked'=>1), + 'ref'=>array('label'=>"Ref", 'checked'=>1), + 'documents'=>array('label'=>"Documents", 'checked'=>1), + 'paid'=>array('label'=>"Paid", 'checked'=>1), + 'total_ht'=>array('label'=>"TotalHT", 'checked'=>1), + 'total_ttc'=>array('label'=>"TotalTTC", 'checked'=>1), + 'total_vat'=>array('label'=>"TotalVAT", 'checked'=>1), + //... ); // Security check @@ -77,7 +90,22 @@ if ($user->socid > 0) { accessforbidden(); } -$entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; +// Define $arrayofentities if multientity is set. +$arrayofentities = array(); +if (!empty($conf->multicompany->enabled) && is_object($mc)) { + $arrayofentities = $mc->getEntitiesList(); +} + +$entity = (GETPOSTISSET('entity') ? GETPOST('entity', 'int') : (GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $conf->entity)); +if (!empty($conf->multicompany->enabled) && is_object($mc)) { + if (empty($entity) && !empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) { + $entity = '0,'.join(',', array_keys($arrayofentities)); + } +} +if (empty($entity)) $entity = $conf->entity; + +$error = 0; + /* @@ -91,7 +119,7 @@ $entity = GETPOST('entity', 'int') ?GETPOST('entity', 'int') : $conf->entity; $filesarray = array(); $result = false; -if (($action == "searchfiles" || $action == "dl")) { +if (($action == 'searchfiles' || $action == 'dl')) { if (empty($date_start)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateStart")), null, 'errors'); @@ -105,188 +133,213 @@ if (($action == "searchfiles" || $action == "dl")) { if (!$error) { + $sql = ''; + $wheretail = " '".$db->idate($date_start)."' AND '".$db->idate($date_stop)."'"; // Customer invoices - $sql = "SELECT t.rowid as id, t.ref, t.paye as paid, total as total_ht, total_ttc, tva as total_vat, fk_soc, t.datef as date, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; - $sql .= " WHERE datef between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - $sql .= " AND t.fk_statut <> ".Facture::STATUS_DRAFT; - $sql .= " UNION ALL"; + if (GETPOST('selectinvoices')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= "SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total as total_ht, t.total_ttc, t.tva as total_vat, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'Invoice' as item, s.nom as thirdparty_name, s.code_client as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; + $sql .= " WHERE datef between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".Facture::STATUS_DRAFT; + } // Vendor invoices - $sql .= " SELECT t.rowid as id, t.ref, paye as paid, total_ht, total_ttc, total_tva as total_vat, fk_soc, datef as date, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; - $sql .= " WHERE datef between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - $sql .= " AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT; - $sql .= " UNION ALL"; + if (GETPOST('selectsupplierinvoices')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paye as paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.fk_soc, t.datef as date, t.date_lim_reglement as date_due, 'SupplierInvoice' as item, s.nom as thirdparty_name, s.code_fournisseur as thirdparty_code, c.code as country_code, s.tva_intra as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = t.fk_soc LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = s.fk_pays"; + $sql .= " WHERE datef between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".FactureFournisseur::STATUS_DRAFT; + } // Expense reports - $sql .= " SELECT t.rowid as id, t.ref, paid, total_ht, total_ttc, total_tva as total_vat, fk_user_author as fk_soc, date_fin as date, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; - $sql .= " WHERE date_fin between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - $sql .= " AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT; - $sql .= " UNION ALL"; + if (GETPOST('selectexpensereports')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.entity, t.ref, t.paid, t.total_ht, t.total_ttc, t.total_tva as total_vat, t.fk_user_author as fk_soc, t.date_fin as date, t.date_fin as date_due, 'ExpenseReport' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user_author LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; + $sql .= " WHERE date_fin between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".ExpenseReport::STATUS_DRAFT; + } // Donations - $sql .= " SELECT t.rowid as id, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, 0 as fk_soc, datedon as date, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country"; - $sql .= " WHERE datedon between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT; - $sql .= " UNION ALL"; + if (GETPOST('selectdonations')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.entity, t.ref, paid, amount as total_ht, amount as total_ttc, 0 as total_vat, 0 as fk_soc, t.datedon as date, t.datedon as date_due, 'Donation' as item, t.societe as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."don as t LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_country"; + $sql .= " WHERE datedon between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT; + } // Paiements of salaries - $sql .= " SELECT t.rowid as id, t.ref as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, t.fk_user as fk_soc, datep as date, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; - $sql .= " WHERE datep between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - //$sql.=" AND fk_statut <> ".PaymentSalary::STATUS_DRAFT; - $sql .= " UNION ALL"; + if (GETPOST('selectpaymentsofsalaries')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.entity, t.ref as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, t.fk_user as fk_soc, t.datep as date, t.dateep as date_due, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_salary as t LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid = t.fk_user LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = u.fk_country"; + $sql .= " WHERE datep between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + //$sql.=" AND fk_statut <> ".PaymentSalary::STATUS_DRAFT; + } // Social contributions - $sql .= " SELECT t.rowid as id, t.libelle as ref, paye as paid, amount as total_ht, amount as total_ttc, 0 as total_tva, 0 as fk_soc, date_creation as date, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum"; - $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t"; - $sql .= " WHERE date_creation between ".$wheretail; - $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; - //$sql.=" AND fk_statut <> ".ChargeSociales::STATUS_DRAFT; - $sql .= $db->order($sortfield, $sortorder); - //print $sql; + if (GETPOST('selectsocialcontributions')) { + if (!empty($sql)) $sql .= " UNION ALL"; + $sql .= " SELECT t.rowid as id, t.entity, t.libelle as ref, t.paye as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_tva, 0 as fk_soc, t.date_creation as date, t.date_ech as date_due, 'SocialContributions' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum"; + $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as t"; + $sql .= " WHERE date_creation between ".$wheretail; + $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; + //$sql.=" AND fk_statut <> ".ChargeSociales::STATUS_DRAFT; + } - $resd = $db->query($sql); - $files = array(); - $link = ''; + if ($sql) { + $sql .= $db->order($sortfield, $sortorder); + //print $sql; - if ($resd) - { - $numd = $db->num_rows($resd); + $resd = $db->query($sql); + $files = array(); + $link = ''; - $tmpinvoice = new Facture($db); - $tmpinvoicesupplier = new FactureFournisseur($db); - $tmpdonation = new Don($db); + if ($resd) + { + $numd = $db->num_rows($resd); - $upload_dir = ''; - $i = 0; - while ($i < $numd) - { - $objd = $db->fetch_object($resd); + $tmpinvoice = new Facture($db); + $tmpinvoicesupplier = new FactureFournisseur($db); + $tmpdonation = new Don($db); - switch ($objd->item) - { - case "Invoice": - $subdir = ''; - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); - $upload_dir = $conf->facture->dir_output.'/'.$subdir; - $link = "document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - case "SupplierInvoice": - $tmpinvoicesupplier->fetch($objd->id); - $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); - $upload_dir = $conf->fournisseur->facture->dir_output.'/'.$subdir; - $link = "document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - case "ExpenseReport": - $subdir = ''; - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); - $upload_dir = $conf->expensereport->dir_output.'/'.$subdir; - $link = "document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - case "SalaryPayment": - $subdir = ''; - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); - $upload_dir = $conf->salaries->dir_output.'/'.$subdir; - $link = "document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - case "Donation": - $tmpdonation->fetch($objp->id); - $subdir = get_exdir(0, 0, 0, 0, $tmpdonation, 'donation'); - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); - $upload_dir = $conf->don->dir_output.'/'.$subdir; - $link = "document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - case "SocialContributions": - $subdir = ''; - $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); - $upload_dir = $conf->tax->dir_output.'/'.$subdir; - $link = "document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F'; - break; - default: - $subdir = ''; - $upload_dir = ''; - $link = ''; - break; - } + $upload_dir = ''; + $i = 0; + while ($i < $numd) + { + $objd = $db->fetch_object($resd); - if (!empty($upload_dir)) - { - $result = true; + switch ($objd->item) + { + case "Invoice": + $subdir = ''; + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $upload_dir = $conf->facture->dir_output.'/'.$subdir; + $link = "document.php?modulepart=facture&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + case "SupplierInvoice": + $tmpinvoicesupplier->fetch($objd->id); + $subdir = get_exdir($tmpinvoicesupplier->id, 2, 0, 1, $tmpinvoicesupplier, 'invoice_supplier'); // TODO Use first file + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $upload_dir = $conf->fournisseur->facture->dir_output.'/'.$subdir; + $link = "document.php?modulepart=facture_fournisseur&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + case "ExpenseReport": + $subdir = ''; + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->ref); + $upload_dir = $conf->expensereport->dir_output.'/'.$subdir; + $link = "document.php?modulepart=expensereport&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + case "SalaryPayment": + $subdir = ''; + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $upload_dir = $conf->salaries->dir_output.'/'.$subdir; + $link = "document.php?modulepart=salaries&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + case "Donation": + $tmpdonation->fetch($objp->id); + $subdir = get_exdir(0, 0, 0, 0, $tmpdonation, 'donation'); + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $upload_dir = $conf->don->dir_output.'/'.$subdir; + $link = "document.php?modulepart=don&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + case "SocialContributions": + $subdir = ''; + $subdir .= ($subdir ? '/' : '').dol_sanitizeFileName($objd->id); + $upload_dir = $conf->tax->dir_output.'/'.$subdir; + $link = "document.php?modulepart=tax&file=".str_replace('/', '%2F', $subdir).'%2F'; + break; + default: + $subdir = ''; + $upload_dir = ''; + $link = ''; + break; + } - $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview\.png)$', '', SORT_ASC, 1); - //var_dump($upload_dir); - //var_dump($files); + if (!empty($upload_dir)) + { + $result = true; - if (count($files) < 1) - { - $nofile = array(); - $nofile['id'] = $objd->id; - $nofile['date'] = $db->idate($objd->date); - $nofile['paid'] = $objd->paid; - $nofile['amount_ht'] = $objd->total_ht; - $nofile['amount_ttc'] = $objd->total_ttc; - $nofile['amount_vat'] = $objd->total_vat; - $nofile['ref'] = ($objd->ref ? $objd->ref : $objd->id); - $nofile['fk'] = $objd->fk_soc; - $nofile['item'] = $objd->item; - $nofile['thirdparty_name'] = $objd->thirdparty_name; - $nofile['thirdparty_code'] = $objd->thirdparty_code; - $nofile['country_code'] = $objd->country_code; - $nofile['vatnum'] = $objd->vatnum; + $files = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', '', SORT_ASC, 1); + //var_dump($upload_dir); + //var_dump($files); + if (count($files) < 1) + { + $nofile = array(); + $nofile['id'] = $objd->id; + $nofile['entity'] = $objd->entity; + $nofile['date'] = $db->idate($objd->date); + $nofile['date_due'] = $db->idate($objd->date_due); + $nofile['paid'] = $objd->paid; + $nofile['amount_ht'] = $objd->total_ht; + $nofile['amount_ttc'] = $objd->total_ttc; + $nofile['amount_vat'] = $objd->total_vat; + $nofile['ref'] = ($objd->ref ? $objd->ref : $objd->id); + $nofile['fk'] = $objd->fk_soc; + $nofile['item'] = $objd->item; + $nofile['thirdparty_name'] = $objd->thirdparty_name; + $nofile['thirdparty_code'] = $objd->thirdparty_code; + $nofile['country_code'] = $objd->country_code; + $nofile['vatnum'] = $objd->vatnum; - $filesarray[$nofile['item'].'_'.$nofile['id']] = $nofile; - } - else - { - foreach ($files as $key => $file) - { - $file['id'] = $objd->id; - $file['date'] = $db->idate($objd->date); - $file['paid'] = $objd->paid; - $file['amount_ht'] = $objd->total_ht; - $file['amount_ttc'] = $objd->total_ttc; - $file['amount_vat'] = $objd->total_vat; - $file['ref'] = ($objd->ref ? $objd->ref : $objd->id); - $file['fk'] = $objd->fk_soc; - $file['item'] = $objd->item; + $filesarray[$nofile['item'].'_'.$nofile['id']] = $nofile; + } + else + { + foreach ($files as $key => $file) + { + $file['id'] = $objd->id; + $file['entity'] = $objd->entity; + $file['date'] = $db->idate($objd->date); + $file['date_due'] = $db->idate($objd->date_due); + $file['paid'] = $objd->paid; + $file['amount_ht'] = $objd->total_ht; + $file['amount_ttc'] = $objd->total_ttc; + $file['amount_vat'] = $objd->total_vat; + $file['ref'] = ($objd->ref ? $objd->ref : $objd->id); + $file['fk'] = $objd->fk_soc; + $file['item'] = $objd->item; - $file['thirdparty_name'] = $objd->thirdparty_name; - $file['thirdparty_code'] = $objd->thirdparty_code; - $file['country_code'] = $objd->country_code; - $file['vatnum'] = $objd->vatnum; + $file['thirdparty_name'] = $objd->thirdparty_name; + $file['thirdparty_code'] = $objd->thirdparty_code; + $file['country_code'] = $objd->country_code; + $file['vatnum'] = $objd->vatnum; - // Save record into array (only the first time it is found) - if (empty($filesarray[$file['item'].'_'.$file['id']])) { - $filesarray[$file['item'].'_'.$file['id']] = $file; - } + // Save record into array (only the first time it is found) + if (empty($filesarray[$file['item'].'_'.$file['id']])) { + $filesarray[$file['item'].'_'.$file['id']] = $file; + } - // Add or concat file - if (empty($filesarray[$file['item'].'_'.$file['id']]['files'])) { - $filesarray[$file['item'].'_'.$file['id']]['files'] = array(); - } - $filesarray[$file['item'].'_'.$file['id']]['files'][] = array('link' => $link.$file['name'], 'name'=>$file['name'], 'ref'=>$file['ref'], 'fullname' => $file['fullname'], 'relpathnamelang' => $langs->trans($file['item']).'/'.$file['name']); - //var_dump($file['item'].'_'.$file['id']); - //var_dump($filesarray[$file['item'].'_'.$file['id']]['files']); - } - } - } + // Add or concat file + if (empty($filesarray[$file['item'].'_'.$file['id']]['files'])) { + $filesarray[$file['item'].'_'.$file['id']]['files'] = array(); + } + $filesarray[$file['item'].'_'.$file['id']]['files'][] = array('link' => $link.$file['name'], 'name'=>$file['name'], 'ref'=>$file['ref'], 'fullname' => $file['fullname'], 'relpathnamelang' => $langs->trans($file['item']).'/'.$file['name']); + //var_dump($file['item'].'_'.$file['id']); + //var_dump($filesarray[$file['item'].'_'.$file['id']]['files']); + } + } + } - $i++; - } - } - else - { - dol_print_error($db); - } + $i++; + } + } + else + { + dol_print_error($db); + } - $db->free($resd); + $db->free($resd); + } + else { + setEventMessages($langs->trans("ErrorSelectAtLeastOne"), null, 'errors'); + $error++; + } } } @@ -314,13 +367,19 @@ if ($result && $action == "dl" && !$error) dol_mkdir($dirfortmpfile); $log = $langs->transnoentitiesnoconv("Type"); + if (!empty($conf->multicompany->enabled) && is_object($mc)) + { + $log .= ','.$langs->transnoentitiesnoconv("Entity"); + } $log .= ','.$langs->transnoentitiesnoconv("Date"); + $log .= ','.$langs->transnoentitiesnoconv("DateDue"); $log .= ','.$langs->transnoentitiesnoconv("Ref"); $log .= ','.$langs->transnoentitiesnoconv("TotalHT"); $log .= ','.$langs->transnoentitiesnoconv("TotalTTC"); $log .= ','.$langs->transnoentitiesnoconv("TotalVAT"); $log .= ','.$langs->transnoentitiesnoconv("Paid"); - $log .= ',filename,item_id'; + $log .= ','.$langs->transnoentitiesnoconv("Document"); + $log .= ','.$langs->transnoentitiesnoconv("ItemID"); $log .= ','.$langs->transnoentitiesnoconv("ThirdParty"); $log .= ','.$langs->transnoentitiesnoconv("Code"); $log .= ','.$langs->transnoentitiesnoconv("Country"); @@ -335,25 +394,31 @@ if ($result && $action == "dl" && !$error) { foreach ($filesarray as $key => $file) { - foreach($file['files'] as $filecursor) { + foreach ($file['files'] as $filecursor) { if (file_exists($filecursor["fullname"])) { $zip->addFile($filecursor["fullname"], $filecursor["relpathnamelang"]); } } - $log .= $file['item']; + $log .= '"'.$langs->trans($file['item']).'"'; + if (!empty($conf->multicompany->enabled) && is_object($mc)) + { + $log .= ',"'.(empty($arrayofentities[$file['entity']]) ? $file['entity'] : $arrayofentities[$file['entity']]).'"'; + } $log .= ','.dol_print_date($file['date'], 'dayrfc'); - $log .= ','.$file['ref']; + $log .= ','.dol_print_date($file['date_due'], 'dayrfc'); + $log .= ',"'.$file['ref'].'"'; $log .= ','.$file['amount_ht']; $log .= ','.$file['amount_ttc']; $log .= ','.$file['amount_vat']; $log .= ','.$file['paid']; - $log .= ','.$file["name"]; + $log .= ',"'.$file["name"].'"'; $log .= ','.$file['fk']; - $log .= ','.$file['thirdparty_name']; - $log .= ','.$file['thirdparty_code']; - $log .= ','.$file['country_code']; - $log .= ',"'.$file['vatnum'].'"'."\n"; + $log .= ',"'.$file['thirdparty_name'].'"'; + $log .= ',"'.$file['thirdparty_code'].'"'; + $log .= ',"'.$file['country_code'].'"'; + $log .= ',"'.$file['vatnum'].'"'; + $log .= "\n"; } $zip->addFromString('transactions.csv', $log); $zip->close(); @@ -381,13 +446,17 @@ if ($result && $action == "dl" && !$error) $form = new Form($db); $userstatic = new User($db); +$invoice = new Facture($db); +$supplier_invoice = new FactureFournisseur($db); $title = $langs->trans("ComptaFiles").' - '.$langs->trans("List"); +$help_url = ''; llxHeader('', $title, $help_url); $h = 0; -$head[$h][0] = $_SERVER["PHP_SELF"].$varlink; +$head = array(); +$head[$h][0] = $_SERVER["PHP_SELF"]; $head[$h][1] = $langs->trans("AccountantFiles"); $head[$h][2] = 'AccountancyFiles'; @@ -400,16 +469,36 @@ print ''; print $langs->trans("ReportPeriod").': '.$form->selectDate($date_start, 'date_start', 0, 0, 0, "", 1, 1, 0); print ' - '.$form->selectDate($date_stop, 'date_stop', 0, 0, 0, "", 1, 1, 0)."\n"; -// Export is for current company only ! +// Export is for current company only if (!empty($conf->multicompany->enabled) && is_object($mc)) { - print '('.$langs->trans("Entity").' : '; - $mc->dao->getEntities(); - $mc->dao->fetch($conf->entity); - print $mc->dao->label; + $mc->getInfo($conf->entity); + print '('.$langs->trans("Entity").' : '; + print ""; print ")\n"; } +print '
    '; + +$listofchoices = array( + 'selectinvoices'=>array('label'=>'Invoices', 'lang'=>'bills'), + 'selectsupplierinvoices'=>array('label'=>'BillsSuppliers', 'lang'=>'bills'), + 'selectexpensereports'=>array('label'=>'ExpenseReports', 'lang'=>'trips'), + 'selectdonations'=>array('label'=>'Donations', 'lang'=>'donation'), + 'selectpaymentsofsalaries'=>array('label'=>'SalariesPayments', 'lang'=>'salaries'), + 'selectsocialcontributions'=>array('label'=>'SocialContributions') +); +foreach ($listofchoices as $choice => $val) { + $checked = (((!GETPOSTISSET('search') && $action != 'searchfiles') || GETPOST($choice)) ? ' checked="checked"' : ''); + print '
    '.$langs->trans($val['label']).'
    '; +} + print ''; print ''."\n"; @@ -425,22 +514,19 @@ if (!empty($date_start) && !empty($date_stop)) $param .= '&date_stopday='.GETPOST('date_stopday', 'int'); $param .= '&date_stopmonth='.GETPOST('date_stopmonth', 'int'); $param .= '&date_stopyear='.GETPOST('date_stopyear', 'int'); - + foreach ($listofchoices as $choice => $val) { + $param .= '&'.$choice.'='.(GETPOST($choice, 'int') ? 1 : 0); + } print ''."\n"; - print ''; + print ''; echo dol_print_date($date_start, 'day')." - ".dol_print_date($date_stop, 'day'); print ''; print ''; - - //print ''; - //print ''; - //print ''; - - //print ''; - //print ''; - //print ''; + foreach ($listofchoices as $choice => $val) { + print ''; + } print ''; print ''."\n"; @@ -452,7 +538,8 @@ if (!empty($date_start) && !empty($date_stop)) print ''; print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "item", "", $param, '', $sortfield, $sortorder, 'nowrap '); print_liste_field_titre($arrayfields['date']['label'], $_SERVER["PHP_SELF"], "date", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - print ''; + print_liste_field_titre($arrayfields['date_due']['label'], $_SERVER["PHP_SELF"], "date_due", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'nowraponall '); print ''; print ''; print ''; @@ -497,14 +584,32 @@ if (!empty($date_start) && !empty($date_stop)) print dol_print_date($data['date'], 'day'); print "\n"; + // Date + print '\n"; + // Ref - print ''; + print ''; // File link print ''; print ''; print ''; + print ''; print ''; print ''; print ''; diff --git a/htdocs/compta/bank/account_statement_document.php b/htdocs/compta/bank/account_statement_document.php index 08447216dda..4c1d06e37fa 100644 --- a/htdocs/compta/bank/account_statement_document.php +++ b/htdocs/compta/bank/account_statement_document.php @@ -59,7 +59,7 @@ if ($user->socid) // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } $offset = $conf->liste_limit * $page; $pageprev = $page - 1; @@ -137,9 +137,9 @@ if ($id > 0 || !empty($ref)) { $modulepart = 'bank'; $permission = $user->rights->banque->modifier; $permtoedit = $user->rights->banque->modifier; - $param = '&id='.$object->id.'&num='.$num; - $uri = '&num='.$num; - $relativepathwithnofile = $id."/statement/".$num."/"; + $param = '&id='.$object->id.'&num='.urlencode($num); + $moreparam = '&num='.urlencode($num);; + $relativepathwithnofile = $id."/statement/".dol_sanitizeFileName($num)."/"; include_once DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 297f0dd91d4..26563f98dd4 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -98,7 +98,7 @@ if (empty($dateop)) $dateop = -1; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $pageplusone = GETPOST("pageplusone", 'int'); if ($pageplusone) $page = $pageplusone - 1; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 @@ -1157,14 +1157,14 @@ if ($resql) } else { $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; } - $backgroundcolor = 'style="background-color: '.$color.';"'; + $backgroundcolor = 'style="background: '.$color.';"'; } else { if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { $color = '#7fdb86'; } else { $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; } - $backgroundcolor = 'style="background-color: '.$color.';"'; + $backgroundcolor = 'style="background: '.$color.';"'; } } print ''; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 6fc0efbd6e0..60d7c4f2463 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -1337,6 +1337,10 @@ class Account extends CommonObject $label .= '
    '.$langs->trans('AccountAccounting').': '.length_accountg($this->account_number); $label .= '
    '.$langs->trans('AccountancyJournal').': '.$this->accountancy_journal; } + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } + $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id; diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index 2ecb59861d9..1272cfcad85 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -183,10 +183,10 @@ class BankAccounts extends DolibarrApi * * @status 201 * - * @throws 401 Unauthorized: User does not have permission to configure bank accounts - * @throws 404 Not Found: Either the source or the destination bankaccount for the provided id does not exist - * @throws 422 Unprocessable Entity: Refer to detailed exception message for the cause - * @throws 500 Internal Server Error: Error(s) returned by the RDBMS + * @throws RestException 401 Unauthorized: User does not have permission to configure bank accounts + * @throws RestException 404 Not Found: Either the source or the destination bankaccount for the provided id does not exist + * @throws RestException 422 Unprocessable Entity: Refer to detailed exception message for the cause + * @throws RestException 500 Internal Server Error: Error(s) returned by the RDBMS */ public function transfer($bankaccount_from_id = 0, $bankaccount_to_id = 0, $date = null, $description = "", $amount = 0.0, $amount_to = 0.0) { diff --git a/htdocs/compta/bank/document.php b/htdocs/compta/bank/document.php index b70a3ba2c77..022e1ceea5a 100644 --- a/htdocs/compta/bank/document.php +++ b/htdocs/compta/bank/document.php @@ -56,7 +56,7 @@ if ($user->socid) // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } $offset = $conf->liste_limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index fbcd06a51bc..ccf677fa2b8 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -255,13 +255,14 @@ else $px1->draw($file, $fileurl); $show1 = $px1->show(); - unset($graph_datas); - unset($px1); - unset($datas); - unset($datamin); - unset($dataall); - unset($labels); - unset($amounts); + + $px1 = null; + $graph_datas =null; + $datas = null; + $datamin = null; + $dataall = null; + $labels = null; + $amounts = null; } // Graph Balance for the year @@ -349,10 +350,11 @@ else } $datamin[$i] = $object->min_desired; $dataall[$i] = $object->min_allowed; - if ($xday == '15') + /*if ($xday == '15') // Set only some label for jflot { $labels[$i] = dol_print_date($day, "%b"); - } + }*/ + $labels[$i] = dol_print_date($day, "%Y%m"); $day += 86400; $textdate = strftime("%Y%m%d", $day); $xyear = substr($textdate, 0, 4); @@ -392,13 +394,13 @@ else $show2 = $px2->show(); - unset($px2); - unset($graph_datas); - unset($datas); - unset($datamin); - unset($dataall); - unset($labels); - unset($amounts); + $px2 = null; + $graph_datas =null; + $datas = null; + $datamin = null; + $dataall = null; + $labels = null; + $amounts = null; } // Graph 3 - Balance for all time line @@ -460,14 +462,15 @@ else } else { - $datas[$i] = '' +$solde + $subtotal; + $datas[$i] = 0 + $solde + $subtotal; } $datamin[$i] = $object->min_desired; $dataall[$i] = $object->min_allowed; - if (substr($textdate, 6, 2) == '01' || $i == 0) + /*if (substr($textdate, 6, 2) == '01' || $i == 0) // Set only few label for jflot { - $labels[$i] = substr($textdate, 4, 2); - } + $labels[$i] = substr($textdate, 0, 6); + }*/ + $labels[$i] = substr($textdate, 0, 6); $day += 86400; $textdate = strftime("%Y%m%d", $day); @@ -505,13 +508,13 @@ else $show3 = $px3->show(); - unset($px3); - unset($graph_datas); - unset($datas); - unset($datamin); - unset($dataall); - unset($labels); - unset($amounts); + $px3 = null; + $graph_datas =null; + $datas = null; + $datamin = null; + $dataall = null; + $labels = null; + $amounts = null; } // Tableau 4a - Credit/Debit @@ -634,10 +637,10 @@ else $show4 = $px4->show(); - unset($graph_datas); - unset($px4); - unset($debits); - unset($credits); + $px4 = null; + $graph_datas = null; + $debits = null; + $credits = null; } // Tableau 4b - Credit/Debit @@ -742,10 +745,10 @@ else $show5 = $px5->show(); - unset($graph_datas); - unset($px5); - unset($debits); - unset($credits); + $px5 = null; + $graph_datas = null; + $debits = null; + $credits = null; } } @@ -814,6 +817,8 @@ else } print '

    '; +print '
    '.$langs->trans("Filter").'
    "; + if (!empty($conf->global->MULTICOMPANY_ALLOW_EXPORT_ACCOUNTING_DOC_FOR_ALL_ENTITIES)) { + print $mc->select_entities(GETPOSTISSET('search_entity') ? GETPOST('search_entity', 'int') : $mc->id, 'search_entity', '', false, false, false, false, true); + } else { + print $mc->label; + } + print "
    '.$langs->trans("Ref").''.$langs->trans("Document").''.$langs->trans("Paid").''.$langs->trans("TotalHT").''; + print dol_print_date($data['date_due'], 'day'); + print "'.$data['ref'].''; + + if ($data['item'] == 'Invoice') { + $invoice->id = $data['id']; + $invoice->ref = $data['ref']; + print $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); + } elseif ($data['item'] == 'SupplierInvoice') { + $supplier_invoice->id = $data['id']; + $supplier_invoice->ref = $data['ref']; + print $supplier_invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); + } else { + print $data['ref']; + } + print ''; - if (! empty($data['files'])) + if (!empty($data['files'])) { - foreach($data['files'] as $filecursor) { + foreach ($data['files'] as $filecursor) { print ''.($filecursor['name'] ? $filecursor['name'] : $filecursor['ref']).'
    '; } } @@ -552,6 +657,7 @@ if (!empty($date_start) && !empty($date_stop)) print '
    '.price(price2num($totalET, 'MT')).''.price(price2num($totalIT, 'MT')).''.price(price2num($totalVAT, 'MT')).'
    '; + // Graphs if ($mode == 'standard') @@ -825,39 +830,39 @@ if ($mode == 'standard') // For month $link = "".img_previous('', 'class="valignbottom"')." ".$langs->trans("Month")." ".img_next('', 'class="valignbottom"').""; - print '
    '.$link.'
    '; + print '
    '; $file = "movement".$account."-".$year.$month.".png"; print $show4; - print '
    '; + print '
    '; print $show1; - print '
    '.$link.'
    '; + print '
    '.$link.'
    '; + + print '
    '; print $show5; - print '
    '; + print '
    '; print $show2; - print '
    '; + print '
    '; print $show3; - print '
    '; // End of page llxFooter(); diff --git a/htdocs/compta/bank/list.php b/htdocs/compta/bank/list.php index 329ac25ef79..82728fc693d 100644 --- a/htdocs/compta/bank/list.php +++ b/htdocs/compta/bank/list.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2018 Ferran Marcet + * Copyright (C) 2020 Tobias Sekan * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -30,36 +31,43 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.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/accountingaccount.class.php'; -if (! empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingjournal.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcategory.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'; +if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // 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'); +$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 +$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'); -$search_number=GETPOST('search_number', 'alpha'); -$search_status=GETPOST('search_status')?GETPOST('search_status', 'alpha'):'opened'; // 'all' or ''='opened' +$search_ref = GETPOST('search_ref', 'alpha'); +$search_label = GETPOST('search_label', 'alpha'); +$search_number = GETPOST('search_number', 'alpha'); +$search_status = GETPOST('search_status') ?GETPOST('search_status', 'alpha') : 'opened'; // 'all' or ''='opened' $optioncss = GETPOST('optioncss', 'alpha'); +if (!empty($conf->categorie->enabled)) +{ + $search_category_list = GETPOST("search_category_".Categorie::TYPE_ACCOUNT."_list", "array"); +} + // Security check -if ($user->socid) $socid=$user->socid; -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'); +if ($user->socid) $socid = $user->socid; +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; +$diroutputmassaction = $conf->bank->dir_output.'/temp/massgeneration/'.$user->id; -$limit = GETPOST('limit', 'int')?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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -74,7 +82,7 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extrafields->fetch_name_optionals_label($object->table_element); -$search_array_options=$extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -100,10 +108,10 @@ $arrayfields = array( // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { - foreach($extrafields->attributes[$object->table_element]['label'] as $key => $val) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - if (! empty($extrafields->attributes[$object->table_element]['list'][$key])) - $arrayfields["ef.".$key]=array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key]<0)?0:1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key])!=3 && $extrafields->attributes[$object->table_element]['perms'][$key])); + if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) + $arrayfields["ef.".$key] = array('label'=>$extrafields->attributes[$object->table_element]['label'][$key], 'checked'=>(($extrafields->attributes[$object->table_element]['list'][$key] < 0) ? 0 : 1), 'position'=>$extrafields->attributes[$object->table_element]['pos'][$key], 'enabled'=>(abs($extrafields->attributes[$object->table_element]['list'][$key]) != 3 && $extrafields->attributes[$object->table_element]['perms'][$key])); } } $object->fields = dol_sort_array($object->fields, 'position'); @@ -138,38 +146,50 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' * View */ -$form=new Form($db); +$form = new FormCategory($db); -$title=$langs->trans('BankAccounts'); +$title = $langs->trans('BankAccounts'); // Load array of financial accounts (opened by default) $accounts = array(); $sql = "SELECT b.rowid, b.label, b.courant, b.rappro, b.account_number, b.fk_accountancy_journal, b.currency_code, b.datec as date_creation, b.tms as date_update"; // Add fields from extrafields -if (! empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql.=($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); } // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " FROM ".MAIN_DB_PREFIX."bank_account as b"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (b.rowid = ef.fk_object)"; -$sql.= " WHERE b.entity IN (".getEntity('bank_account').")"; -if ($search_status == 'opened') $sql.= " AND clos = 0"; -if ($search_status == 'closed') $sql.= " AND clos = 1"; -if ($search_ref != '') $sql.=natural_search('b.ref', $search_ref); -if ($search_label != '') $sql.=natural_search('b.label', $search_label); -if ($search_number != '') $sql.=natural_search('b.number', $search_number); +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as b"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (b.rowid = ef.fk_object)"; + +if (!empty($conf->categorie->enabled)) +{ + $sql .= Categorie::getFilterJoinQuery(Categorie::TYPE_ACCOUNT, "b.rowid"); +} + +$sql .= " WHERE b.entity IN (".getEntity('bank_account').")"; +if ($search_status == 'opened') $sql .= " AND clos = 0"; +if ($search_status == 'closed') $sql .= " AND clos = 1"; + +if (!empty($conf->categorie->enabled)) +{ + $sql .= Categorie::getFilterSelectQuery(Categorie::TYPE_ACCOUNT, "b.rowid", $search_category_list); +} + +if ($search_ref != '') $sql .= natural_search('b.ref', $search_ref); +if ($search_label != '') $sql .= natural_search('b.label', $search_label); +if ($search_number != '') $sql .= natural_search('b.number', $search_number); // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; @@ -263,6 +283,10 @@ if ($sall) $moreforfilter = ''; +if (!empty($conf->categorie->enabled)) +{ + $moreforfilter .= $form->getFilterBox(Categorie::TYPE_ACCOUNT, $search_category_list); +} // Bank accounts $parameters = array(); @@ -414,52 +438,52 @@ foreach ($accounts as $key=>$type) $solde = $objecttmp->solde(1); - if (! empty($lastcurrencycode) && $lastcurrencycode != $objecttmp->currency_code) + if (!empty($lastcurrencycode) && $lastcurrencycode != $objecttmp->currency_code) { - $lastcurrencycode='various'; // We found several different currencies + $lastcurrencycode = 'various'; // We found several different currencies } if ($lastcurrencycode != 'various') { - $lastcurrencycode=$objecttmp->currency_code; + $lastcurrencycode = $objecttmp->currency_code; } print ''; // Ref - if (! empty($arrayfields['b.ref']['checked'])) + if (!empty($arrayfields['b.ref']['checked'])) { print ''.$objecttmp->getNomUrl(1).''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Label - if (! empty($arrayfields['b.label']['checked'])) + if (!empty($arrayfields['b.label']['checked'])) { print ''.$objecttmp->label.''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Account type - if (! empty($arrayfields['accountype']['checked'])) + if (!empty($arrayfields['accountype']['checked'])) { print ''; print $objecttmp->type_lib[$objecttmp->type]; print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Number - if (! empty($arrayfields['b.number']['checked'])) + if (!empty($arrayfields['b.number']['checked'])) { print ''.$objecttmp->number.''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Account number - if (! empty($arrayfields['b.account_number']['checked'])) + if (!empty($arrayfields['b.account_number']['checked'])) { print ''; - if (! empty($conf->accounting->enabled) && ! empty($objecttmp->account_number)) + if (!empty($conf->accounting->enabled) && !empty($objecttmp->account_number)) { $accountingaccount = new AccountingAccount($db); $accountingaccount->fetch('', $objecttmp->account_number, 1); @@ -470,14 +494,14 @@ foreach ($accounts as $key=>$type) print $objecttmp->account_number; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Accountancy journal - if (! empty($arrayfields['b.fk_accountancy_journal']['checked'])) + if (!empty($arrayfields['b.fk_accountancy_journal']['checked'])) { print ''; - if (! empty($conf->accounting->enabled) && ! empty($objecttmp->fk_accountancy_journal)) + if (!empty($conf->accounting->enabled) && !empty($objecttmp->fk_accountancy_journal)) { $accountingjournal = new AccountingJournal($db); $accountingjournal->fetch($objecttmp->fk_accountancy_journal); @@ -523,47 +547,47 @@ foreach ($accounts as $key=>$type) print ''.$langs->trans("FeatureDisabled").''; } print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters, $objecttmp); // Note that $action and $objecttmpect may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objecttmp); // Note that $action and $objecttmpect may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['b.datec']['checked'])) + if (!empty($arrayfields['b.datec']['checked'])) { print ''; print dol_print_date($objecttmp->date_creation, 'dayhour'); print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Date modification - if (! empty($arrayfields['b.tms']['checked'])) + if (!empty($arrayfields['b.tms']['checked'])) { print ''; print dol_print_date($objecttmp->date_update, 'dayhour'); print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Status - if (! empty($arrayfields['b.clos']['checked'])) + if (!empty($arrayfields['b.clos']['checked'])) { print ''.$objecttmp->getLibStatut(5).''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Balance - if (! empty($arrayfields['balance']['checked'])) + if (!empty($arrayfields['balance']['checked'])) { print ''; print ''.price($solde, 0, $langs, 0, -1, -1, $objecttmp->currency_code).''; print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='balance'; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'balance'; $totalarray['val']['balance'] += $solde; } diff --git a/htdocs/compta/bank/releve.php b/htdocs/compta/bank/releve.php index 9ae1d5d7d83..0350895ca0d 100644 --- a/htdocs/compta/bank/releve.php +++ b/htdocs/compta/bank/releve.php @@ -49,7 +49,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php'; $langs->loadLangs(array("banks", "categories", "companies", "bills", "trips", "donations", "loan")); $action = GETPOST('action', 'alpha'); -$id = GETPOST('account', 'int'); +$id = GETPOST('account', 'int') ? GETPOST('account', 'int') : GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $dvid = GETPOST('dvid', 'alpha'); $numref = GETPOST('num', 'alpha'); @@ -80,7 +80,7 @@ if ($user->rights->banque->consolidate && $action == 'dvprev' && !empty($dvid)) $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $pageplusone = GETPOST("pageplusone", 'int'); if ($pageplusone) $page = $pageplusone - 1; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 diff --git a/htdocs/compta/bank/treso.php b/htdocs/compta/bank/treso.php index 7ca62b67ab8..b8d259cdc8d 100644 --- a/htdocs/compta/bank/treso.php +++ b/htdocs/compta/bank/treso.php @@ -39,18 +39,18 @@ $langs->loadLangs(array('banks', 'categories', 'bills', 'companies')); // Security check if (isset($_GET["account"]) || isset($_GET["ref"])) { - $id = isset($_GET["account"])?$_GET["account"]:(isset($_GET["ref"])?$_GET["ref"]:''); + $id = isset($_GET["account"]) ? $_GET["account"] : (isset($_GET["ref"]) ? $_GET["ref"] : ''); } -$fieldid = isset($_GET["ref"])?'ref':'rowid'; -if ($user->socid) $socid=$user->socid; -$result=restrictedArea($user, 'banque', $id, 'bank_account&bank_account', '', '', $fieldid); +$fieldid = isset($_GET["ref"]) ? 'ref' : 'rowid'; +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'banque', $id, 'bank_account&bank_account', '', '', $fieldid); -$vline=isset($_GET["vline"])?$_GET["vline"]:$_POST["vline"]; -$page=isset($_GET["page"])?$_GET["page"]:0; +$vline = isset($_GET["vline"]) ? $_GET["vline"] : $_POST["vline"]; +$page = isset($_GET["page"]) ? $_GET["page"] : 0; // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('banktreso','globalcard')); +$hookmanager->initHooks(array('banktreso', 'globalcard')); /* * View @@ -61,9 +61,9 @@ $helpurl = ""; llxHeader('', $title, $helpurl); $societestatic = new Societe($db); -$facturestatic=new Facture($db); -$facturefournstatic=new FactureFournisseur($db); -$socialcontribstatic=new ChargeSociales($db); +$facturestatic = new Facture($db); +$facturefournstatic = new FactureFournisseur($db); +$socialcontribstatic = new ChargeSociales($db); $form = new Form($db); @@ -81,17 +81,17 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) $object = new Account($db); if ($_GET["account"]) { - $result=$object->fetch($_GET["account"]); + $result = $object->fetch($_GET["account"]); } if ($_GET["ref"]) { - $result=$object->fetch(0, $_GET["ref"]); - $_GET["account"]=$object->id; + $result = $object->fetch(0, $_GET["ref"]); + $_GET["account"] = $object->id; } // Onglets - $head=bank_prepare_head($object); + $head = bank_prepare_head($object); dol_fiche_head($head, 'cash', $langs->trans("FinancialAccount"), 0, 'account'); $linkback = ''.$langs->trans("BackToList").''; @@ -103,7 +103,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) print '
    '; $solde = $object->solde(0); - if($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED)$colspan = 6; + if ($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED)$colspan = 6; else $colspan = 5; // Show next coming entries @@ -114,7 +114,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) print ''; print ''.$langs->trans("DateDue").''; print ''.$langs->trans("Description").''; - if($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED )print ''.$langs->trans("Entity").''; + if ($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED)print ''.$langs->trans("Entity").''; print ''.$langs->trans("ThirdParty").''; print ''.$langs->trans("Debit").''; print ''.$langs->trans("Credit").''; @@ -139,54 +139,54 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) // Customer invoices $sql = "SELECT 'invoice' as family, f.rowid as objid, f.ref as ref, f.total_ttc, f.type, f.date_lim_reglement as dlr,"; - $sql.= " s.rowid as socid, s.nom as name, s.fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; - $sql.= " WHERE f.entity IN (".getEntity('invoice').")"; - $sql.= " AND f.paye = 0 AND f.fk_statut = 1"; // Not paid - $sql.= " AND (f.fk_account IN (0, ".$object->id.") OR f.fk_account IS NULL)"; // Id bank account of invoice - $sql.= " ORDER BY dlr ASC"; + $sql .= " s.rowid as socid, s.nom as name, s.fournisseur"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').")"; + $sql .= " AND f.paye = 0 AND f.fk_statut = 1"; // Not paid + $sql .= " AND (f.fk_account IN (0, ".$object->id.") OR f.fk_account IS NULL)"; // Id bank account of invoice + $sql .= " ORDER BY dlr ASC"; $sqls[] = $sql; // Supplier invoices $sql = " SELECT 'invoice_supplier' as family, ff.rowid as objid, ff.ref as ref, ff.ref_supplier as ref_supplier, (-1*ff.total_ttc) as total_ttc, ff.type, ff.date_lim_reglement as dlr,"; - $sql.= " s.rowid as socid, s.nom as name, s.fournisseur"; - $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON ff.fk_soc = s.rowid"; - $sql.= " WHERE ff.entity = ".$conf->entity; - $sql.= " AND ff.paye = 0 AND fk_statut = 1"; // Not paid - $sql.= " AND (ff.fk_account IN (0, ".$object->id.") OR ff.fk_account IS NULL)"; // Id bank account of supplier invoice - $sql.= " ORDER BY dlr ASC"; + $sql .= " s.rowid as socid, s.nom as name, s.fournisseur"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON ff.fk_soc = s.rowid"; + $sql .= " WHERE ff.entity = ".$conf->entity; + $sql .= " AND ff.paye = 0 AND fk_statut = 1"; // Not paid + $sql .= " AND (ff.fk_account IN (0, ".$object->id.") OR ff.fk_account IS NULL)"; // Id bank account of supplier invoice + $sql .= " ORDER BY dlr ASC"; $sqls[] = $sql; // Social contributions $sql = " SELECT 'social_contribution' as family, cs.rowid as objid, cs.libelle as ref, (-1*cs.amount) as total_ttc, ccs.libelle as type, cs.date_ech as dlr"; - $sql.= ", cs.fk_account"; - $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as ccs ON cs.fk_type = ccs.id"; - $sql.= " WHERE cs.entity = ".$conf->entity; - $sql.= " AND cs.paye = 0"; // Not paid - $sql.= " AND (cs.fk_account IN (0, ".$object->id.") OR cs.fk_account IS NULL)"; // Id bank account of social contribution - $sql.= " ORDER BY dlr ASC"; + $sql .= ", cs.fk_account"; + $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as ccs ON cs.fk_type = ccs.id"; + $sql .= " WHERE cs.entity = ".$conf->entity; + $sql .= " AND cs.paye = 0"; // Not paid + $sql .= " AND (cs.fk_account IN (0, ".$object->id.") OR cs.fk_account IS NULL)"; // Id bank account of social contribution + $sql .= " ORDER BY dlr ASC"; $sqls[] = $sql; // others sql $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreSQL', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if(empty($reshook) and isset($hookmanager->resArray['sql'])){ + if (empty($reshook) and isset($hookmanager->resArray['sql'])) { $sqls[] = $hookmanager->resArray['sql']; } - $error=0; - $tab_sqlobjOrder=array(); - $tab_sqlobj=array(); + $error = 0; + $tab_sqlobjOrder = array(); + $tab_sqlobj = array(); - foreach($sqls as $sql){ + foreach ($sqls as $sql) { $resql = $db->query($sql); if ($resql) { while ($sqlobj = $db->fetch_object($resql)) { $tab_sqlobj[] = $sqlobj; - $tab_sqlobjOrder[]= $db->jdate($sqlobj->dlr); + $tab_sqlobjOrder[] = $db->jdate($sqlobj->dlr); } $db->free($resql); } else { @@ -195,13 +195,13 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) } // Sort array - if (! $error) + if (!$error) { array_multisort($tab_sqlobjOrder, $tab_sqlobj); // Apply distinct filter foreach ($tab_sqlobj as $key=>$value) { - $tab_sqlobj[$key] = "'" . serialize($value) . "'"; + $tab_sqlobj[$key] = "'".serialize($value)."'"; } $tab_sqlobj = array_unique($tab_sqlobj); foreach ($tab_sqlobj as $key=>$value) { @@ -221,52 +221,52 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) if ($obj->family == 'invoice_supplier') { - $showline=1; + $showline = 1; // Uncomment this line to avoid to count suppliers credit note (ff.type = 2) //$showline=(($obj->total_ttc < 0 && $obj->type != 2) || ($obj->total_ttc > 0 && $obj->type == 2)) if ($showline) { - $ref=$obj->ref; - $facturefournstatic->ref=$ref; - $facturefournstatic->id=$obj->objid; - $facturefournstatic->type=$obj->type; + $ref = $obj->ref; + $facturefournstatic->ref = $ref; + $facturefournstatic->id = $obj->objid; + $facturefournstatic->type = $obj->type; $ref = $facturefournstatic->getNomUrl(1, ''); $societestatic->id = $obj->socid; $societestatic->name = $obj->name; - $refcomp=$societestatic->getNomUrl(1, '', 24); + $refcomp = $societestatic->getNomUrl(1, '', 24); - $totalpayment = -1*$facturefournstatic->getSommePaiement(); // Payment already done + $totalpayment = -1 * $facturefournstatic->getSommePaiement(); // Payment already done } } if ($obj->family == 'invoice') { - $facturestatic->ref=$obj->ref; - $facturestatic->id=$obj->objid; - $facturestatic->type=$obj->type; + $facturestatic->ref = $obj->ref; + $facturestatic->id = $obj->objid; + $facturestatic->type = $obj->type; $ref = $facturestatic->getNomUrl(1, ''); $societestatic->id = $obj->socid; $societestatic->name = $obj->name; - $refcomp=$societestatic->getNomUrl(1, '', 24); + $refcomp = $societestatic->getNomUrl(1, '', 24); - $totalpayment = $facturestatic->getSommePaiement(); // Payment already done - $totalpayment+= $facturestatic->getSumDepositsUsed(); - $totalpayment+= $facturestatic->getSumCreditNotesUsed(); + $totalpayment = $facturestatic->getSommePaiement(); // Payment already done + $totalpayment += $facturestatic->getSumDepositsUsed(); + $totalpayment += $facturestatic->getSumCreditNotesUsed(); } if ($obj->family == 'social_contribution') { - $socialcontribstatic->ref=$obj->ref; - $socialcontribstatic->id=$obj->objid; - $socialcontribstatic->label=$obj->type; + $socialcontribstatic->ref = $obj->ref; + $socialcontribstatic->id = $obj->objid; + $socialcontribstatic->label = $obj->type; $ref = $socialcontribstatic->getNomUrl(1, 24); - $totalpayment = -1*$socialcontribstatic->getSommePaiement(); // Payment already done + $totalpayment = -1 * $socialcontribstatic->getSommePaiement(); // Payment already done } $parameters = array('obj' => $obj, 'ref' => $ref, 'refcomp' => $refcomp, 'totalpayment' => $totalpayment); $reshook = $hookmanager->executeHooks('moreFamily', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if(empty($reshook)){ + if (empty($reshook)) { $ref = isset($hookmanager->resArray['ref']) ? $hookmanager->resArray['ref'] : $ref; $refcomp = isset($hookmanager->resArray['refcomp']) ? $hookmanager->resArray['refcomp'] : $refcomp; $totalpayment = isset($hookmanager->resArray['totalpayment']) ? $hookmanager->resArray['totalpayment'] : $totalpayment; @@ -286,11 +286,14 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) else print $langs->trans("NotDefined"); print ""; print "".$ref.""; - if($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED ){ - if($obj->family == 'invoice'){ + if ($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED) { + if ($obj->family == 'invoice') { $mc->getInfo($obj->entity); print "".$mc->label.""; - }else print ""; + } + else { + print ""; + } } print "".$refcomp.""; if ($obj->total_ttc < 0) { print ''.price(abs($total_ttc))." "; }; @@ -310,7 +313,7 @@ if ($_REQUEST["account"] || $_REQUEST["ref"]) // Other lines $parameters = array('solde' => $solde); $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if(empty($reshook)){ + if (empty($reshook)) { print $hookmanager->resPrint; $solde = isset($hookmanager->resArray['solde']) ? $hookmanager->resArray['solde'] : $solde; } diff --git a/htdocs/compta/bank/various_payment/document.php b/htdocs/compta/bank/various_payment/document.php index 37ff26b0b4b..618cc6006a5 100644 --- a/htdocs/compta/bank/various_payment/document.php +++ b/htdocs/compta/bank/various_payment/document.php @@ -45,7 +45,7 @@ $result = restrictedArea($user, 'banque', '', '', ''); // Get parameters $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index b6cee9a29d0..e2aa6517417 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -56,7 +56,7 @@ if ($search_accountancy_subledger == - 1) $search_accountancy_subledger = ''; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/compta/cashcontrol/cashcontrol_card.php b/htdocs/compta/cashcontrol/cashcontrol_card.php index 8e83e6a33a4..57d81c625fe 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_card.php +++ b/htdocs/compta/cashcontrol/cashcontrol_card.php @@ -47,7 +47,7 @@ $sday = (GETPOSTISSET('closeday') ?GETPOST('closeday', 'int') : dol_print_date($ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -77,6 +77,9 @@ $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('cashcontrolcard', 'globalcard')); +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. + /* * Actions @@ -96,7 +99,22 @@ if (empty($conf->global->CASHDESK_ID_BANKACCOUNT_CASH) && empty($conf->global->C if (GETPOST('cancel', 'alpha')) { - $action = 'create'; + if ($action == 'valid') { + $action = 'view'; + } + else { + $action = 'create'; + } +} + +if ($action == "reopen") +{ + $result = $object->setStatut($object::STATUS_DRAFT, null, '', 'CASHFENCE_REOPEN'); + if ($result < 0) { + dol_print_error($db, $object->error, $object->error); + } + + $action = 'view'; } if ($action == "start") @@ -162,18 +180,35 @@ elseif ($action == "add") } } -if ($action == "close") +if ($action == "valid") // validate = close { $object->fetch($id); - $result = $object->valid($user); + $db->begin(); + + /* + $object->day_close = GETPOST('closeday', 'int'); + $object->month_close = GETPOST('closemonth', 'int'); + $object->year_close = GETPOST('closeyear', 'int'); + */ + + $object->cash = price2num(GETPOST('cash_amount', 'alpha')); + $object->card = price2num(GETPOST('card_amount', 'alpha')); + $object->cheque = price2num(GETPOST('cheque_amount', 'alpha')); + + $result = $object->update($user); + + $result = $object->valid($user); + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); } else { setEventMessages($langs->trans("CashFenceDone"), null); + $db->commit(); } $action = "view"; @@ -213,15 +248,22 @@ if ($action == 'confirm_delete' && !empty($permissiontodelete)) $form = new Form($db); -if ($action == "create" || $action == "start") +$initialbalanceforterminal = array(); +$theoricalamountforterminal = array(); +$theoricalnbofinvoiceforterminal = array(); + +if ($action == "create" || $action == "start" || $action == 'close') { - llxHeader(); + if ($action == 'close') { + $posmodule = $object->posmodule; + $terminalid = $object->posnumber; + $terminaltouse = $terminalid; - $initialbalanceforterminal = array(); - $theoricalamountforterminal = array(); - $theoricalnbofinvoiceforterminal = array(); - - if (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1') + $syear = $object->year_close; + $smonth = $object->month_close; + $sday = $object->day_close; + } + elseif (GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '' && GETPOST('posnumber', 'alpha') != '-1') { $posmodule = GETPOST('posmodule', 'alpha'); $terminalid = GETPOST('posnumber', 'alpha'); @@ -234,7 +276,10 @@ if ($action == "create" || $action == "start") setEventMessages($langs->trans("OnlyTerminal1IsAvailableForCashDeskModule"), null, 'errors'); $error++; } + } + if ($terminalid != '') + { // Calculate $initialbalanceforterminal for terminal 0 foreach ($arrayofpaymentmode as $key => $val) { @@ -246,9 +291,7 @@ if ($action == "create" || $action == "start") // Get the bank account dedicated to this point of sale module/terminal $vartouse = 'CASHDESK_ID_BANKACCOUNT_CASH'.$terminaltouse; - $bankid = $conf->global->$vartouse; // This value is ok for 'Terminal 0' for module 'CashDesk' and 'TakePos' (they manage only 1 terminal) - // Hook to get the good bank id according to posmodule and posnumber. - // @todo add hook here + $bankid = $conf->global->$vartouse; if ($bankid > 0) { @@ -274,11 +317,9 @@ if ($action == "create" || $action == "start") } } - // Calculate $theoricalamountforterminal for terminal 0 + // Calculate $theoricalamountforterminal foreach ($arrayofpaymentmode as $key => $val) { - /*$sql = "SELECT SUM(amount) as total FROM ".MAIN_DB_PREFIX."bank"; - $sql.= " WHERE fk_account = ".$bankid;*/ $sql = "SELECT SUM(pf.amount) as total, COUNT(*) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."paiement as p, ".MAIN_DB_PREFIX."c_paiement as cp"; $sql .= " WHERE pf.fk_facture = f.rowid AND p.rowid = pf.fk_paiement AND cp.id = p.fk_paiement"; @@ -315,197 +356,230 @@ if ($action == "create" || $action == "start") } } - print load_fiche_titre($langs->trans("CashControl")." - ".$langs->trans("New"), '', 'cash-register'); + //var_dump($theoricalamountforterminal); var_dump($theoricalnbofinvoiceforterminal); + if ($action != 'close') { + llxHeader(); - print '
    '; - print ''; - if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') - { - print ''; - } - else - { - print ''; - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print load_fiche_titre($langs->trans("CashControl")." - ".$langs->trans("New"), '', 'cash-register'); - $disabled = 0; - $prefix = 'close'; + print ''; + print ''; + if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') + { + print ''; + } + elseif ($action == 'close') + { + print ''; + print ''; + } + else + { + print ''; + } - print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; diff --git a/htdocs/compta/deplacement/list.php b/htdocs/compta/deplacement/list.php index e8e806bbbcd..ea2d68cc126 100644 --- a/htdocs/compta/deplacement/list.php +++ b/htdocs/compta/deplacement/list.php @@ -45,7 +45,7 @@ $search_company=GETPOST('search_company', 'alpha'); // $search_amount=GETPOST('search_amount','alpha'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $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; diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index c9c48fd9b93..cf745b784fc 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -227,7 +227,9 @@ print '
    '; // Show filter box print '
    '; +print ''; print ''; + print '
    '.$langs->trans("Module").''.$langs->trans("Terminal").''.$langs->trans("Year").''.$langs->trans("Month").''.$langs->trans("Day").'
    '.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable) > 1 ? 1 : 0)).''; + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; - $array = array(); - $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); - for($i = 1; $i <= $numterminals; $i++) { - $array[$i] = $i; - } - $selectedposnumber = 0; $showempty = 1; - if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') - { - $selectedposnumber = 1; $showempty = 0; - } - print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty); - //print ''; - print ''; - // Year - print ''; - // Month - print ''; - // Day - print ''; - // Button Start - print ''; - print '
    '.$langs->trans("Module").''.$langs->trans("Terminal").''.$langs->trans("Year").''.$langs->trans("Month").''.$langs->trans("Day").'
    '; - $retstring = ''; - for ($year = $syear - 10; $year < $syear + 10; $year++) - { - $retstring .= ''; - } - $retstring .= "\n"; - print $retstring; - print ''; - $retstring = ''; - $retstring .= ''; - for ($month = 1; $month <= 12; $month++) - { - $retstring .= '"; - } - $retstring .= ""; - print $retstring; - print ''; - $retstring = ''; - $retstring .= ''; - for ($day = 1; $day <= 31; $day++) - { - $retstring .= ''; - } - $retstring .= ""; - print $retstring; - print ''; - if ($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') - { - print ''; - } - else - { - print ''; - } - print '
    '; + $disabled = 0; + $prefix = 'close'; - // Table to see/enter balance - if ($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') - { - $posmodule = GETPOST('posmodule', 'alpha'); - $terminalid = GETPOST('posnumber', 'alpha'); + print '
    '.$form->selectarray('posmodule', $arrayofposavailable, GETPOST('posmodule', 'alpha'), (count($arrayofposavailable) > 1 ? 1 : 0)).''; - print '
    '; - - print ''; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - print ''; - print ''; - $i = 0; - foreach ($arrayofpaymentmode as $key => $val) + $array = array(); + $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); + for($i = 1; $i <= $numterminals; $i++) { + $array[$i] = $i; + } + $selectedposnumber = 0; $showempty = 1; + if ($conf->global->TAKEPOS_NUM_TERMINALS == '1') + { + $selectedposnumber = 1; $showempty = 0; + } + print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty); + //print ''; + print ''; + // Year + print ''; + // Month + print ''; + // Day + print ''; + // Button Start + print ''; + print '
    '.$langs->trans("InitialBankBalance"); - //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); - print '
    '; - print $langs->trans("AmountAtEndOfPeriod"); - print '
    '.$langs->trans("Cash"); - //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); - print '
    '; + $retstring = ''; + for ($year = $syear - 10; $year < $syear + 10; $year++) { - print ''.$langs->trans($val); + $retstring .= ''; + } + $retstring .= "\n"; + print $retstring; + print ''; + $retstring = ''; + $retstring .= ''; + for ($month = 1; $month <= 12; $month++) + { + $retstring .= '"; + } + $retstring .= ""; + print $retstring; + print ''; + $retstring = ''; + $retstring .= ''; + for ($day = 1; $day <= 31; $day++) + { + $retstring .= ''; + } + $retstring .= ""; + print $retstring; + print ''; + if ($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') + { + print ''; + } + else + { + print ''; + } + print '
    '; + print ''; + + // Table to see/enter balance + if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') + { + $posmodule = GETPOST('posmodule', 'alpha'); + $terminalid = GETPOST('posnumber', 'alpha'); + + print '
    '; + + print '
    '; + print ''; + + print ''; + print ''; + print ''; - $i++; - } - print ''; - print ''; - print ''; - // Initial amount - print ''; - print ''; - // Amount per payment type - $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { - print ''; - $i++; - } - // Save - print ''; - print ''; - - print ''; - // Initial amount - print ''; - print ''; - // Amount per payment type - $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { - print ''; - $i++; - } - // Save - print ''; - print ''; + */ + print ''; + print ''; - print ''; - print ''; - // Initial amount - print ''; - // Amount per payment type - $i = 0; - foreach ($arrayofpaymentmode as $key => $val) - { - print ''; + print ''; + print ''; - $i++; - } - // Save - print ''; - print ''; + /* + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + }*/ + print ''; + print ''; - print ''; + /*print ''; + // Initial amount + print ''; + print ''; + // Amount per payment type + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + } + // Save + print ''; + print ''; + */ + + print ''; + // Initial amount + print ''; + print ''; + // Amount per payment type + /*$i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + }*/ + // Save + print ''; + print ''; + + print ''; + print ''; + // Initial amount + print ''; + // Amount per payment type + /*$i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + }*/ + // Save + print ''; + print ''; + + print '
    '.$langs->trans("InitialBankBalance"); //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); print '
    '.$langs->trans("NbOfInvoices").''; - print ''; - print $theoricalnbofinvoiceforterminal[$terminalid][$key]; - print '
    '.$langs->trans("TheoricalAmount").''; - print price($initialbalanceforterminal[$terminalid]['cash']).'
    '; - print '
    '; - print price($theoricalamountforterminal[$terminalid][$key]).'
    '; + /* + print '
    '; + print $langs->trans("AmountAtEndOfPeriod"); print '
    '.$langs->trans("RealAmount").''; - print ''; - print ''; - print ''; + print '
    '.$langs->trans("Cash"); + //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); print '
    '; - print ''; - print ''; - print '
    '.$langs->trans($val); + //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); + print '
    '.$langs->trans("NbOfInvoices").''; + print ''; + print $theoricalnbofinvoiceforterminal[$terminalid][$key]; + print '
    '.$langs->trans("TheoricalAmount").''; + print price($initialbalanceforterminal[$terminalid]['cash']).'
    '; + print '
    '; + print price($theoricalamountforterminal[$terminalid][$key]).'
    '; + print '
    '.$langs->trans("RealAmount").''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($action == 'start') print ''; + elseif ($action == 'close') print ''; + print '
    '; + print '
    '; + } + + print ''; } - print ''; } -if (empty($action) || $action == "view") +if (empty($action) || $action == "view" || $action == "close") { $result = $object->fetch($id); @@ -520,7 +594,7 @@ if (empty($action) || $action == "view") $head[0][1] = $langs->trans("Card"); $head[0][2] = 'cashcontrol'; - dol_fiche_head($head, 'cashcontrol', $langs->trans("CashControl"), -1, 'cashcontrol'); + dol_fiche_head($head, 'cashcontrol', $langs->trans("CashControl"), -1, 'account'); $linkback = ''.$langs->trans("BackToList").''; @@ -533,7 +607,7 @@ if (empty($action) || $action == "view") print '
    '; print '
    '; print '
    '; - print ''; + print '
    '; print ''; print ''; @@ -293,7 +293,7 @@ if ($action == 'create') print ''; print ''; diff --git a/htdocs/compta/deplacement/document.php b/htdocs/compta/deplacement/document.php index 2829e257b3b..d85f4239d02 100644 --- a/htdocs/compta/deplacement/document.php +++ b/htdocs/compta/deplacement/document.php @@ -50,7 +50,7 @@ $result = restrictedArea($user, 'deplacement', $id, ''); // Get parameters $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/compta/deplacement/index.php b/htdocs/compta/deplacement/index.php index fde600aff8f..e95d7f95732 100644 --- a/htdocs/compta/deplacement/index.php +++ b/htdocs/compta/deplacement/index.php @@ -32,43 +32,43 @@ $langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid=$user->socid; +if ($user->socid) $socid = $user->socid; $result = restrictedArea($user, 'deplacement', '', ''); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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="DESC"; -if (! $sortfield) $sortfield="d.dated"; -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "d.dated"; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; /* * View */ -$tripandexpense_static=new Deplacement($db); +$tripandexpense_static = new Deplacement($db); $childids = $user->getAllChildIds(); -$childids[]=$user->id; +$childids[] = $user->id; //$help_url='EN:Module_Donations|FR:Module_Dons|ES:Módulo_Donaciones'; -$help_url=''; +$help_url = ''; llxHeader('', $langs->trans("ListOfFees"), $help_url); -$totalnb=0; +$totalnb = 0; $sql = "SELECT count(d.rowid) as nb, sum(d.km) as km, d.type"; -$sql.= " FROM ".MAIN_DB_PREFIX."deplacement as d"; -$sql.= " WHERE d.entity = ".$conf->entity; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql.=' AND d.fk_user IN ('.join(',', $childids).')'; -$sql.= " GROUP BY d.type"; -$sql.= " ORDER BY d.type"; +$sql .= " FROM ".MAIN_DB_PREFIX."deplacement as d"; +$sql .= " WHERE d.entity = ".$conf->entity; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +$sql .= " GROUP BY d.type"; +$sql .= " ORDER BY d.type"; $result = $db->query($sql); if ($result) @@ -102,10 +102,10 @@ print ''; print ''; print "\n"; -$listoftype=$tripandexpense_static->listOfTypes(); +$listoftype = $tripandexpense_static->listOfTypes(); foreach ($listoftype as $code => $label) { - $dataseries[]=array($label, (isset($nb[$code])?(int) $nb[$code]:0)); + $dataseries[] = array($label, (isset($nb[$code]) ? (int) $nb[$code] : 0)); } if ($conf->use_javascript_ajax) @@ -115,12 +115,12 @@ if ($conf->use_javascript_ajax) include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphstatus'); - print $dolgraph->show($totalnb?0:1); + print $dolgraph->show($totalnb ? 0 : 1); print ''; } @@ -137,25 +137,25 @@ print '
    '; print $langs->trans("Ref"); @@ -587,17 +661,212 @@ if (empty($action) || $action == "view") dol_fiche_end(); - print '
    '; - print ''; - if ($object->status == CashControl::STATUS_DRAFT) - { - print ''; + if ($action != 'close') { + print '
    '; - print ''; - } - print '
    '; + print ''; - print '
    '; + if ($object->status == CashControl::STATUS_DRAFT) + { + print ''; + + print ''; + } else { + print ''; + } + + print '
    '; + + print '
    '; + } else { + print '
    '; + print ''; + if ($action == 'start' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '' && GETPOST('posnumber', 'int') != '-1') + { + print ''; + } + elseif ($action == 'close') + { + print ''; + print ''; + } + else + { + print ''; + } + + /* + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $disabled = 1; + $prefix = 'close'; + + print ''; + print ''; + print ''; + print ''; + // Year + print ''; + // Month + print ''; + // Day + print ''; + + print ''; + print '
    '.$langs->trans("Module").''.$langs->trans("Terminal").''.$langs->trans("Year").''.$langs->trans("Month").''.$langs->trans("Day").'
    '.$form->selectarray('posmodulebis', $arrayofposavailable, $object->posmodule, (count($arrayofposavailable) > 1 ? 1 : 0), 0, 0, '', 0, 0, $disabled).''; + + $array = array(); + $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); + for($i = 1; $i <= $numterminals; $i++) { + $array[$i] = $i; + } + $selectedposnumber = $object->posnumber; $showempty = 1; + //print $form->selectarray('posnumber', $array, GETPOSTISSET('posnumber') ?GETPOST('posnumber', 'int') : $selectedposnumber, $showempty, 0, 0, '', 0, 0, $disabled); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
    '; + print '
    '; + */ + + // Table to see/enter balance + if (($action == 'start' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '' && GETPOST('posnumber') != '-1') || $action == 'close') + { + $posmodule = $object->posmodule; + $terminalid = $object->posnumber; + + print '
    '; + + print '
    '; + print ''; + + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + } + print ''; + print ''; + + print ''; + // Initial amount + print ''; + print ''; + // Amount per payment type + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + } + // Save + print ''; + print ''; + + print ''; + // Initial amount + print ''; + print ''; + // Amount per payment type + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + } + // Save + print ''; + print ''; + + print ''; + print ''; + // Initial amount + print ''; + // Amount per payment type + $i = 0; + foreach ($arrayofpaymentmode as $key => $val) + { + print ''; + $i++; + } + // Save + print ''; + print ''; + + print '
    '.$langs->trans("InitialBankBalance"); + //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); + print '
    '; + print $langs->trans("AmountAtEndOfPeriod"); + print '
    '.$langs->trans("Cash"); + //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); + print '
    '.$langs->trans($val); + //print '
    '.$langs->trans("TheoricalAmount").'
    '.$langs->trans("RealAmount"); + print '
    '.$langs->trans("NbOfInvoices").''; + print ''; + print $theoricalnbofinvoiceforterminal[$terminalid][$key]; + print '
    '.$langs->trans("TheoricalAmount").''; + print price($initialbalanceforterminal[$terminalid]['cash']).'
    '; + print '
    '; + if ($key == 'cash') { + $deltaforcash = ($object->opening - $initialbalanceforterminal[$terminalid]['cash']); + print price($theoricalamountforterminal[$terminalid][$key] + $deltaforcash).'
    '; + } else { + print price($theoricalamountforterminal[$terminalid][$key]).'
    '; + } + print '
    '.$langs->trans("RealAmount").''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($action == 'start') print ''; + elseif ($action == 'close') print ''; + print '
    '; + print '
    '; + } + + print '
    '; + } } } diff --git a/htdocs/compta/cashcontrol/cashcontrol_list.php b/htdocs/compta/cashcontrol/cashcontrol_list.php index 6c59276d600..d559fad2b30 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_list.php +++ b/htdocs/compta/cashcontrol/cashcontrol_list.php @@ -65,7 +65,7 @@ $id = GETPOST('id', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index 32f7533b6c3..f30410d187f 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -104,6 +104,7 @@ class CashControl extends CommonObject const STATUS_DRAFT = 0; const STATUS_VALIDATED = 1; + const STATUS_CLOSED = 1; // For the moment CLOSED = VALIDATED /** @@ -288,6 +289,18 @@ class CashControl extends CommonObject return $result; } + /** + * Update object into database + * + * @param User $user User that modifies + * @param bool $notrigger false=launch triggers after, true=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = false) + { + return $this->updateCommon($user, $notrigger); + } + /** * Delete object in database * diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index 8cd74f1cccf..1ea06eba9e9 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -40,6 +40,7 @@ $langs->load("bills"); $id = GETPOST('id', 'int'); $_GET['optioncss'] = "print"; + $cashcontrol = new CashControl($db); $cashcontrol->fetch($id); @@ -69,6 +70,8 @@ $terminalid = $cashcontrol->posnumber; * View */ +$param = ''; + llxHeader('', $langs->trans("CashControl"), '', '', 0, 0, array(), array(), $param); /*$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro as conciliated, b.num_releve, b.num_chq,"; @@ -268,21 +271,21 @@ if ($resql) print "

    "; print $langs->trans("Cash").": ".price($cash); - if ($cash != $cashcontrol->cash) { + if ($cashcontrol->status == $cashcontrol::STATUS_VALIDATED && $cash != $cashcontrol->cash) { print ' <> '.$langs->trans("Declared").': '.price($cashcontrol->cash).''; } print "

    "; //print '
    '; print $langs->trans("PaymentTypeCHQ").": ".price($cheque); - if ($cheque != $cashcontrol->cheque) { + if ($cashcontrol->status == $cashcontrol::STATUS_VALIDATED && $cheque != $cashcontrol->cheque) { print ' <> '.$langs->trans("Declared").': '.price($cashcontrol->cheque).''; } print "

    "; //print '
    '; print $langs->trans("PaymentTypeCB").": ".price($bank); - if ($bank != $cashcontrol->card) { + if ($cashcontrol->status == $cashcontrol::STATUS_VALIDATED && $bank != $cashcontrol->card) { print ' <> '.$langs->trans("Declared").': '.price($cashcontrol->card).''; } print "

    "; diff --git a/htdocs/compta/charges/index.php b/htdocs/compta/charges/index.php index 653a13f01a1..e9aa35d80b3 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -58,7 +58,7 @@ $search_account = GETPOST('search_account', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/clients.php b/htdocs/compta/clients.php index 8cfeeda613e..b9db96a78bc 100644 --- a/htdocs/compta/clients.php +++ b/htdocs/compta/clients.php @@ -46,7 +46,7 @@ $mode=GETPOST("mode"); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index cabc3510ea4..c08be32242b 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -281,7 +281,7 @@ if ($action == 'create') print '

    '.$langs->trans('NotePublic').''; - $doleditor = new DolEditor('note_public', GETPOST('note_public', 'alpha'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); print $doleditor->Create(1); print '
    '.$langs->trans('NotePrivate').''; - $doleditor = new DolEditor('note_private', GETPOST('note_private', 'alpha'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); print $doleditor->Create(1); print '
    '.$langs->trans("Statistics").'
    '; print '
    '; -$max=10; +$max = 10; $langs->load("boxes"); $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, d.rowid, d.dated as date, d.tms as dm, d.km, d.fk_statut"; -$sql.= " FROM ".MAIN_DB_PREFIX."deplacement as d, ".MAIN_DB_PREFIX."user as u"; -if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -$sql.= " WHERE u.rowid = d.fk_user"; -$sql.= " AND d.entity = ".$conf->entity; -if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql.=' AND d.fk_user IN ('.join(',', $childids).')'; -if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND d.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -if ($socid) $sql.= " AND d.fk_soc = ".$socid; -$sql.= $db->order("d.tms", "DESC"); -$sql.= $db->plimit($max, 0); +$sql .= " FROM ".MAIN_DB_PREFIX."deplacement as d, ".MAIN_DB_PREFIX."user as u"; +if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +$sql .= " WHERE u.rowid = d.fk_user"; +$sql .= " AND d.entity = ".$conf->entity; +if (empty($user->rights->deplacement->readall) && empty($user->rights->deplacement->lire_tous)) $sql .= ' AND d.fk_user IN ('.join(',', $childids).')'; +if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND d.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) $sql .= " AND d.fk_soc = ".$socid; +$sql .= $db->order("d.tms", "DESC"); +$sql .= $db->plimit($max, 0); $result = $db->query($sql); if ($result) { - $var=false; + $var = false; $num = $db->num_rows($result); $i = 0; @@ -171,16 +171,16 @@ if ($result) { $total_ttc = $totalam = $total = 0; - $deplacementstatic=new Deplacement($db); - $userstatic=new User($db); + $deplacementstatic = new Deplacement($db); + $userstatic = new User($db); while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); - $deplacementstatic->ref=$obj->rowid; - $deplacementstatic->id=$obj->rowid; - $userstatic->id=$obj->uid; - $userstatic->lastname=$obj->lastname; - $userstatic->firstname=$obj->firstname; + $deplacementstatic->ref = $obj->rowid; + $deplacementstatic->id = $obj->rowid; + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; print '
    '.$deplacementstatic->getNomUrl(1).''.$userstatic->getNomUrl(1).'
    '; print ''; // Company diff --git a/htdocs/compta/facture/card-rec.php b/htdocs/compta/facture/card-rec.php index 7d1f529bf82..dd295fa3112 100644 --- a/htdocs/compta/facture/card-rec.php +++ b/htdocs/compta/facture/card-rec.php @@ -70,7 +70,7 @@ $month_date_when = GETPOST('month_date_when'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; if (!$sortorder) $sortorder = 'DESC'; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 3e59b92a146..868ccc006d8 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -101,6 +101,9 @@ $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global- $object = new Facture($db); $extrafields = new ExtraFields($db); +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + // Load object if ($id > 0 || !empty($ref)) { if ($action != 'add') { @@ -293,31 +296,32 @@ if (empty($reshook)) // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must // do it again in validation to avoid cases where invoice is created from another object that allow negative lines. - // Note that we can accept the negative line if sum with other lines with same vat is positivie: Because all the lines will be merged together + // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together // when converted into 'available credit' and we will get a positive available credit line. // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only). - $array_of_pu_ht_per_vat_rate = array(); - $array_of_pu_ht_devise_per_vat_rate = array(); + $array_of_total_ht_per_vat_rate = array(); + $array_of_total_ht_devise_per_vat_rate = array(); foreach ($object->lines as $line) { - if (empty($array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0; - if (empty($array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0; - $array_of_pu_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->subprice; - $array_of_pu_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->multicurrency_subprice; + if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0; + if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code])) $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] = 0; + $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->total_ht; + $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$line->vat_src_code] += $line->multicurrency_total_ht; } - //var_dump($array_of_pu_ht_per_vat_rate);exit; - foreach ($array_of_pu_ht_per_vat_rate as $vatrate => $tmpvalue) - { - $pu_ht = $array_of_pu_ht_per_vat_rate[$vatrate]; - $pu_ht_devise = $array_of_pu_ht_devise_per_vat_rate[$vatrate]; - if (($pu_ht < 0 || $pu_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) + //var_dump($array_of_total_ht_per_vat_rate);exit; + foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) + { + $tmp_total_ht = $array_of_total_ht_per_vat_rate[$vatrate]; + $tmp_total_ht_devise = $array_of_total_ht_devise_per_vat_rate[$vatrate]; + + if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) { $langs->load("errors"); if ($object->type == $object::TYPE_DEPOSIT) { // Using negative lines on deposit lead to headach and blocking problems when you want to consume them. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors'); } else { - setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors'); + setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate"), null, 'errors'); } $error++; $action = ''; @@ -793,7 +797,7 @@ if (empty($reshook)) $canconvert = 0; if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) if ($canconvert) { $db->begin(); @@ -1519,7 +1523,7 @@ if (empty($reshook)) // If we create a deposit with all lines and a percent, we change amount if ($_POST['type'] == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') { if (is_array($lines)) { - foreach($lines as $line) { + foreach ($lines as $line) { // We keep ->subprice and ->pa_ht, but we change the qty $line->qty = price2num($line->qty * $valuedeposit / 100, 'MS'); } @@ -1709,7 +1713,17 @@ if (empty($reshook)) $object->fk_facture_source = $_POST['situations']; $object->type = Facture::TYPE_SITUATION; - if (!empty($origin) && !empty($originid)) + + $object->retained_warranty = GETPOST('retained_warranty', 'int'); + $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int'); + + $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit'); + if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) { + $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit); + } + $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement); + + if (!empty($origin) && !empty($originid)) { $object->origin = $origin; $object->origin_id = $originid; @@ -2551,7 +2565,12 @@ if (empty($reshook)) $pa_ht = $originLine->pa_ht; $label = $originLine->label; $array_options = $originLine->array_options; - $situation_percent = 100; + if($object->type == Facture::TYPE_SITUATION){ + $situation_percent = 0; + } + else{ + $situation_percent = 100; + } $fk_prev_id = ''; $fk_unit = $originLine->fk_unit; $pu_ht_devise = $originLine->multicurrency_subprice; @@ -3031,7 +3050,7 @@ if ($action == 'create') // First situation invoice print '
    '; $tmp = ' '; - $tmp = $tmp.''; + $tmp = $tmp.''; $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3); print $desc; print '
    '; @@ -3318,14 +3337,28 @@ if ($action == 'create') } $retained_warranty = GETPOST('retained_warranty', 'int'); - $retained_warranty = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT; + if(empty($retained_warranty)){ + if(!empty($objectsrc->retained_warranty)){ // use previous situation value + $retained_warranty = $objectsrc->retained_warranty; + }else{ + $retained_warranty = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT; + } + } + print ''; @@ -3351,8 +3384,8 @@ if ($action == 'create') print ''; // Bank Account - if (isset($_POST['fk_account'])) { - $fk_account = $_POST['fk_account']; + if (GETPOSTISSET('fk_account')) { + $fk_account = GETPOST('fk_account'); } print ''; print ''; print ''; - print ''; + print ''; print ''; } } @@ -5093,9 +5126,9 @@ elseif ($id > 0 || !empty($ref)) } // Reverse back money or convert to reduction - if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_STANDARD) { + if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) { // For credit note only - if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercanissuepayment) + if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) { if ($resteapayer == 0) { @@ -5108,12 +5141,12 @@ elseif ($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 && $usercancreate && empty($discount->id)) + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) { print ''.$langs->trans('ConvertExcessReceivedToReduc').''; } // For credit note - if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercancreate + if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0) ) { print ''.$langs->trans('ConvertToReduc').''; @@ -5126,7 +5159,7 @@ elseif ($id > 0 || !empty($ref)) } // Classify paid - if (($object->statut == 1 && $object->paye == 0 && $usercanissuepayment && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0))) + if (($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0))) || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $usercanissuepayment && empty($discount->id)) ) { @@ -5135,7 +5168,7 @@ elseif ($id > 0 || !empty($ref)) // Classify 'closed not completely paid' (possible si validee et pas encore classee payee) - if ($object->statut == 1 && $object->paye == 0 && $resteapayer > 0 && $usercanissuepayment) + if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && $usercanissuepayment) { if ($totalpaye > 0 || $totalcreditnotes > 0) { diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 7c7437bfb8e..961d07eda2e 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -1,5 +1,6 @@ +/* Copyright (C) 2020 Thibault FOUCART * * 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 @@ -63,11 +64,65 @@ class Invoices extends DolibarrApi */ public function get($id, $contact_list = 1) { + return $this->_fetch($id, '', '', $contact_list); + } + + /** + * Get properties of an invoice object by ref + * + * Return an array with invoice informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } + + /** + * Get properties of an invoice object by ref_ext + * + * Return an array with invoice informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } + + /** + * Get properties of an invoice object + * + * Return an array with invoice informations + * + * @param int $id ID of order + * @param string $ref Ref of object + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { if (!DolibarrApiAccess::$user->rights->facture->lire) { throw new RestException(401); } - $result = $this->invoice->fetch($id); + $result = $this->invoice->fetch($id, $ref, $ref_ext); if (!$result) { throw new RestException(404, 'Invoice not found'); } @@ -87,7 +142,7 @@ class Invoices extends DolibarrApi $this->invoice->fetchObjectLinked(); return $this->_cleanObjectDatas($this->invoice); - } + } /** * List invoices @@ -103,7 +158,8 @@ class Invoices extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @return array Array of invoice objects * - * @throws RestException + * @throws RestException 404 Not found + * @throws RestException 503 Error */ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $status = '', $sqlfilters = '') { @@ -242,10 +298,10 @@ class Invoices extends DolibarrApi * @url POST /createfromorder/{orderid} * * @return int - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function createInvoiceFromOrder($orderid) { @@ -318,10 +374,9 @@ class Invoices extends DolibarrApi * * @return array * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 Invoice not found */ public function putLine($id, $lineid, $request_data = null) { @@ -383,8 +438,9 @@ class Invoices extends DolibarrApi * @url POST {id}/contact/{contactid}/{type} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function postContact($id, $contactid, $type) { @@ -424,9 +480,10 @@ class Invoices extends DolibarrApi * @url DELETE {id}/contact/{rowid} * * @return array - * @throws 401 - * @throws 404 - * @throws 500 + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function deleteContact($id, $rowid) { @@ -463,10 +520,10 @@ class Invoices extends DolibarrApi * * @return array * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function deleteLine($id, $lineid) { @@ -591,10 +648,10 @@ class Invoices extends DolibarrApi * * @return int * - * @throws 200 - * @throws 401 - * @throws 404 - * @throws 400 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 400 */ public function postLine($id, $request_data = null) { @@ -673,11 +730,10 @@ class Invoices extends DolibarrApi * * @return array * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * */ public function addContact($id, $fk_socpeople, $type_contact, $source, $notrigger = 0) @@ -723,11 +779,10 @@ class Invoices extends DolibarrApi * * @return array * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 * */ public function settodraft($id, $idwarehouse = -1) @@ -827,11 +882,10 @@ class Invoices extends DolibarrApi * * @return array An invoice object * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function settopaid($id, $close_code = '', $close_note = '') { @@ -878,11 +932,10 @@ class Invoices extends DolibarrApi * * @return array An invoice object * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function settounpaid($id) { @@ -927,11 +980,10 @@ class Invoices extends DolibarrApi * * @return array An invoice object * - * @throws 200 - * @throws 304 - * @throws 401 - * @throws 404 - * @throws 500 + * @throws RestException 304 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 */ public function markAsCreditAvailable($id) { @@ -1103,10 +1155,11 @@ class Invoices extends DolibarrApi * @url POST {id}/usediscount/{discountid} * * @return int - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function useDiscount($id, $discountid) { @@ -1149,10 +1202,11 @@ class Invoices extends DolibarrApi * @url POST {id}/usecreditnote/{discountid} * * @return int - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function useCreditNote($id, $discountid) { @@ -1194,10 +1248,11 @@ class Invoices extends DolibarrApi * @url GET {id}/payments * * @return array - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function getPayments($id) { @@ -1243,9 +1298,10 @@ class Invoices extends DolibarrApi * @url POST {id}/payments * * @return int Payment ID - * @throws 400 - * @throws 401 - * @throws 404 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 */ public function addPayment($id, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') { @@ -1362,10 +1418,11 @@ class Invoices extends DolibarrApi * @url POST /paymentsdistributed * * @return int Payment ID - * @throws 400 - * @throws 401 - * @throws 403 - * @throws 404 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ public function addPaymentDistributed($arrayofamounts, $datepaye, $paiementid, $closepaidinvoices, $accountid, $num_paiement = '', $comment = '', $chqemetteur = '', $chqbank = '') { diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 0cc72fdcdcc..4658af376f1 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -112,7 +112,13 @@ class Facture extends CommonInvoice public $date; // Date invoice public $datem; public $ref_client; - public $ref_int; + + /** + * @var int Ref Int + * @deprecated + */ + public $ref_int; // deprecated + //Check constants for types public $type = self::TYPE_STANDARD; @@ -250,15 +256,15 @@ class Facture extends CommonInvoice /** * @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( + public $fields = array( 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>15), 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1), 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>25), - 'ref_int' =>array('type'=>'varchar(255)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>30), + 'ref_int' =>array('type'=>'varchar(255)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>30), // deprecated 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35), 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'Ref client', 'enabled'=>1, 'visible'=>-1, 'position'=>40), - 'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45), + //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45), 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>50), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>55), 'datef' =>array('type'=>'date', 'label'=>'DateInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>60), @@ -267,18 +273,17 @@ class Facture extends CommonInvoice 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>75), 'paye' =>array('type'=>'smallint(6)', 'label'=>'InvoicePaidCompletely', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80), //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85), - 'remise_percent' =>array('type'=>'double', 'label'=>'Remise percent', 'enabled'=>1, 'visible'=>-1, 'position'=>90), - 'remise_absolue' =>array('type'=>'double', 'label'=>'Remise absolue', 'enabled'=>1, 'visible'=>-1, 'position'=>95), - 'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100), + 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90), + 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>95), + //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100), 'close_code' =>array('type'=>'varchar(16)', 'label'=>'EarlyClosingReason', 'enabled'=>1, 'visible'=>-1, 'position'=>105), 'close_note' =>array('type'=>'varchar(128)', 'label'=>'EarlyClosingComment', 'enabled'=>1, 'visible'=>-1, 'position'=>110), 'tva' =>array('type'=>'double(24,8)', 'label'=>'TotalVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>115, 'isameasure'=>1), - 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1), - 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), + 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LT1', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1), + 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LT2', 'enabled'=>1, 'visible'=>-1, 'position'=>125, 'isameasure'=>1), 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>130, 'isameasure'=>1), 'total' =>array('type'=>'double(24,8)', 'label'=>'TotalHT', 'enabled'=>1, 'visible'=>-1, 'position'=>135, 'isameasure'=>1), 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'TotalTTC', 'enabled'=>1, 'visible'=>-1, 'position'=>140, 'isameasure'=>1), - 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Paid', 3=>'Abandonned')), 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>150), 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>155), 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>160), @@ -300,20 +305,21 @@ class Facture extends CommonInvoice 'retained_warranty' =>array('type'=>'double', 'label'=>'Retained warranty', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>245), 'retained_warranty_date_limit' =>array('type'=>'date', 'label'=>'Retained warranty date limit', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>250), 'retained_warranty_fk_cond_reglement' =>array('type'=>'integer', 'label'=>'Retained warranty fk cond reglement', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>255), - 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermsCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260), - 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermsLocation', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265), + 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260), + 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265), 'date_pointoftax' =>array('type'=>'date', 'label'=>'DatePointOfTax', 'enabled'=>'$conf->global->INVOICE_POINTOFTAX_DATE', 'visible'=>-1, 'position'=>270), 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>275), - 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCode', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>280), - 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>285), - 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>290), - 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>295), - 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>300), + 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'MulticurrencyCurrency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>280), + 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>285, 'isameasure'=>1), + 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>290, 'isameasure'=>1), + 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>295, 'isameasure'=>1), + 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>300, 'isameasure'=>1), 'fk_fac_rec_source' =>array('type'=>'integer', 'label'=>'RecurringInvoiceSource', 'enabled'=>1, 'visible'=>-1, 'position'=>305), - 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>310), + 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>310), 'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>315), 'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>320), - 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>220), + 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Paid', 3=>'Abandonned')), + 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900), ); // END MODULEBUILDER PROPERTIES @@ -477,7 +483,7 @@ class Facture extends CommonInvoice $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', 'alpha') ? GETPOST('model', 'apha') : $_facrec->modelpdf; + $this->modelpdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_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; @@ -807,6 +813,14 @@ class Facture extends CommonInvoice $vatrate = $line->tva_tx; if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if(!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { + $originid=$line->origin_id; + $origintype=$line->origin; + } else { + $originid=$line->id; + $origintype=$this->element; + } + $result = $this->addline( $line->desc, $line->subprice, @@ -826,8 +840,8 @@ class Facture extends CommonInvoice $line->product_type, $line->rang, $line->special_code, - $this->element, - $line->id, + $origintype, + $originid, $fk_parent_line, $line->fk_fournprice, $line->pa_ht, @@ -1053,6 +1067,11 @@ class Facture extends CommonInvoice $facture->situation_cycle_ref = $this->situation_cycle_ref; $facture->situation_final = $this->situation_final; + $facture->retained_warranty = $this->retained_warranty; + $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement; + $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit; + + // Loop on each line of new invoice foreach ($facture->lines as $i => $tmpline) { @@ -1253,6 +1272,14 @@ class Facture extends CommonInvoice $line->date_start = $object->lines[$i]->date_start; $line->date_end = $object->lines[$i]->date_end; + // Multicurrency + $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency; + $line->multicurrency_code = $object->lines[$i]->multicurrency_code; + $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice; + $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht; + $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva; + $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc; + $line->fk_fournprice = $object->lines[$i]->fk_fournprice; $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht); $line->pa_ht = $marginInfos[0]; @@ -1267,6 +1294,7 @@ class Facture extends CommonInvoice $this->socid = $object->socid; $this->fk_project = $object->fk_project; + $this->fk_account = $object->fk_account; $this->cond_reglement_id = $object->cond_reglement_id; $this->mode_reglement_id = $object->mode_reglement_id; $this->availability_id = $object->availability_id; @@ -1388,6 +1416,9 @@ class Facture extends CommonInvoice if (!empty($this->total_ttc)) $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($moretitle) $label .= ' - '.$moretitle; + if (isset($this->statut) && isset($this->alreadypaid)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5, $this->alreadypaid); + } } $linkclose = ($target ? ' target="'.$target.'"' : ''); @@ -1438,18 +1469,18 @@ class Facture extends CommonInvoice /** * Get object from database. Get also lines. * - * @param int $rowid Id of object to load - * @param string $ref Reference of invoice - * @param string $ref_ext External reference of invoice - * @param int $ref_int Internal reference of other object + * @param int $rowid Id of object to load + * @param string $ref Reference of invoice + * @param string $ref_ext External reference of invoice + * @param int $notused Not used * @param bool $fetch_situation Fetch the previous and next situation in $tab_previous_situation_invoice and $tab_next_situation_invoice - * @return int >0 if OK, <0 if KO, 0 if not found + * @return int >0 if OK, <0 if KO, 0 if not found */ - public function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $fetch_situation = false) + public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false) { global $conf; - if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1; + if (empty($rowid) && empty($ref) && empty($ref_ext)) return -1; $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc'; $sql .= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp'; @@ -1481,7 +1512,7 @@ class Facture extends CommonInvoice $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Dont't use entity if you use rowid if ($ref) $sql .= " AND f.ref='".$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)."'"; + if ($notused) $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -1514,15 +1545,15 @@ class Facture extends CommonInvoice $this->total_localtax2 = $obj->localtax2; $this->total_ttc = $obj->total_ttc; $this->revenuestamp = $obj->revenuestamp; - $this->paye = $obj->paye; + $this->paye = $obj->paye; $this->close_code = $obj->close_code; $this->close_note = $obj->close_note; $this->socid = $obj->fk_soc; - $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty + $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty $this->fk_project = $obj->fk_project; - $this->project = null; // Clear if another value was already set by fetch_projet + $this->project = null; // Clear if another value was already set by fetch_projet $this->statut = $obj->fk_statut; $this->date_lim_reglement = $this->db->jdate($obj->dlr); @@ -2225,10 +2256,10 @@ class Facture extends CommonInvoice // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Tag la facture comme paye completement (si close_code non renseigne) => this->fk_statut=2, this->paye=1 - * ou partiellement (si close_code renseigne) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0 + * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1 + * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0 * - * @param User $user Objet utilisateur qui modifie + * @param User $user Object user that modify * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple) * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple) * @return int <0 if KO, >0 if OK @@ -2410,12 +2441,23 @@ class Facture extends CommonInvoice * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * @param int $batch_rule [=0] 0 not decrement batch, else batch rule to use + * 1=take in batches ordered by sellby and eatby dates * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK */ - public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0) + public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0) { global $conf, $langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + $productStatic = null; + $warehouseStatic = null; + if ($batch_rule > 0) { + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; + $productStatic = new Product($this->db); + $warehouseStatic = new Entrepot($this->db); + } $now = dol_now(); @@ -2507,7 +2549,7 @@ class Facture extends CommonInvoice { $num = $this->ref; } - $this->newref = $num; + $this->newref = dol_sanitizeFileName($num); if ($num) { @@ -2557,11 +2599,94 @@ class Facture extends CommonInvoice $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrease stock for product - if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num)); - else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num)); - if ($result < 0) { - $error++; - $this->error = $mouvP->error; + if ($this->type == self::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num)); + if ($result < 0) { + $error++; + $this->error = $mouvP->error; + } + } else { + $is_batch_line = false; + if ($batch_rule > 0) { + $productStatic->fetch($this->lines[$i]->fk_product); + if ($productStatic->hasbatch()) { + $is_batch_line = true; + $product_qty_remain = $this->lines[$i]->qty; + + $sortfield = null; + $sortorder = null; + // find all batch order by sellby (DLC) and eatby dates (DLUO) first + if ($batch_rule == Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST) { + $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid'; + $sortorder = 'ASC,ASC,ASC,ASC'; + } + + $resBatchList = Productbatch::findAllForProduct($this->db, $productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder); + if (!is_array($resBatchList)) { + $error++; + $this->error = $this->db->lasterror(); + } + + if (!$error) { + $batchList = $resBatchList; + if (empty($batchList)) { + $error++; + $langs->load('errors'); + $warehouseStatic->fetch($idwarehouse); + $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref); + dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR); + } + + foreach ($batchList as $batch) { + if ($batch->qty <= 0) continue; // try to decrement only batches have positive quantity first + + // enough quantity in this batch + if ($batch->qty >= $product_qty_remain) { + $product_batch_qty = $product_qty_remain; + } // not enough (take all in batch) + else { + $product_batch_qty = $batch->qty; + } + $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch); + if ($result < 0) { + $error++; + $this->error = $mouvP->error; + break; + } + + $product_qty_remain -= $product_batch_qty; + // all product quantity was decremented + if ($product_qty_remain <= 0) break; + } + + if (!$error && $product_qty_remain > 0) { + if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) { + // take in the first batch + $batch = $batchList[0]; + $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch); + if ($result < 0) { + $error++; + $this->error = $mouvP->error; + } + } else { + $error++; + $langs->load('errors'); + $warehouseStatic->fetch($idwarehouse); + $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref); + dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR); + } + } + } + } + } + + if (!$is_batch_line) { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num)); + if ($result < 0) { + $error++; + $this->error = $mouvP->error; + } + } } } } @@ -2830,8 +2955,8 @@ class Facture extends CommonInvoice * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. * @param int $rang Position of line * @param int $special_code Special code (also used by externals modules!) - * @param string $origin 'order', ... - * @param int $origin_id Id of origin object + * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'.... + * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id * @param int $fk_parent_line Id of parent line * @param int $fk_fournprice Supplier price id (to calculate margin) or '' * @param int $pa_ht Buying price of line (to calculate margin) or '' @@ -3579,63 +3704,76 @@ class Facture extends CommonInvoice public function getNextNumRef($soc, $mode = 'next') { global $conf, $langs; - $langs->load("bills"); - // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON = 'mod_facture_terre'; - elseif ($conf->global->FACTURE_ADDON == 'terre') $conf->global->FACTURE_ADDON = 'mod_facture_terre'; - elseif ($conf->global->FACTURE_ADDON == 'mercure') $conf->global->FACTURE_ADDON = 'mod_facture_mercure'; + if ($this->module_source == 'takepos') { + $langs->load('cashdesk@cashdesk'); - if (!empty($conf->global->FACTURE_ADDON)) - { - dol_syslog("Call getNextNumRef with FACTURE_ADDON = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->nom.", type=".$soc->typent_code, LOG_DEBUG); + $moduleName = 'takepos'; + $moduleSourceName = 'Takepos'; + $addonConstName = 'TAKEPOS_REF_ADDON'; + + // Clean parameters (if not defined or using deprecated value) + if (empty($conf->global->TAKEPOS_REF_ADDON)) $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple'; + + $addon = $conf->global->TAKEPOS_REF_ADDON; + } else { + $langs->load('bills'); + + $moduleName = 'facture'; + $moduleSourceName = 'Invoice'; + $addonConstName = 'FACTURE_ADDON'; + + // Clean parameters (if not defined or using deprecated value) + if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON = 'mod_facture_terre'; + elseif ($conf->global->FACTURE_ADDON == 'terre') $conf->global->FACTURE_ADDON = 'mod_facture_terre'; + elseif ($conf->global->FACTURE_ADDON == 'mercure') $conf->global->FACTURE_ADDON = 'mod_facture_mercure'; + + $addon = $conf->global->FACTURE_ADDON; + } + + if (!empty($addon)) { + dol_syslog("Call getNextNumRef with " . $addonConstName . " = " . $conf->global->FACTURE_ADDON . ", thirdparty=" . $soc->nom . ", type=" . $soc->typent_code, LOG_DEBUG); $mybool = false; - $file = $conf->global->FACTURE_ADDON.".php"; - $classname = $conf->global->FACTURE_ADDON; + $file = $addon . '.php'; + $classname = $addon; // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) { - $dir = dol_buildpath($reldir."core/modules/facture/"); + $dir = dol_buildpath($reldir . 'core/modules/' . $moduleName . '/'); // Load file with numbering class (if found) - if (is_file($dir.$file) && is_readable($dir.$file)) - { - $mybool |= include_once $dir.$file; - } - } - - // For compatibility - if (!$mybool) - { - $file = $conf->global->FACTURE_ADDON."/".$conf->global->FACTURE_ADDON.".modules.php"; - $classname = "mod_facture_".$conf->global->FACTURE_ADDON; - $classname = preg_replace('/\-.*$/', '', $classname); - // Include file with class - foreach ($conf->file->dol_document_root as $dirroot) - { - $dir = $dirroot."/core/modules/facture/"; - - // Load file with numbering class (if found) - if (is_file($dir.$file) && is_readable($dir.$file)) { - $mybool |= include_once $dir.$file; - } + if (is_file($dir . $file) && is_readable($dir . $file)) { + $mybool |= include_once $dir . $file; } } - if (!$mybool) - { - dol_print_error('', "Failed to include file ".$file); + // For compatibility + if (!$mybool) { + $file = $addon . '/' . $addon . '.modules.php'; + $classname = 'mod_' . $moduleName . '_' . $addon; + $classname = preg_replace('/\-.*$/', '', $classname); + // Include file with class + foreach ($conf->file->dol_document_root as $dirroot) { + $dir = $dirroot . '/core/modules/' . $moduleName . '/'; + + // Load file with numbering class (if found) + if (is_file($dir . $file) && is_readable($dir . $file)) { + $mybool |= include_once $dir . $file; + } + } + } + + if (!$mybool) { + dol_print_error('', 'Failed to include file ' . $file); return ''; } $obj = new $classname(); - $numref = ""; $numref = $obj->getNextValue($soc, $this, $mode); /** @@ -3644,17 +3782,14 @@ class Facture extends CommonInvoice */ if ($mode != 'last' && !$numref) { $this->error = $obj->error; - //dol_print_error($this->db,"Facture::getNextNumRef ".$obj->error); - return ""; + return ''; } return $numref; - } - else - { - $langs->load("errors"); - print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Invoice")); - return ""; + } else { + $langs->load('errors'); + print $langs->trans('Error') . ' ' . $langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName)); + return ''; } } @@ -4104,7 +4239,7 @@ class Facture extends CommonInvoice if ($generic_facture->hasDelay()) { $response->nbtodolate++; - $response->url_late=DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills'; + $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills'; } } @@ -4580,15 +4715,40 @@ class Facture extends CommonInvoice // Paid invoices have status STATUS_CLOSED if ($this->statut != Facture::STATUS_VALIDATED) return false; - return $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); + $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); + if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) + { + $totalpaye = $this->getSommePaiement(); + $totalpaye = floatval($totalpaye); + $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); + if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) + { + if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } + elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) + { + $hasDelay = 1; + } + else + { + $hasDelay = 0; + } + } + } + + return $hasDelay; } /** + * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT) * @return number or -1 if not available */ - public function getRetainedWarrantyAmount() + public function getRetainedWarrantyAmount($rounding = -1) { + global $conf; if (empty($this->retained_warranty)) { return -1; } @@ -4632,6 +4792,11 @@ class Facture extends CommonInvoice $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100; } + if ($rounding < 0) { + $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); + return round($retainedWarrantyAmount, 2); + } + return $retainedWarrantyAmount; } diff --git a/htdocs/compta/facture/class/facturestats.class.php b/htdocs/compta/facture/class/facturestats.class.php index f24f31bbc9a..ea0b17bc59a 100644 --- a/htdocs/compta/facture/class/facturestats.class.php +++ b/htdocs/compta/facture/class/facturestats.class.php @@ -22,10 +22,10 @@ * \ingroup factures * \brief Fichier de la classe de gestion des stats des factures */ -include_once DOL_DOCUMENT_ROOT . '/core/class/stats.class.php'; -include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; -include_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; -include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +include_once DOL_DOCUMENT_ROOT.'/core/class/stats.class.php'; +include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; /** * Class to manage stats for invoices (customer and supplier) @@ -64,32 +64,32 @@ class FactureStats extends Stats if ($mode == 'customer') { - $object=new Facture($this->db); + $object = new Facture($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as f"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field='total'; - $this->field_line='total_ht'; + $this->field = 'total'; + $this->field_line = 'total_ht'; } if ($mode == 'supplier') { - $object=new FactureFournisseur($this->db); + $object = new FactureFournisseur($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as f"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; - $this->field='total_ht'; - $this->field_line='total_ht'; + $this->field = 'total_ht'; + $this->field_line = 'total_ht'; } $this->where = " f.fk_statut >= 0"; - $this->where.= " AND f.entity IN (".getEntity('invoice').")"; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($mode == 'customer') $this->where.=" AND (f.fk_statut <> 3 OR f.close_code <> 'replaced')"; // Exclude replaced invoices as they are duplicated (we count closed invoices for other reasons) + $this->where .= " AND f.entity IN (".getEntity('invoice').")"; + if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($mode == 'customer') $this->where .= " AND (f.fk_statut <> 3 OR f.close_code <> 'replaced')"; // Exclude replaced invoices as they are duplicated (we count closed invoices for other reasons) if ($this->socid) { - $this->where.=" AND f.fk_soc = ".$this->socid; + $this->where .= " AND f.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where.=' AND f.fk_user_author = '.$this->userid; - if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $this->where.= " AND f.type IN (0,1,2,5)"; - else $this->where.= " AND f.type IN (0,1,2,3,5)"; + if ($this->userid > 0) $this->where .= ' AND f.fk_user_author = '.$this->userid; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $this->where .= " AND f.type IN (0,1,2,5)"; + else $this->where .= " AND f.type IN (0,1,2,3,5)"; } @@ -105,14 +105,14 @@ class FactureStats extends Stats global $user; $sql = "SELECT date_format(f.datef,'%m') as dm, COUNT(*) as nb"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getNbByMonth($year, $sql, $format); + $res = $this->_getNbByMonth($year, $sql, $format); //var_dump($res);print '
    '; return $res; } @@ -128,11 +128,11 @@ class FactureStats extends Stats global $user; $sql = "SELECT date_format(f.datef,'%Y') as dm, COUNT(*), SUM(c.".$this->field.")"; - $sql.= " FROM ".$this->from; + $sql .= " FROM ".$this->from; if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getNbByYear($sql); } @@ -150,14 +150,14 @@ class FactureStats extends Stats global $user; $sql = "SELECT date_format(datef,'%m') as dm, SUM(f.".$this->field.")"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); - $res=$this->_getAmountByMonth($year, $sql, $format); + $res = $this->_getAmountByMonth($year, $sql, $format); //var_dump($res);print '
    '; return $res; } @@ -173,12 +173,12 @@ class FactureStats extends Stats global $user; $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->field.")"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; - $sql.= " AND ".$this->where; - $sql.= " GROUP BY dm"; - $sql.= $this->db->order('dm', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; + $sql .= " AND ".$this->where; + $sql .= " GROUP BY dm"; + $sql .= $this->db->order('dm', 'DESC'); return $this->_getAverageByMonth($year, $sql); } @@ -193,11 +193,11 @@ class FactureStats extends Stats global $user; $sql = "SELECT date_format(datef,'%Y') as year, COUNT(*) as nb, SUM(f.".$this->field.") as total, AVG(f.".$this->field.") as avg"; - $sql.= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " GROUP BY year"; - $sql.= $this->db->order('year', 'DESC'); + $sql .= " FROM ".$this->from; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " GROUP BY year"; + $sql .= $this->db->order('year', 'DESC'); return $this->_getAllByYear($sql); } @@ -205,23 +205,24 @@ class FactureStats extends Stats /** * Return nb, amount of predefined product for year * - * @param int $year Year to scan - * @return array Array of values + * @param int $year Year to scan + * @param int $limit Limit + * @return array Array of values */ - public function getAllByProduct($year) + public function getAllByProduct($year, $limit = 10) { global $user; $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; - $sql.= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$this->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE ".$this->where; - $sql.= " AND f.rowid = tl.fk_facture AND tl.fk_product = product.rowid"; - $sql.= " AND f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; - $sql.= " GROUP BY product.ref"; - $sql.= $this->db->order('nb', 'DESC'); + $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; + if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE ".$this->where; + $sql .= " AND f.rowid = tl.fk_facture AND tl.fk_product = product.rowid"; + $sql .= " AND f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year, 1, false))."' AND '".$this->db->idate(dol_get_last_day($year, 12, false))."'"; + $sql .= " GROUP BY product.ref"; + $sql .= $this->db->order('nb', 'DESC'); //$sql.= $this->db->plimit(20); - return $this->_getAllByProduct($sql); + return $this->_getAllByProduct($sql, $limit); } } diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index e880d77db74..cccae974893 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -58,7 +58,7 @@ $result=restrictedArea($user, 'facture', $id, ''); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index 370bfe9a8b9..c04e9072339 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -33,10 +33,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -if (!empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - //require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; -} +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; @@ -54,6 +51,8 @@ $cancel = GETPOST('cancel', 'alpha'); $toselect = GETPOST('toselect', 'array'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'invoicetemplatelist'; // To manage different context of search +$socid = GETPOST('socid', 'int'); + // Security check $id = (GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int')); $lineid = GETPOST('lineid', 'int'); @@ -62,7 +61,6 @@ if ($user->socid) $socid = $user->socid; $objecttype = 'facture_rec'; 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'); @@ -85,7 +83,7 @@ $search_status = GETPOST('search_status', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; if (!$sortorder) $sortorder = 'DESC'; @@ -146,6 +144,13 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); +if ($socid > 0) { + $tmpthirdparty = new Societe($db); + $res = $tmpthirdparty->fetch($socid); + if ($res > 0) $search_societe = $tmpthirdparty->name; +} + + /* * Actions @@ -218,6 +223,7 @@ $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray[' /* * List mode */ + $sql = "SELECT s.nom as name, s.rowid as socid, f.rowid as facid, f.titre as title, f.total, f.tva as total_vat, f.total_ttc, f.frequency, f.unit_frequency,"; $sql .= " f.nb_gen_done, f.nb_gen_max, f.date_last_gen, f.date_when, f.suspended,"; $sql .= " f.datec, f.tms,"; @@ -243,6 +249,7 @@ if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } if ($search_ref) $sql .= natural_search('f.titre', $search_ref); +if ($socid) $sql .= ' AND s.rowid = '.(int) $socid; if ($search_societe) $sql .= natural_search('s.nom', $search_societe); if ($search_montant_ht != '') $sql .= natural_search('f.total', $search_montant_ht, 1); if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_vat, 1); @@ -286,7 +293,7 @@ if ($resql) $param = ''; if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($socid) $param .= '&socid='.urlencode($socid); + if ($socid > 0) $param .= '&socid='.urlencode($socid); if ($search_day) $param .= '&search_day='.urlencode($search_day); if ($search_month) $param .= '&search_month='.urlencode($search_month); if ($search_year) $param .= '&search_year='.urlencode($search_year); @@ -299,12 +306,11 @@ if ($resql) if ($search_montant_vat != '') $param .= '&search_montant_vat='.urlencode($search_montant_vat); if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); if ($search_payment_mode != '') $param .= '&search_payment_mode='.urlencode($search_payment_mode); - if ($search_payment_type != '') $param .= '&search_payment_type='.urlencode($search_payment_type); + if ($search_payment_term != '') $param .= '&search_payment_term='.urlencode($search_payment_term); if ($search_recurring != '' && $search_recurrning != '-1') $param .= '&search_recurring='.urlencode($search_recurring); if ($search_frequency > 0) $param .= '&search_frequency='.urlencode($search_frequency); if ($search_unit_frequency != '') $param .= '&search_unit_frequency='.urlencode($search_unit_frequency); if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($option) $param .= "&option=".urlencode($option); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -326,12 +332,16 @@ if ($resql) print ''; print ''; - print_barre_liste($langs->trans("RepeatableInvoices"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'invoicing', 0, '', '', $limit); + $title = $langs->trans("RepeatableInvoices"); + + print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'invoicing', 0, '', '', $limit); print ''.$langs->trans("ToCreateAPredefinedInvoice", $langs->transnoentitiesnoconv("ChangeIntoRepeatableInvoice")).'

    '; $i = 0; + $moreforfilter = ''; + print '
    '; print '
    '.$langs->trans("Filter").'
    '.$langs->trans('RetainedWarranty').''; print '%'; // Retained warranty payment term print '
    '.$langs->trans('PaymentConditionsShortRetainedWarranty').''; $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int'); - $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID; + if(empty($retained_warranty_fk_cond_reglement)){ + $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID; + if(!empty($objectsrc->retained_warranty_fk_cond_reglement)){ // use previous situation value + $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement; + }else{ + $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID; + } + } $form->select_conditions_paiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1); print '
    '.$langs->trans('BankAccount').''; @@ -3640,7 +3673,7 @@ elseif ($id > 0 || !empty($ref)) // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if ($object->type == Facture::TYPE_STANDARD) $type_fac = 'ExcessReceived'; + if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) $type_fac = 'ExcessReceived'; elseif ($object->type == Facture::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; elseif ($object->type == Facture::TYPE_DEPOSIT) $type_fac = 'Deposit'; $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac))); @@ -4517,7 +4550,7 @@ elseif ($id > 0 || !empty($ref)) $current_situation_counter = array(); foreach ($object->tab_previous_situation_invoice as $prev_invoice) { - $totalpaye = $prev_invoice->getSommePaiement(); + $totalpaye_prev = $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; @@ -4528,7 +4561,7 @@ elseif ($id > 0 || !empty($ref)) if (!empty($conf->banque->enabled)) print ''.price($prev_invoice->total_ht).''.price($prev_invoice->total_ttc).''.$prev_invoice->getLibStatut(3, $totalpaye).''.$prev_invoice->getLibStatut(3, $totalpaye_prev).'
    '."\n"; @@ -467,7 +477,6 @@ if ($resql) print ''; print "\n"; - print ''; if (!empty($arrayfields['f.titre']['checked'])) print_liste_field_titre($arrayfields['f.titre']['label'], $_SERVER['PHP_SELF'], "f.titre", "", $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); @@ -527,21 +536,21 @@ if ($resql) } if (!empty($arrayfields['f.total']['checked'])) { - print ''."\n"; + print ''."\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total'; $totalarray['val']['f.total'] += $objp->total; } if (!empty($arrayfields['f.tva']['checked'])) { - print ''."\n"; + print ''."\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.tva'; $totalarray['val']['f.tva'] += $objp->total_vat; } if (!empty($arrayfields['f.total_ttc']['checked'])) { - print ''."\n"; + print ''."\n"; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; $totalarray['val']['f.total_ttc'] += $objp->total_ttc; diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 32cd30ea207..cecbacdc209 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -87,6 +87,11 @@ $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_multicurrency_code = GETPOST('search_multicurrency_code', 'alpha'); +$search_multicurrency_tx = GETPOST('search_multicurrency_tx', 'alpha'); +$search_multicurrency_montant_ht = GETPOST('search_multicurrency_montant_ht', 'alpha'); +$search_multicurrency_montant_vat = GETPOST('search_multicurrency_montant_vat', 'alpha'); +$search_multicurrency_montant_ttc = GETPOST('search_multicurrency_montant_ttc', 'alpha'); $search_status = GETPOST('search_status', 'intcomma'); $search_paymentmode = GETPOST('search_paymentmode', 'int'); $search_paymentterms = GETPOST('search_paymentterms', 'int'); @@ -116,7 +121,7 @@ $filtre = GETPOST('filtre', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; @@ -183,6 +188,13 @@ $arrayfields = array( 'f.total_ttc'=>array('label'=>"AmountTTC", 'checked'=>0, 'position'=>130), 'dynamount_payed'=>array('label'=>"Received", 'checked'=>0, 'position'=>140), 'rtp'=>array('label'=>"Rest", 'checked'=>0, 'position'=>150), // Not enabled by default because slow + 'f.multicurrency_code'=>array('label'=>'Currency', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>160), + 'f.multicurrency_tx'=>array('label'=>'CurrencyRate', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>170), + 'f.multicurrency_total_ht'=>array('label'=>'MulticurrencyAmountHT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>180), + 'f.multicurrency_total_vat'=>array('label'=>'MulticurrencyAmountVAT', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>190), + 'f.multicurrency_total_ttc'=>array('label'=>'MulticurrencyAmountTTC', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>200), + 'multicurrency_dynamount_payed'=>array('label'=>'MulticurrencyAlreadyPaid', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>210), + 'multicurrency_rtp'=>array('label'=>'MulticurrencyRemainderToPay', 'checked'=>0, 'enabled'=>(empty($conf->multicurrency->enabled) ? 0 : 1), 'position'=>220), // Not enabled by default because slow 'f.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), 'f.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), 'f.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), @@ -236,6 +248,11 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', $search_montant_localtax1 = ''; $search_montant_localtax2 = ''; $search_montant_ttc = ''; + $search_multicurrency_code = ''; + $search_multicurrency_tx = ''; + $search_multicurrency_montant_ht = ''; + $search_multicurrency_montant_vat = ''; + $search_multicurrency_montant_ttc = ''; $search_status = ''; $search_paymentmode = ''; $search_paymentterms = ''; @@ -383,6 +400,7 @@ $sql = 'SELECT'; if ($sall || $search_product_category > 0) $sql = 'SELECT DISTINCT'; $sql .= ' f.rowid as id, f.ref, f.ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total as total_ht, f.tva as total_vat, f.total_ttc,'; $sql .= ' f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,'; +$sql .= ' f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva as multicurrency_total_vat, f.multicurrency_total_ttc,'; $sql .= ' f.datef as df, f.date_lim_reglement as datelimite, f.module_source, f.pos_source,'; $sql .= ' f.paye as paye, f.fk_statut, f.close_code,'; $sql .= ' f.datec as date_creation, f.tms as date_update, f.date_closing as date_closing,'; @@ -394,7 +412,7 @@ $sql .= " country.code as country_code,"; $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 (!$sall) $sql .= ', SUM(pf.amount) as dynamount_payed, SUM(pf.multicurrency_amount) as multicurrency_dynamount_payed'; if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { @@ -459,6 +477,11 @@ if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_v 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_multicurrency_code != '') $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +if ($search_multicurrency_tx != '') $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); +if ($search_multicurrency_montant_ht != '') $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); 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 != '') @@ -591,6 +614,11 @@ if ($resql) if ($search_montant_localtax1 != '') $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); if ($search_montant_localtax2 != '') $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); + if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); if ($search_status != '') $param .= '&search_status='.urlencode($search_status); if ($search_paymentmode > 0) $param .= '&search_paymentmode='.urlencode($search_paymentmode); if ($search_paymentterms > 0) $param .= '&search_paymentterms='.urlencode($search_paymentterms); @@ -878,13 +906,11 @@ if ($resql) print ''; print ''; } - if (!empty($arrayfields['f.retained_warranty']['checked'])) { print ''; } - if (!empty($arrayfields['dynamount_payed']['checked'])) { print ''; } + if (!empty($arrayfields['f.multicurrency_code']['checked'])) + { + // Currency + print ''; + } + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) + { + // Currency rate + print ''; + } + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) + { + // Amount + print ''; + } + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) + { + print ''; + } + if (!empty($arrayfields['multicurrency_rtp']['checked'])) + { + print ''; + } if (!empty($arrayfields['f.date_closing']['checked'])) { print '\n"; print ''; - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['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['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.module_source']['checked'])) print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.pos_source']['checked'])) print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.retained_warranty']['checked'])) print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['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['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['f.module_source']['checked'])) print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['f.pos_source']['checked'])) print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.retained_warranty']['checked'])) print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="right"', $sortfield, $sortorder); + if (!empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['multicurrency_rtp']['checked'])) print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -989,10 +1067,16 @@ if ($resql) $facturestatic->id = $obj->id; $facturestatic->ref = $obj->ref; + $facturestatic->ref_client = $obj->ref_client; $facturestatic->type = $obj->type; $facturestatic->total_ht = $obj->total_ht; $facturestatic->total_tva = $obj->total_vat; $facturestatic->total_ttc = $obj->total_ttc; + $facturestatic->multicurrency_code = $obj->multicurrency_code; + $facturestatic->multicurrency_tx = $obj->multicurrency_tx; + $facturestatic->multicurrency_total_ht = $obj->multicurrency_total_ht; + $facturestatic->multicurrency_total_tva = $obj->multicurrency_total_vat; + $facturestatic->multicurrency_total_ttc = $obj->multicurrency_total_ttc; $facturestatic->statut = $obj->fk_statut; $facturestatic->close_code = $obj->close_code; $facturestatic->total_ttc = $obj->total_ttc; @@ -1030,16 +1114,27 @@ if ($resql) $totaldeposits = $facturestatic->getSumDepositsUsed(); $totalpay = $paiement + $totalcreditnotes + $totaldeposits; $remaintopay = price2num($facturestatic->total_ttc - $totalpay); + $multicurrency_paiement = $facturestatic->getSommePaiement(1); + $multicurrency_totalcreditnotes = $facturestatic->getSumCreditNotesUsed(1); + $multicurrency_totaldeposits = $facturestatic->getSumDepositsUsed(1); + $multicurrency_totalpay = $multicurrency_paiement + $multicurrency_totalcreditnotes + $multicurrency_totaldeposits; + $multicurrency_remaintopay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_totalpay); if ($facturestatic->statut == Facture::STATUS_CLOSED && $facturestatic->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment $remaintopay = 0; + $multicurrency_remaintopay = 0; } if ($facturestatic->type == Facture::TYPE_CREDIT_NOTE && $obj->paye == 1) { // If credit note closed, we take into account the amount not yet consummed - $remaincreditnote = $discount->getAvailableDiscounts($obj->fk_soc, '', 'rc.fk_facture_source='.$facturestatic->id); + $remaincreditnote = $discount->getAvailableDiscounts($thirdpartystatic, '', 'rc.fk_facture_source='.$facturestatic->id); $remaintopay = -$remaincreditnote; $totalpay = price2num($facturestatic->total_ttc - $remaintopay); + $multicurrency_remaincreditnote = $discount->getAvailableDiscounts($thirdpartystatic, '', 'rc.fk_facture_source='.$facturestatic->id, 0, 0, 1); + $multicurrency_remaintopay = -$multicurrency_remaincreditnote; + $multicurrency_totalpay = price2num($facturestatic->multicurrency_total_ttc - $multicurrency_remaintopay); } + $facturestatic->alreadypaid = $paiement; + print ''; + print ''; if (!$i) $totalarray['nbfield']++; @@ -1303,6 +1398,55 @@ if ($resql) $totalarray['val']['rtp'] += $remaintopay; } + + // Currency + if (!empty($arrayfields['f.multicurrency_code']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + + // Currency rate + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount HT + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount VAT + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + // Amount TTC + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) + { + print ''; // TODO Use a denormalized field + if (!$i) $totalarray['nbfield']++; + } + + // Pending amount + if (!empty($arrayfields['multicurrency_rtp']['checked'])) + { + print ''; // TODO Use a denormalized field + if (!$i) $totalarray['nbfield']++; + } + // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index bd749e02dee..a72b03b47a3 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -235,7 +235,9 @@ print '
    '; // Show filter box print ''; +print ''; print ''; + print '
    '.price($objp->total).''.price($objp->total).''.price($objp->total_vat).''.price($objp->total_vat).''.price($objp->total_ttc).''.price($objp->total_ttc).''; print ''; @@ -895,6 +921,51 @@ if ($resql) print ''; print ''; + print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; @@ -936,31 +1007,38 @@ if ($resql) print "
    '; print $obj->ref_client; print ''.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; + $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); + print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."'.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : ' ').''; + print (!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : ' '); + print '
    '; print ''; // Company diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 447f5f47ecc..c9a77e5cc26 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -455,7 +455,7 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-> $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.libelle, ff.total_ht, ff.total_tva, ff.total_ttc, ff.tms, ff.paye"; $sql .= ", s.nom as name"; $sql .= ", s.rowid as socid"; - $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; + $sql .= ", s.code_fournisseur, s.code_compta_fournisseur, s.email"; $sql .= ", SUM(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf on ff.rowid=pf.fk_facturefourn"; @@ -503,10 +503,14 @@ if (!empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture-> $thirdpartystatic->id = $obj->socid; $thirdpartystatic->name = $obj->name; + $thirdpartystatic->email = $obj->email; + $thirdpartystatic->country_id = 0; + $thirdpartystatic->country_code = ''; + $thirdpartystatic->client = 0; $thirdpartystatic->fournisseur = 1; - //$thirdpartystatic->code_client = $obj->code_client; + $thirdpartystatic->code_client = ''; $thirdpartystatic->code_fournisseur = $obj->code_fournisseur; - //$thirdpartystatic->code_compta = $obj->code_compta; + $thirdpartystatic->code_compta = ''; $thirdpartystatic->code_compta_fournisseur = $obj->code_compta_fournisseur; print ''; + print ''; if (!$i) $totalarray['nbfield']++; // Account diff --git a/htdocs/compta/paiement/tovalidate.php b/htdocs/compta/paiement/tovalidate.php index 1c5e4be20c2..c14c29f3179 100644 --- a/htdocs/compta/paiement/tovalidate.php +++ b/htdocs/compta/paiement/tovalidate.php @@ -42,7 +42,7 @@ if ($user->socid > 0) $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -64,7 +64,7 @@ if (! $sortfield) $sortfield="p.rowid"; llxHeader(); $sql = "SELECT p.rowid, p.datep as dp, p.amount, p.statut"; -$sql.=", c.libelle as paiement_type, p.num_paiement"; +$sql.=", c.libelle as paiement_type, p.num_paiement as num_payment"; $sql.= " FROM ".MAIN_DB_PREFIX."paiement as p LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_paiement = c.id"; if ($socid) { @@ -119,7 +119,7 @@ if ($resql) print ''; print ''; print '\n"; - print "\n"; + print "\n"; print ''; print ''; - print ''."\n"; + print ''."\n"; print ''; print ''; diff --git a/htdocs/compta/prelevement/bons.php b/htdocs/compta/prelevement/bons.php index c623d660aaa..b42e6a4fe62 100644 --- a/htdocs/compta/prelevement/bons.php +++ b/htdocs/compta/prelevement/bons.php @@ -39,7 +39,7 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php index d998554b533..68f40999aa7 100644 --- a/htdocs/compta/prelevement/card.php +++ b/htdocs/compta/prelevement/card.php @@ -49,7 +49,7 @@ $socid = GETPOST('socid', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 4050d081fe4..41f1ebf5a62 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -484,7 +484,7 @@ class BonPrelevement extends CommonObject $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice $paiement->paiementid = 3; // $paiement->num_payment = $this->ref; // Set ref of direct debit note - $paiement->num_paiement = $this->ref; // For bacward compatibility + $paiement->num_paiement = $this->ref; // For backward compatibility $paiement->id_prelevement = $this->id; $paiement_id = $paiement->create($user); diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 740a1e47784..c78dbd06259 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -154,6 +154,7 @@ class RejetPrelevement $pai->datepaye = $date_rejet; $pai->paiementid = 3; // type of payment: withdrawal $pai->num_paiement = $fac->ref; + $pai->num_payment = $fac->ref; if ($pai->create($this->user) < 0) // we call with no_commit { diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index d1b6361cc34..45c413efb76 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -48,7 +48,7 @@ $action = GETPOST('action', 'alpha'); $mode = GETPOST('mode', 'alpha') ?GETPOST('mode', 'alpha') : 'real'; $format = GETPOST('format', 'aZ09'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; diff --git a/htdocs/compta/prelevement/demandes.php b/htdocs/compta/prelevement/demandes.php index 61c457c9b17..181f71a678c 100644 --- a/htdocs/compta/prelevement/demandes.php +++ b/htdocs/compta/prelevement/demandes.php @@ -50,7 +50,7 @@ $search_societe = trim(GETPOST('search_societe', 'alpha')); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php index 63db9aea363..3297042407f 100644 --- a/htdocs/compta/prelevement/factures.php +++ b/htdocs/compta/prelevement/factures.php @@ -45,7 +45,7 @@ $ref = GETPOST('ref', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/fiche-rejet.php b/htdocs/compta/prelevement/fiche-rejet.php index 4320a0c6094..44be3d1cd01 100644 --- a/htdocs/compta/prelevement/fiche-rejet.php +++ b/htdocs/compta/prelevement/fiche-rejet.php @@ -45,7 +45,7 @@ $ref = GETPOST('ref', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/fiche-stat.php b/htdocs/compta/prelevement/fiche-stat.php index 70441ff19c2..6e8e8390ae8 100644 --- a/htdocs/compta/prelevement/fiche-stat.php +++ b/htdocs/compta/prelevement/fiche-stat.php @@ -43,7 +43,7 @@ $ref = GETPOST('ref', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/line.php b/htdocs/compta/prelevement/line.php index 5d0734cae22..3615809d21a 100644 --- a/htdocs/compta/prelevement/line.php +++ b/htdocs/compta/prelevement/line.php @@ -43,7 +43,7 @@ $action = GETPOST('action', 'alpha'); $id = GETPOST('id', 'int'); $socid = GETPOST('socid', 'int'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortorder = GETPOST('sortorder', 'alpha'); $sortfield = GETPOST('sortfield', 'alpha'); diff --git a/htdocs/compta/prelevement/list.php b/htdocs/compta/prelevement/list.php index e5ba1daffa8..bbac6c6232e 100644 --- a/htdocs/compta/prelevement/list.php +++ b/htdocs/compta/prelevement/list.php @@ -41,7 +41,7 @@ $result = restrictedArea($user, 'prelevement', '', '', 'bons'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php index 4235f5d7fc3..cc4f3fe5e79 100644 --- a/htdocs/compta/prelevement/rejets.php +++ b/htdocs/compta/prelevement/rejets.php @@ -39,7 +39,7 @@ if ($user->socid) $socid=$user->socid; $result = restrictedArea($user, 'prelevement', '', '', 'bons'); // Get supervariables -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortorder = GETPOST('sortorder', 'alpha'); $sortfield = GETPOST('sortfield', 'alpha'); diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index 60ea008a834..37bf3d36d70 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -48,7 +48,7 @@ $hookmanager->initHooks(array('recapcomptacard', 'globalcard')); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index ee76a29d282..17d2becfc19 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -57,7 +57,7 @@ if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'account $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -67,8 +67,7 @@ if (!$sortorder) $sortorder = 'ASC'; // Date range $year = GETPOST('year', 'int'); -if (empty($year)) -{ +if (empty($year)) { $year_current = strftime("%Y", dol_now()); $month_current = strftime("%m", dol_now()); $year_start = $year_current; @@ -114,7 +113,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')); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES' or 'BOOKKEEPING') @@ -193,17 +192,21 @@ if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') } // Show report array -$param = '&modecompta='.$modecompta; +$param = '&modecompta='.urlencode($modecompta).'&showaccountdetail='.urlencode($showaccountdetail); if ($date_startday) $param .= '&date_startday='.$date_startday; if ($date_startmonth) $param .= '&date_startmonth='.$date_startmonth; if ($date_startyear) $param .= '&date_startyear='.$date_startyear; if ($date_endday) $param .= '&date_endday='.$date_endday; if ($date_endmonth) $param .= '&date_endmonth='.$date_endmonth; -if ($date_endyear) $param .= '&date_endyear='.$date_startyear; +if ($date_endyear) $param .= '&date_endyear='.$date_endyear; print '
    '.$langs->trans("Filter").'
    '; diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index fb2a3edfd9c..b4da848ea5a 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -49,7 +49,7 @@ $socid = GETPOST('socid', 'int'); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $amounts = array(); $amountsresttopay = array(); @@ -97,6 +97,8 @@ if (empty($reshook)) $totalpayment = 0; $multicurrency_totalpayment = 0; $atleastonepaymentnotnull = 0; + $formquestion = array(); + $i = 0; // Generate payment array and check if there is payment higher than invoice and payment date before invoice date $tmpinvoice = new Facture($db); @@ -216,7 +218,7 @@ if (empty($reshook)) { $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')); $db->begin(); @@ -262,8 +264,10 @@ if (empty($reshook)) $paiement->amounts = $amounts; // Array with all payments dispatching with invoice id $paiement->multicurrency_amounts = $multicurrency_amounts; // Array with all payments dispatching $paiement->paiementid = dol_getIdFromCode($db, GETPOST('paiementcode'), 'c_paiement', 'code', 'id', 1); - $paiement->num_paiement = GETPOST('num_paiement', 'alpha'); - $paiement->note = GETPOST('comment', 'alpha'); + $paiement->num_payment = GETPOST('num_paiement', 'alpha'); + $paiement->note_private = GETPOST('comment', 'alpha'); + $paiement->num_paiement = $paiement->num_payment; // For bacward compatibility + $paiement->note = $paiement->note_private; // For bacward compatibility if (!$error) { diff --git a/htdocs/compta/paiement/cheque/card.php b/htdocs/compta/paiement/cheque/card.php index 526905e2ee9..89445e1ec74 100644 --- a/htdocs/compta/paiement/cheque/card.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -48,7 +48,7 @@ $result = restrictedArea($user, 'cheque', $id, 'bordereau_cheque', '', 'fk_user_ $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "b.dateo,b.rowid"; if (empty($page) || $page == -1) { $page = 0; } diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php index 823ae87d420..4534f08dbb1 100644 --- a/htdocs/compta/paiement/cheque/list.php +++ b/htdocs/compta/paiement/cheque/list.php @@ -45,7 +45,7 @@ $search_amount = GETPOST('search_amount', 'alpha'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index ad20599ce94..9b0ee645fc7 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -29,8 +29,8 @@ * \ingroup facture * \brief File of class to manage payments of customers invoices */ -require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT .'/multicurrency/class/multicurrency.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** @@ -41,12 +41,12 @@ class Paiement extends CommonObject /** * @var string ID to identify managed object */ - public $element='payment'; + public $element = 'payment'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='paiement'; + public $table_element = 'paiement'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png @@ -68,12 +68,12 @@ class Paiement extends CommonObject */ public $montant; - public $amount; // Total amount of payment - public $amounts=array(); // Array of amounts - public $multicurrency_amounts=array(); // Array of amounts + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts + public $multicurrency_amounts = array(); // Array of amounts public $author; - public $paiementid; // Type of payment. Id saved into fields fk_paiement on llx_paiement - public $paiementcode; // Code of payment. + public $paiementid; // Type of payment. Id saved into fields fk_paiement on llx_paiement + public $paiementcode; // Code of payment. /** * @var string type libelle @@ -136,7 +136,7 @@ class Paiement extends CommonObject /** * @var int payment id */ - public $fk_paiement; // Type of payment + public $fk_paiement; // Type of payment /** @@ -160,18 +160,18 @@ class Paiement extends CommonObject public function fetch($id, $ref = '', $fk_bank = '') { $sql = 'SELECT p.rowid, p.ref, p.datep as dp, p.amount, p.statut, p.ext_payment_id, p.ext_payment_site, p.fk_bank,'; - $sql.= ' c.code as type_code, c.libelle as type_label,'; - $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'; - $sql.= ' WHERE p.entity IN (' . getEntity('invoice').')'; + $sql .= ' c.code as type_code, c.libelle as type_label,'; + $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'; + $sql .= ' WHERE p.entity IN ('.getEntity('invoice').')'; if ($id > 0) - $sql.= ' AND p.rowid = '.$id; + $sql .= ' AND p.rowid = '.$id; elseif ($ref) - $sql.= " AND p.ref = '".$ref."'"; + $sql .= " AND p.ref = '".$ref."'"; elseif ($fk_bank) - $sql.= ' AND p.fk_bank = '.$fk_bank; + $sql .= ' AND p.fk_bank = '.$fk_bank; $resql = $this->db->query($sql); if ($resql) @@ -180,15 +180,15 @@ class Paiement extends CommonObject { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - $this->ref = $obj->ref?$obj->ref:$obj->rowid; + $this->ref = $obj->ref ? $obj->ref : $obj->rowid; $this->date = $this->db->jdate($obj->dp); $this->datepaye = $this->db->jdate($obj->dp); - $this->num_paiement = $obj->num_payment; // deprecated + $this->num_paiement = $obj->num_payment; // deprecated $this->num_payment = $obj->num_payment; - $this->montant = $obj->amount; // deprecated + $this->montant = $obj->amount; // deprecated $this->amount = $obj->amount; $this->note = $obj->note; - $this->type_label = $obj->type_label; + $this->type_label = $obj->type_label; $this->type_code = $obj->type_code; $this->statut = $obj->statut; $this->ext_payment_id = $obj->ext_payment_id; @@ -231,7 +231,7 @@ class Paiement extends CommonObject $error = 0; $way = $this->getWay(); - $now=dol_now(); + $now = dol_now(); // Clean parameters $totalamount = 0; @@ -258,7 +258,7 @@ class Paiement extends CommonObject $newvalue = price2num($value, 'MT'); $amounts[$key] = $newvalue; $totalamount += $newvalue; - if (! empty($newvalue)) $atleastonepaymentnotnull++; + if (!empty($newvalue)) $atleastonepaymentnotnull++; } $totalamount = price2num($totalamount); @@ -267,8 +267,8 @@ class Paiement extends CommonObject // Check parameters if (empty($totalamount) && empty($atleastonepaymentnotnull)) // We accept negative amounts for withdraw reject but not empty arrays { - $this->errors[]='TotalAmountEmpty'; - $this->error='TotalAmountEmpty'; + $this->errors[] = 'TotalAmountEmpty'; + $this->error = 'TotalAmountEmpty'; return -1; } @@ -276,7 +276,7 @@ class Paiement extends CommonObject $this->db->begin(); - $this->ref = $this->getNextNumRef(is_object($thirdparty)?$thirdparty:''); + $this->ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : ''); if ($way == 'dolibarr') { @@ -289,11 +289,11 @@ class Paiement extends CommonObject $mtotal = $totalamount; } - $num_payment = ($this->num_payment?$this->num_payment:$this->num_paiement); - $note = ($this->note_public?$this->note_public:$this->note); + $num_payment = ($this->num_payment ? $this->num_payment : $this->num_paiement); + $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, ext_payment_id, ext_payment_site, fk_user_creat)"; - $sql.= " VALUES (".$conf->entity.", '".$this->db->escape($this->ref)."', '". $this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', ".$total.", ".$mtotal.", ".$this->paiementid.", '".$this->db->escape($num_payment)."', '".$this->db->escape($note)."', ".($this->ext_payment_id?"'".$this->db->escape($this->ext_payment_id)."'":"null").", ".($this->ext_payment_site?"'".$this->db->escape($this->ext_payment_site)."'":"null").", ".$user->id.")"; + $sql .= " VALUES (".$conf->entity.", '".$this->db->escape($this->ref)."', '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', ".$total.", ".$mtotal.", ".$this->paiementid.", '".$this->db->escape($num_payment)."', '".$this->db->escape($note)."', ".($this->ext_payment_id ? "'".$this->db->escape($this->ext_payment_id)."'" : "null").", ".($this->ext_payment_site ? "'".$this->db->escape($this->ext_payment_site)."'" : "null").", ".$user->id.")"; $resql = $this->db->query($sql); if ($resql) @@ -308,23 +308,23 @@ class Paiement extends CommonObject { $amount = price2num($amount); $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount, multicurrency_amount)'; - $sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\', \''.$this->multicurrency_amounts[$key].'\')'; + $sql .= ' VALUES ('.$facid.', '.$this->id.', \''.$amount.'\', \''.$this->multicurrency_amounts[$key].'\')'; dol_syslog(get_class($this).'::create Amount line '.$key.' insert paiement_facture', LOG_DEBUG); - $resql=$this->db->query($sql); + $resql = $this->db->query($sql); if ($resql) { - $invoice=new Facture($this->db); + $invoice = new Facture($this->db); $invoice->fetch($facid); // If we want to closed payed invoices if ($closepaidinvoices) { $paiement = $invoice->getSommePaiement(); - $creditnotes=$invoice->getSumCreditNotesUsed(); - $deposits=$invoice->getSumDepositsUsed(); - $alreadypayed=price2num($paiement + $creditnotes + $deposits, 'MT'); - $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); + $creditnotes = $invoice->getSumCreditNotesUsed(); + $deposits = $invoice->getSumDepositsUsed(); + $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); + $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); //var_dump($invoice->total_ttc.' - '.$paiement.' -'.$creditnotes.' - '.$deposits.' - '.$remaintopay);exit; @@ -395,12 +395,12 @@ class Paiement extends CommonObject } // Set invoice to paid - if (! $error) + if (!$error) { - $result=$invoice->set_paid($user, '', ''); - if ($result<0) + $result = $invoice->set_paid($user, '', ''); + if ($result < 0) { - $this->error=$invoice->error; + $this->error = $invoice->error; $error++; } } @@ -412,13 +412,13 @@ class Paiement extends CommonObject { dol_syslog(get_class($this).'::create Regenerate the document after inserting payment for thirdparty default_lang='.(is_object($invoice->thirdparty) ? $invoice->thirdparty->default_lang : 'null'), LOG_DEBUG); - $newlang=''; + $newlang = ''; $outputlangs = $langs; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $invoice->fetch_thirdparty(); $newlang = $invoice->thirdparty->default_lang; } - if (! empty($newlang)) { + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -432,7 +432,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } } @@ -442,25 +442,25 @@ class Paiement extends CommonObject } } - if (! $error) // All payments into $this->amounts were recorded without errors + if (!$error) // All payments into $this->amounts were recorded without errors { // Appel des triggers - $result=$this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user); + $result = $this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user); if ($result < 0) { $error++; } // Fin appel triggers } } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $error++; } - if (! $error) + if (!$error) { - $this->amount=$total; - $this->total=$total; // deprecated - $this->multicurrency_amount=$mtotal; + $this->amount = $total; + $this->total = $total; // deprecated + $this->multicurrency_amount = $mtotal; $this->db->commit(); return $this->id; } @@ -484,7 +484,7 @@ class Paiement extends CommonObject { global $conf, $user, $langs; - $error=0; + $error = 0; $bank_line_id = $this->bank_line; @@ -492,12 +492,12 @@ class Paiement extends CommonObject // Verifier si paiement porte pas sur une facture classee // Si c'est le cas, on refuse la suppression - $billsarray=$this->getBillsArray('fk_statut > 1'); + $billsarray = $this->getBillsArray('fk_statut > 1'); if (is_array($billsarray)) { if (count($billsarray)) { - $this->error="ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible"; + $this->error = "ErrorDeletePaymentLinkedToAClosedInvoiceNotPossible"; $this->db->rollback(); return -1; } @@ -513,32 +513,32 @@ class Paiement extends CommonObject { $accline = new AccountLine($this->db); - $result=$accline->fetch($bank_line_id); - if ($result == 0) $accline->rowid=$bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url + $result = $accline->fetch($bank_line_id); + if ($result == 0) $accline->rowid = $bank_line_id; // If not found, we set artificially rowid to allow delete of llx_bank_url // Delete bank account url lines linked to payment - $result=$accline->delete_urls($user); + $result = $accline->delete_urls($user); if ($result < 0) { - $this->error=$accline->error; + $this->error = $accline->error; $this->db->rollback(); return -3; } // Delete bank account lines linked to payment - $result=$accline->delete($user); + $result = $accline->delete($user); if ($result < 0) { - $this->error=$accline->error; + $this->error = $accline->error; $this->db->rollback(); return -4; } } - if (! $notrigger) + if (!$notrigger) { // Call triggers - $result=$this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user); + $result = $this->call_trigger('PAYMENT_CUSTOMER_DELETE', $user); if ($result < 0) { $this->db->rollback(); @@ -549,18 +549,18 @@ class Paiement extends CommonObject // Delete payment (into paiement_facture and paiement) $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement_facture'; - $sql.= ' WHERE fk_paiement = '.$this->id; + $sql .= ' WHERE fk_paiement = '.$this->id; dol_syslog($sql); $result = $this->db->query($sql); if ($result) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiement'; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog($sql); $result = $this->db->query($sql); - if (! $result) + if (!$result) { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -3; } @@ -570,7 +570,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->error; + $this->error = $this->db->error; $this->db->rollback(); return -5; } @@ -592,46 +592,46 @@ class Paiement extends CommonObject */ public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque, $notrigger = 0) { - global $conf,$langs,$user; + global $conf, $langs, $user; - $error=0; - $bank_line_id=0; + $error = 0; + $bank_line_id = 0; - if (! empty($conf->banque->enabled)) + if (!empty($conf->banque->enabled)) { if ($accountid <= 0) { - $this->error='Bad value for parameter accountid='.$accountid; + $this->error = 'Bad value for parameter accountid='.$accountid; dol_syslog(get_class($this).'::addPaymentToBank '.$this->error, LOG_ERR); return -1; } $this->db->begin(); - $this->fk_account=$accountid; + $this->fk_account = $accountid; include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - dol_syslog("$user->id,$mode,$label,$this->fk_account,$emetteur_nom,$emetteur_banque"); + dol_syslog("$user->id, $mode, $label, $this->fk_account, $emetteur_nom, $emetteur_banque"); $acc = new Account($this->db); - $result=$acc->fetch($this->fk_account); + $result = $acc->fetch($this->fk_account); - $totalamount=$this->amount; - if (empty($totalamount)) $totalamount=$this->total; // For backward compatibility + $totalamount = $this->amount; + if (empty($totalamount)) $totalamount = $this->total; // For backward compatibility // if dolibarr currency != bank currency then we received an amount in customer currency (currently I don't manage the case : my currency is USD, the customer currency is EUR and he paid me in GBP. Seems no sense for me) - if (!empty($conf->multicurrency->enabled) && $conf->currency != $acc->currency_code) $totalamount=$this->multicurrency_amount; + if (!empty($conf->multicurrency->enabled) && $conf->currency != $acc->currency_code) $totalamount = $this->multicurrency_amount; - if ($mode == 'payment_supplier') $totalamount=-$totalamount; + if ($mode == 'payment_supplier') $totalamount = -$totalamount; // Insert payment into llx_bank $bank_line_id = $acc->addline( $this->datepaye, - $this->paiementid, // Payment mode id or code ("CHQ or VIR for example") + $this->paiementid, // Payment mode id or code ("CHQ or VIR for example") $label, - $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note) - $this->num_paiement, + $totalamount, // Sign must be positive when we receive money (customer payment), negative when you give money (supplier invoice or credit note) + $this->num_payment, '', $user, $emetteur_nom, @@ -642,7 +642,7 @@ class Paiement extends CommonObject // On connait ainsi le paiement qui a genere l'ecriture bancaire if ($bank_line_id > 0) { - $result=$this->update_fk_bank($bank_line_id); + $result = $this->update_fk_bank($bank_line_id); if ($result <= 0) { $error++; @@ -650,14 +650,14 @@ class Paiement extends CommonObject } // Add link 'payment', 'payment_supplier' in bank_url between payment and bank transaction - if ( ! $error) + if (!$error) { - $url=''; - if ($mode == 'payment') $url=DOL_URL_ROOT.'/compta/paiement/card.php?id='; - if ($mode == 'payment_supplier') $url=DOL_URL_ROOT.'/fourn/paiement/card.php?id='; + $url = ''; + if ($mode == 'payment') $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='; + if ($mode == 'payment_supplier') $url = DOL_URL_ROOT.'/fourn/paiement/card.php?id='; if ($url) { - $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); if ($result <= 0) { $error++; @@ -668,9 +668,9 @@ class Paiement extends CommonObject // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) //if (! $error && $label != '(WithdrawalPayment)') - if (! $error) + if (!$error) { - $linkaddedforthirdparty=array(); + $linkaddedforthirdparty = array(); foreach ($this->amounts as $key => $value) // We should have invoices always for same third party but we loop in case of. { if ($mode == 'payment') @@ -678,9 +678,9 @@ class Paiement extends CommonObject $fac = new Facture($this->db); $fac->fetch($key); $fac->fetch_thirdparty(); - if (! in_array($fac->thirdparty->id, $linkaddedforthirdparty)) // Not yet done for this thirdparty + if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) // Not yet done for this thirdparty { - $result=$acc->add_url_line( + $result = $acc->add_url_line( $bank_line_id, $fac->thirdparty->id, DOL_URL_ROOT.'/comm/card.php?socid=', @@ -688,7 +688,7 @@ class Paiement extends CommonObject 'company' ); if ($result <= 0) dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror()); - $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id; // Mark as done for this thirdparty + $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty } } if ($mode == 'payment_supplier') @@ -696,9 +696,9 @@ class Paiement extends CommonObject $fac = new FactureFournisseur($this->db); $fac->fetch($key); $fac->fetch_thirdparty(); - if (! in_array($fac->thirdparty->id, $linkaddedforthirdparty)) // Not yet done for this thirdparty + if (!in_array($fac->thirdparty->id, $linkaddedforthirdparty)) // Not yet done for this thirdparty { - $result=$acc->add_url_line( + $result = $acc->add_url_line( $bank_line_id, $fac->thirdparty->id, DOL_URL_ROOT.'/fourn/card.php?socid=', @@ -706,15 +706,15 @@ class Paiement extends CommonObject 'company' ); if ($result <= 0) dol_syslog(get_class($this).'::addPaymentToBank '.$this->db->lasterror()); - $linkaddedforthirdparty[$fac->thirdparty->id]=$fac->thirdparty->id; // Mark as done for this thirdparty + $linkaddedforthirdparty[$fac->thirdparty->id] = $fac->thirdparty->id; // Mark as done for this thirdparty } } } } // Add link 'WithdrawalPayment' in bank_url - if (! $error && $label == '(WithdrawalPayment)') { - $result=$acc->add_url_line( + if (!$error && $label == '(WithdrawalPayment)') { + $result = $acc->add_url_line( $bank_line_id, $this->id_prelevement, DOL_URL_ROOT.'/compta/prelevement/card.php?id=', @@ -723,21 +723,21 @@ class Paiement extends CommonObject ); } - if (! $error && ! $notrigger) + if (!$error && !$notrigger) { // Appel des triggers - $result=$this->call_trigger('PAYMENT_ADD_TO_BANK', $user); + $result = $this->call_trigger('PAYMENT_ADD_TO_BANK', $user); if ($result < 0) { $error++; } // Fin appel triggers } } else { - $this->error=$acc->error; + $this->error = $acc->error; $error++; } - if (! $error) + if (!$error) { $this->db->commit(); } @@ -747,7 +747,7 @@ class Paiement extends CommonObject } } - if (! $error) + if (!$error) { return $bank_line_id; } @@ -769,7 +769,7 @@ class Paiement extends CommonObject { // phpcs:enable $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.$id_bank; - $sql.= ' WHERE rowid = '.$this->id; + $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG); $result = $this->db->query($sql); @@ -779,7 +779,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::update_fk_bank '.$this->error); return -1; } @@ -795,7 +795,7 @@ class Paiement extends CommonObject public function update_date($date) { // phpcs:enable - $error=0; + $error = 0; if (!empty($date) && $this->statut != 1) { @@ -804,35 +804,35 @@ class Paiement extends CommonObject dol_syslog(get_class($this)."::update_date with date = ".$date, LOG_DEBUG); $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET datep = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET datep = '".$this->db->idate($date)."'"; + $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if (! $result) + if (!$result) { $error++; - $this->error='Error -1 '.$this->db->error(); + $this->error = 'Error -1 '.$this->db->error(); } $type = $this->element; $sql = "UPDATE ".MAIN_DB_PREFIX.'bank'; - $sql.= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'"; - $sql.= " WHERE rowid IN (SELECT fk_bank FROM ".MAIN_DB_PREFIX."bank_url WHERE type = '".$type."' AND url_id = ".$this->id.")"; - $sql.= " AND rappro = 0"; + $sql .= " SET dateo = '".$this->db->idate($date)."', datev = '".$this->db->idate($date)."'"; + $sql .= " WHERE rowid IN (SELECT fk_bank FROM ".MAIN_DB_PREFIX."bank_url WHERE type = '".$type."' AND url_id = ".$this->id.")"; + $sql .= " AND rappro = 0"; $result = $this->db->query($sql); - if (! $result) + if (!$result) { $error++; - $this->error='Error -1 '.$this->db->error(); + $this->error = 'Error -1 '.$this->db->error(); } - if (! $error) + if (!$error) { } - if (! $error) + if (!$error) { $this->datepaye = $date; $this->date = $date; @@ -859,10 +859,10 @@ class Paiement extends CommonObject public function update_num($num) { // phpcs:enable - if(!empty($num) && $this->statut!=1) { + if (!empty($num) && $this->statut != 1) { $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; - $sql.= " SET num_paiement = '".$this->db->escape($num)."'"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " SET num_paiement = '".$this->db->escape($num)."'"; + $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update_num", LOG_DEBUG); $result = $this->db->query($sql); @@ -873,7 +873,7 @@ class Paiement extends CommonObject } else { - $this->error='Error -1 '.$this->db->error(); + $this->error = 'Error -1 '.$this->db->error(); return -2; } } @@ -898,7 +898,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::valide '.$this->error); return -1; } @@ -922,7 +922,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->lasterror(); + $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::reject '.$this->error); return -1; } @@ -937,8 +937,8 @@ class Paiement extends CommonObject public function info($id) { $sql = 'SELECT p.rowid, p.datec, p.fk_user_creat, p.fk_user_modif, p.tms'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p'; - $sql.= ' WHERE p.rowid = '.$id; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement as p'; + $sql .= ' WHERE p.rowid = '.$id; dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); @@ -953,7 +953,7 @@ class Paiement extends CommonObject { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); - $this->user_creation = $cuser; + $this->user_creation = $cuser; } if ($obj->fk_user_modif) { @@ -981,20 +981,20 @@ class Paiement extends CommonObject public function getBillsArray($filter = '') { $sql = 'SELECT pf.fk_facture'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'facture as f'; // We keep link on invoice to allow use of some filters on invoice - $sql.= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.$this->id; - if ($filter) $sql.= ' AND '.$filter; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'facture as f'; // We keep link on invoice to allow use of some filters on invoice + $sql .= ' WHERE pf.fk_facture = f.rowid AND pf.fk_paiement = '.$this->id; + if ($filter) $sql .= ' AND '.$filter; $resql = $this->db->query($sql); if ($resql) { - $i=0; - $num=$this->db->num_rows($resql); - $billsarray=array(); + $i = 0; + $num = $this->db->num_rows($resql); + $billsarray = array(); while ($i < $num) { $obj = $this->db->fetch_object($resql); - $billsarray[$i]=$obj->fk_facture; + $billsarray[$i] = $obj->fk_facture; $i++; } @@ -1002,7 +1002,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG); return -1; } @@ -1016,19 +1016,19 @@ class Paiement extends CommonObject public function getAmountsArray() { $sql = 'SELECT pf.fk_facture, pf.amount'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf'; - $sql.= ' WHERE pf.fk_paiement = '.$this->id; + $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf'; + $sql .= ' WHERE pf.fk_paiement = '.$this->id; $resql = $this->db->query($sql); if ($resql) { - $i=0; - $num=$this->db->num_rows($resql); + $i = 0; + $num = $this->db->num_rows($resql); $amounts = array(); while ($i < $num) { $obj = $this->db->fetch_object($resql); - $amounts[$obj->fk_facture]=$obj->amount; + $amounts[$obj->fk_facture] = $obj->amount; $i++; } @@ -1036,7 +1036,7 @@ class Paiement extends CommonObject } else { - $this->error=$this->db->error(); + $this->error = $this->db->error(); dol_syslog(get_class($this).'::getAmountsArray Error '.$this->error.' -', LOG_DEBUG); return -1; } @@ -1056,13 +1056,13 @@ class Paiement extends CommonObject $langs->load("bills"); // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->PAYMENT_ADDON)) $conf->global->PAYMENT_ADDON='mod_payment_cicada'; - elseif ($conf->global->PAYMENT_ADDON=='ant') $conf->global->PAYMENT_ADDON='mod_payment_ant'; - elseif ($conf->global->PAYMENT_ADDON=='cicada') $conf->global->PAYMENT_ADDON='mod_payment_cicada'; + if (empty($conf->global->PAYMENT_ADDON)) $conf->global->PAYMENT_ADDON = 'mod_payment_cicada'; + elseif ($conf->global->PAYMENT_ADDON == 'ant') $conf->global->PAYMENT_ADDON = 'mod_payment_ant'; + elseif ($conf->global->PAYMENT_ADDON == 'cicada') $conf->global->PAYMENT_ADDON = 'mod_payment_cicada'; - if (! empty($conf->global->PAYMENT_ADDON)) + if (!empty($conf->global->PAYMENT_ADDON)) { - $mybool=false; + $mybool = false; $file = $conf->global->PAYMENT_ADDON.".php"; $classname = $conf->global->PAYMENT_ADDON; @@ -1076,12 +1076,12 @@ class Paiement extends CommonObject // Load file with numbering class (if found) if (is_file($dir.$file) && is_readable($dir.$file)) { - $mybool |= include_once $dir . $file; + $mybool |= include_once $dir.$file; } } // For compatibility - if (! $mybool) + if (!$mybool) { $file = $conf->global->PAYMENT_ADDON.".php"; $classname = "mod_payment_".$conf->global->PAYMENT_ADDON; @@ -1093,12 +1093,12 @@ class Paiement extends CommonObject // Load file with numbering class (if found) if (is_file($dir.$file) && is_readable($dir.$file)) { - $mybool |= include_once $dir . $file; + $mybool |= include_once $dir.$file; } } } - if (! $mybool) + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; @@ -1162,16 +1162,16 @@ class Paiement extends CommonObject */ public function initAsSpecimen($option = '') { - global $user,$langs,$conf; + global $user, $langs, $conf; - $now=dol_now(); - $arraynow=dol_getdate($now); - $nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); + $now = dol_now(); + $arraynow = dol_getdate($now); + $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']); // Initialize parameters - $this->id=0; + $this->id = 0; $this->ref = 'SPECIMEN'; - $this->specimen=1; + $this->specimen = 1; $this->facid = 1; $this->datepaye = $nownotime; } @@ -1190,49 +1190,49 @@ class Paiement extends CommonObject { global $conf, $langs; - 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=''; + $result = ''; $label = ''.$langs->trans("ShowPayment").'
    '; - $label.= ''.$langs->trans("Ref").': '.$this->ref; - if ($this->datepaye ? $this->datepaye : $this->date) $label.= '
    '.$langs->trans("Date").': '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); + $label .= ''.$langs->trans("Ref").': '.$this->ref; + if ($this->datepaye ? $this->datepaye : $this->date) $label .= '
    '.$langs->trans("Date").': '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); if ($mode == 'withlistofinvoices') { $arraybill = $this->getBillsArray(); if (is_array($arraybill) && count($arraybill) > 0) { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $facturestatic=new Facture($this->db); + $facturestatic = new Facture($this->db); foreach ($arraybill as $billid) { $facturestatic->fetch($billid); - $label .='
    '.$facturestatic->getNomUrl(1).' '.$facturestatic->getLibStatut(2, 1); + $label .= '
    '.$facturestatic->getNomUrl(1).' '.$facturestatic->getLibStatut(2, 1); } } } - $linkclose=''; + $linkclose = ''; if (empty($notooltip)) { - if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { - $label=$langs->trans("ShowMyObject"); - $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"'; + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; } - else $linkclose = ($morecss?' class="'.$morecss.'"':''); + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $url = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$this->id; $linkstart = ''; - $linkend=''; + $linkstart .= $linkclose.'>'; + $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 && $withpicto != 2) $result.= ($this->ref?$this->ref:$this->id); + 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 && $withpicto != 2) $result .= ($this->ref ? $this->ref : $this->id); $result .= $linkend; return $result; @@ -1260,7 +1260,7 @@ class Paiement extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage $langs->load('compta'); /*if ($mode == 0) @@ -1311,7 +1311,7 @@ class Paiement extends CommonObject public function fetch_thirdparty($force_thirdparty_id = 0) { // phpcs:enable - include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; if (empty($force_thirdparty_id)) { diff --git a/htdocs/compta/paiement/list.php b/htdocs/compta/paiement/list.php index b1de388f7ba..c78a010777a 100644 --- a/htdocs/compta/paiement/list.php +++ b/htdocs/compta/paiement/list.php @@ -68,7 +68,7 @@ $search_payment_num=GETPOST('search_payment_num', 'alpha'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -115,7 +115,7 @@ if (GETPOST("orphelins", "alpha")) { // Payments not linked to an invoice. Should not happend. For debug only. $sql = "SELECT p.rowid, p.ref, p.datep as dp, p.amount,"; - $sql.= " p.statut, p.num_paiement,"; + $sql.= " p.statut, p.num_paiement as num_payment,"; $sql.= " c.code as paiement_code"; // Add fields from hooks $parameters=array(); @@ -133,7 +133,7 @@ if (GETPOST("orphelins", "alpha")) else { $sql = "SELECT DISTINCT p.rowid, p.ref, p.datep as dp, p.amount,"; // DISTINCT is to avoid duplicate when there is a link to sales representatives - $sql.= " p.statut, p.num_paiement,"; + $sql.= " p.statut, p.num_paiement as num_payment,"; $sql.= " c.code as paiement_code,"; $sql.= " ba.rowid as bid, ba.ref as bref, ba.label as blabel, ba.number, ba.account_number as account_number, ba.fk_accountancy_journal as accountancy_journal,"; $sql.= " s.rowid as socid, s.nom as name, s.email"; @@ -323,7 +323,7 @@ if ($resql) if (!$i) $totalarray['nbfield']++; // Payment number - print '
    '.$objp->num_paiement.''.$objp->num_payment.'
    '.img_object($langs->trans("ShowPayment"), "payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp), 'day')."$objp->paiement_type $objp->num_paiement$objp->paiement_type $objp->num_payment'.price($objp->amount).''; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index 561120aead6..31e13a9d356 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -108,9 +108,10 @@ if ($action == 'add_payment' || ($action == 'confirm_paiement' && $confirm == 'y $paiement->chid = $chid; $paiement->datepaye = $datepaye; $paiement->amounts = $amounts; // Tableau de montant - $paiement->paiementtype = $_POST["paiementtype"]; - $paiement->num_paiement = $_POST["num_paiement"]; - $paiement->note = $_POST["note"]; + $paiement->paiementtype = GETPOST("paiementtype", 'alphanohtml'); + $paiement->num_payment = GETPOST("num_payment", 'alphanohtml'); + $paiement->note = GETPOST("note", 'none'); + $paiement->note_private = GETPOST("note", 'none'); if (!$error) { @@ -243,7 +244,7 @@ if ($action == 'create') print '
    '.$langs->trans('Numero'); print ' ('.$langs->trans("ChequeOrTransferNumber").')'; print '
    '.$langs->trans("Comments").'
    '; print ''; -print_liste_field_titre("PredefinedGroups", $_SERVER["PHP_SELF"], 'f.thirdparty_code,f.rowid', '', $param, '', $sortfield, $sortorder, 'width200 '); +if ($modecompta == 'BOOKKEEPING') { + print_liste_field_titre("PredefinedGroups", $_SERVER["PHP_SELF"], 'f.thirdparty_code,f.rowid', '', $param, '', $sortfield, $sortorder, 'width200 '); +} else { + print_liste_field_titre("", $_SERVER["PHP_SELF"], '', '', $param, '', $sortfield, $sortorder, 'width200 '); +} print_liste_field_titre(''); if ($modecompta == 'BOOKKEEPING') { @@ -243,7 +246,7 @@ if ($modecompta == 'BOOKKEEPING') $sql .= " AND f.entity = ".$conf->entity; if (!empty($date_start) && !empty($date_end)) $sql .= " AND f.doc_date >= '".$db->idate($date_start)."' AND f.doc_date <= '".$db->idate($date_end)."'"; - $sql .= " GROUP BY pcg_type, pcg_subtype, name, socid"; + $sql .= " GROUP BY pcg_type, name, socid"; $sql .= $db->order($sortfield, $sortorder); $oldpcgtype = ''; diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index c5e142ca7ca..d7f20622a43 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -47,6 +47,11 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); $projectid = (GETPOST('projectid') ? GETPOST('projectid', 'int') : 0); +$dateech = dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), GETPOST('echmonth'), GETPOST('echday'), GETPOST('echyear')); +$dateperiod = dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear')); +$label = GETPOST('label', 'alpha'); +$actioncode = GETPOST('actioncode'); + // Security check $socid = GETPOST('socid', 'int'); if ($user->socid) $socid = $user->socid; @@ -134,10 +139,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') // Add social contribution if ($action == 'add' && $user->rights->tax->charges->creer) { - $dateech = dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), GETPOST('echmonth'), GETPOST('echday'), GETPOST('echyear')); - $dateperiod = dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear')); $amount = price2num(GETPOST('amount')); - $actioncode = GETPOST('actioncode'); if (!$dateech) { @@ -187,8 +189,6 @@ if ($action == 'add' && $user->rights->tax->charges->creer) if ($action == 'update' && !$_POST["cancel"] && $user->rights->tax->charges->creer) { - $dateech = dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), GETPOST('echmonth'), GETPOST('echday'), GETPOST('echyear')); - $dateperiod = dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear')); $amount = price2num(GETPOST('amount')); if (!$dateech) @@ -603,7 +603,7 @@ if ($id > 0) /* * Payments */ - $sql = "SELECT p.rowid, p.num_paiement, datep as dp, p.amount,"; + $sql = "SELECT p.rowid, p.num_paiement as num_payment, datep as dp, p.amount,"; $sql .= " c.code as type_code,c.libelle as paiement_type,"; $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.currency_code as bacurrency_code, ba.fk_accountancy_journal'; $sql .= " FROM ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -647,7 +647,7 @@ if ($id > 0) print ''.img_object($langs->trans("Payment"), "payment").' '.$objp->rowid.''; print '\n"; $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; - print "\n"; + print "\n"; if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index a5279ecbeae..02c15b099b9 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -57,7 +57,7 @@ class PaymentSocialContribution extends CommonObject /** * @deprecated - * @see amount + * @see $amount */ public $total; @@ -69,8 +69,17 @@ class PaymentSocialContribution extends CommonObject */ public $fk_typepaiement; + /** + * @var string + * @deprecated + */ public $num_paiement; + /** + * @var string + */ + public $num_payment; + /** * @var int ID */ @@ -125,7 +134,8 @@ class PaymentSocialContribution extends CommonObject if (isset($this->fk_charge)) $this->fk_charge = (int) $this->fk_charge; if (isset($this->amount)) $this->amount = trim($this->amount); if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); if (isset($this->note)) $this->note = trim($this->note); if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; @@ -149,11 +159,11 @@ class PaymentSocialContribution extends CommonObject if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiementcharge (fk_charge, datec, datep, amount,"; - $sql .= " fk_typepaiement, num_paiement, note, fk_user_creat, fk_bank)"; + $sql .= " fk_typepaiement, num_paiement as num_payment, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; $sql .= " '".$this->db->idate($this->datepaye)."',"; $sql .= " ".$totalamount.","; - $sql .= " ".$this->paiementtype.", '".$this->db->escape($this->num_paiement)."', '".$this->db->escape($this->note)."', ".$user->id.","; + $sql .= " ".$this->paiementtype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note)."', ".$user->id.","; $sql .= " 0)"; $resql = $this->db->query($sql); @@ -231,7 +241,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " t.datep,"; $sql.= " t.amount,"; $sql.= " t.fk_typepaiement,"; - $sql.= " t.num_paiement,"; + $sql.= " t.num_paiement as num_payment,"; $sql.= " t.note,"; $sql.= " t.fk_bank,"; $sql.= " t.fk_user_creat,"; @@ -260,7 +270,8 @@ class PaymentSocialContribution extends CommonObject $this->datep = $this->db->jdate($obj->datep); $this->amount = $obj->amount; $this->fk_typepaiement = $obj->fk_typepaiement; - $this->num_paiement = $obj->num_paiement; + $this->num_paiement = $obj->num_payment; + $this->num_payment = $obj->num_payment; $this->note = $obj->note; $this->fk_bank = $obj->fk_bank; $this->fk_user_creat = $obj->fk_user_creat; @@ -301,7 +312,8 @@ class PaymentSocialContribution extends CommonObject if (isset($this->fk_charge)) $this->fk_charge = (int) $this->fk_charge; if (isset($this->amount)) $this->amount = trim($this->amount); if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); if (isset($this->note)) $this->note = trim($this->note); if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; @@ -511,8 +523,9 @@ class PaymentSocialContribution extends CommonObject $this->datep = ''; $this->amount = ''; $this->fk_typepaiement = ''; - $this->num_paiement = ''; - $this->note = ''; + $this->num_payment = ''; + $this->note_private = ''; + $this->note_public = ''; $this->fk_bank = ''; $this->fk_user_creat = ''; $this->fk_user_modif = ''; diff --git a/htdocs/compta/sociales/document.php b/htdocs/compta/sociales/document.php index 4a714df8bae..2d5d3c48899 100644 --- a/htdocs/compta/sociales/document.php +++ b/htdocs/compta/sociales/document.php @@ -54,7 +54,7 @@ $result = restrictedArea($user, 'tax', $id, 'chargesociales', 'charges'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } diff --git a/htdocs/compta/sociales/list.php b/htdocs/compta/sociales/list.php index d259fb362fd..ca58830a7bb 100644 --- a/htdocs/compta/sociales/list.php +++ b/htdocs/compta/sociales/list.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2016 Frédéric France + * Copyright (C) 2020 Pierre Ardoin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -29,6 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php' require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.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'; // Load translation files required by the page $langs->loadLangs(array('compta', 'banks', 'bills')); @@ -52,11 +54,13 @@ $search_status = GETPOST('search_status', '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_project_ref = GETPOST('search_project_ref', 'alpha'); +$search_project = GETPOST('search_project', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -88,11 +92,13 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_label = ""; $search_amount = ""; $search_status = ''; - $search_typeid = ""; + $search_typeid = ""; $year = ""; $search_day_lim = ''; $search_year_lim = ''; $search_month_lim = ''; + $search_project_ref = ''; + $search_project = ''; $toselect = ''; $search_array_options = array(); } @@ -106,21 +112,25 @@ $form = new Form($db); $formother = new FormOther($db); $formsocialcontrib = new FormSocialContrib($db); $chargesociale_static = new ChargeSociales($db); +if (!empty($conf->projet->enabled)) $projectstatic = new Project($db); llxHeader('', $langs->trans("SocialContributions")); $sql = "SELECT cs.rowid as id, cs.fk_type as type, "; $sql .= " cs.amount, cs.date_ech, cs.libelle as label, cs.paye, cs.periode,"; +if (!empty($conf->projet->enabled)) $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,"; $sql .= " c.libelle as type_label,"; $sql .= " SUM(pc.amount) as alreadypayed"; $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql .= " ".MAIN_DB_PREFIX."chargesociales as cs"; +if (!empty($conf->projet->enabled)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = cs.fk_projet"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; $sql .= " WHERE cs.fk_type = c.id"; $sql .= " AND cs.entity = ".$conf->entity; // Search criteria if ($search_ref) $sql .= " AND cs.rowid=".$db->escape($search_ref); if ($search_label) $sql .= natural_search("cs.libelle", $search_label); +if (!empty($conf->projet->enabled)) if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); if ($search_amount) $sql .= natural_search("cs.amount", $search_amount, 1); if ($search_status != '' && $search_status >= 0) $sql .= " AND cs.paye = ".$db->escape($search_status); $sql .= dolSqlDateFilter("cs.periode", $search_day_lim, $search_month_lim, $search_year_lim); @@ -163,6 +173,7 @@ if ($resql) if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); if ($search_label) $param .= '&search_label='.urlencode($search_label); + if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); if ($search_typeid) $param .= '&search_typeid='.urlencode($search_typeid); if ($search_status != '' && $search_status != '-1') $param .= '&search_status='.urlencode($search_status); @@ -217,6 +228,8 @@ if ($resql) print ''; + // Ref Project + if (!empty($conf->projet->enabled)) print ''; // Date print ''; // Period end date @@ -245,6 +258,7 @@ if ($resql) print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "id", "", $param, "", $sortfield, $sortorder); print_liste_field_titre("Label", $_SERVER["PHP_SELF"], "cs.libelle", "", $param, 'class="left"', $sortfield, $sortorder); print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "type", "", $param, 'class="left"', $sortfield, $sortorder); + if (!empty($conf->projet->enabled)) print_liste_field_titre('ProjectRef', $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "cs.date_ech", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "periode", "", $param, 'align="center"', $sortfield, $sortorder); print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "cs.amount", "", $param, 'class="right"', $sortfield, $sortorder); @@ -262,6 +276,11 @@ if ($resql) $chargesociale_static->ref = $obj->id; $chargesociale_static->label = $obj->label; $chargesociale_static->type_label = $obj->type_label; + if (!empty($conf->projet->enabled)) { + $projectstatic->id = $obj->project_id; + $projectstatic->ref = $obj->project_ref; + $projectstatic->title = $obj->project_label; + } print ''; @@ -277,6 +296,17 @@ if ($resql) print "\n"; if (!$i) $totalarray['nbfield']++; + // Project Ref + if (!empty($conf->projet->enabled)) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Date print ''; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/compta/sociales/payments.php b/htdocs/compta/sociales/payments.php index f89171a082d..5cfa5df06ed 100644 --- a/htdocs/compta/sociales/payments.php +++ b/htdocs/compta/sociales/payments.php @@ -48,7 +48,7 @@ if (!$year && $mode != 'sconly') { $year = date("Y", time()); } $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index 138bff4a525..a1bdfb6678d 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -31,23 +31,23 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page -$langs->loadLangs(array("products","categories","errors",'accountancy')); +$langs->loadLangs(array("products", "categories", "errors", 'accountancy')); // Security pack (data & check) $socid = GETPOST('socid', 'int'); if ($user->socid > 0) $socid = $user->socid; -if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user, 'compta', '', '', 'resultat'); -if (! empty($conf->accounting->enabled)) $result=restrictedArea($user, 'accounting', '', '', 'comptarapport'); +if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat'); +if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') $modecompta = $conf->global->ACCOUNTING_MODE; -if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); +if (GETPOST("modecompta")) $modecompta = GETPOST("modecompta"); -$sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"]; -$sortfield=isset($_GET["sortfield"])?$_GET["sortfield"]:$_POST["sortfield"]; -if (! $sortorder) $sortorder="asc"; -if (! $sortfield) $sortfield="ref"; +$sortorder = isset($_GET["sortorder"]) ? $_GET["sortorder"] : $_POST["sortorder"]; +$sortfield = isset($_GET["sortfield"]) ? $_GET["sortfield"] : $_POST["sortfield"]; +if (!$sortorder) $sortorder = "asc"; +if (!$sortfield) $sortfield = "ref"; // Category $selected_cat = (int) GETPOST('search_categ', 'int'); @@ -58,11 +58,11 @@ if (GETPOST('subcat', 'alpha') === 'yes') { } // product/service $selected_type = GETPOST('search_type', 'int'); -if ($selected_type =='') $selected_type = -1; +if ($selected_type == '') $selected_type = -1; // Date range -$year=GETPOST("year"); -$month=GETPOST("month"); +$year = GETPOST("year"); +$month = GETPOST("month"); $date_startyear = GETPOST("date_startyear"); $date_startmonth = GETPOST("date_startmonth"); $date_startday = GETPOST("date_startday"); @@ -79,76 +79,78 @@ if (empty($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")); +$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"); + $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 + $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) + if (!GETPOST('year') && $month_start > $month_current) { $year_start--; $year_end--; } - $month_end=$month_start-1; - if ($month_end < 1) $month_end=12; + $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); + $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); } + 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); +$tmps = dol_getdate($date_start); $year_start = $tmps['year']; -$tmpe=dol_getdate($date_end); +$tmpe = dol_getdate($date_end); $year_end = $tmpe['year']; $nbofyear = ($year_end - $year_start) + 1; -$commonparams=array(); -$commonparams['modecompta']=$modecompta; -$commonparams['sortorder'] = $sortorder; -$commonparams['sortfield'] = $sortfield; +$commonparams = array(); +if (!empty($modecompta)) $commonparams['modecompta'] = $modecompta; +if (!empty($sortorder)) $commonparams['sortorder'] = $sortorder; +if (!empty($sortfield)) $commonparams['sortfield'] = $sortfield; $headerparams = array(); -$headerparams['date_startyear'] = $date_startyear; -$headerparams['date_startmonth'] = $date_startmonth; -$headerparams['date_startday'] = $date_startday; -$headerparams['date_endyear'] = $date_endyear; -$headerparams['date_endmonth'] = $date_endmonth; -$headerparams['date_endday'] = $date_endday; +if (!empty($date_startyear)) $headerparams['date_startyear'] = $date_startyear; +if (!empty($date_startmonth)) $headerparams['date_startmonth'] = $date_startmonth; +if (!empty($date_startday)) $headerparams['date_startday'] = $date_startday; +if (!empty($date_endyear)) $headerparams['date_endyear'] = $date_endyear; +if (!empty($date_endmonth)) $headerparams['date_endmonth'] = $date_endmonth; +if (!empty($date_endday)) $headerparams['date_endday'] = $date_endday; +if (!empty($year)) $headerparams['year'] = $year; +if (!empty($month)) $headerparams['month'] = $month; $headerparams['q'] = $q; $tableparams = array(); -$tableparams['search_categ'] = $selected_cat; -$tableparams['search_soc'] = $selected_soc; -$tableparams['search_type'] = $selected_type; -$tableparams['subcat'] = ($subcat === true)?'yes':''; +if (!empty($selected_cat)) $tableparams['search_categ'] = $selected_cat; +if (!empty($selected_soc)) $tableparams['search_soc'] = $selected_soc; +if (!empty($selected_type)) $tableparams['search_type'] = $selected_type; +$tableparams['subcat'] = ($subcat === true) ? 'yes' : ''; // Adding common parameters $allparams = array_merge($commonparams, $headerparams, $tableparams); $headerparams = array_merge($commonparams, $headerparams); $tableparams = array_merge($commonparams, $tableparams); -foreach($allparams as $key => $value) { - $paramslink .= '&' . $key . '=' . $value; +foreach ($allparams as $key => $value) { + $paramslink .= '&'.$key.'='.$value; } @@ -158,127 +160,127 @@ foreach($allparams as $key => $value) { llxHeader(); -$form=new Form($db); +$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"; +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("ByProductsAndServices"); - $calcmode=$langs->trans("CalcModeDebt"); +if ($modecompta == "CREANCES-DETTES") { + $name = $langs->trans("Turnover").', '.$langs->trans("ByProductsAndServices"); + $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"); + $description = $langs->trans("RulesCADue"); + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description .= $langs->trans("DepositsAreNotIncluded"); } else { - $description.= $langs->trans("DepositsAreIncluded"); + $description .= $langs->trans("DepositsAreIncluded"); } - $builddate=dol_now(); + $builddate = dol_now(); } -elseif ($modecompta=="RECETTES-DEPENSES") +elseif ($modecompta == "RECETTES-DEPENSES") { - $name=$langs->trans("TurnoverCollected").', '.$langs->trans("ByProductsAndServices"); - $calcmode=$langs->trans("CalcModeEngagement"); + $name = $langs->trans("TurnoverCollected").', '.$langs->trans("ByProductsAndServices"); + $calcmode = $langs->trans("CalcModeEngagement"); //$calcmode.='
    ('.$langs->trans("SeeReportInDueDebtMode",'','').')'; - $description=$langs->trans("RulesCAIn"); - $description.= $langs->trans("DepositsAreIncluded"); + $description = $langs->trans("RulesCAIn"); + $description .= $langs->trans("DepositsAreIncluded"); - $builddate=dol_now(); + $builddate = dol_now(); } -elseif ($modecompta=="BOOKKEEPING") +elseif ($modecompta == "BOOKKEEPING") { } -elseif ($modecompta=="BOOKKEEPINGCOLLECTED") +elseif ($modecompta == "BOOKKEEPINGCOLLECTED") { } -$period=$form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); -if ($date_end == dol_time_plus_duree($date_start, 1, 'y') - 1) $periodlink=''.img_previous().''.img_next().''; +$period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); +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') +if (!empty($conf->accounting->enabled) && $modecompta != 'BOOKKEEPING') { print info_admin($langs->trans("WarningReportNotReliable"), 0, 0, 1); } -$name=array(); +$name = array(); // SQL request -$catotal=0; -$catotal_ht=0; -$qtytotal=0; +$catotal = 0; +$catotal_ht = 0; +$qtytotal = 0; 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"; - if($selected_soc > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc ON (soc.rowid = f.fk_soc)"; - $sql.= ",".MAIN_DB_PREFIX."facturedet as l"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product = p.rowid"; + $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"; + if ($selected_soc > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as soc ON (soc.rowid = f.fk_soc)"; + $sql .= ",".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 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"; } elseif ($selected_cat) // Into a specific category { - $sql.= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp"; + $sql .= ", ".MAIN_DB_PREFIX."categorie as c, ".MAIN_DB_PREFIX."categorie_product as cp"; } - $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)"; + $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)"; } else { - $sql.= " AND f.type IN (0,1,2,3,5)"; + $sql .= " AND f.type IN (0,1,2,3,5)"; } if ($date_start && $date_end) { - $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; } - if ($selected_type >=0) + if ($selected_type >= 0) { - $sql.= " AND l.product_type = ".$selected_type; + $sql .= " AND l.product_type = ".$selected_type; } if ($selected_cat === -2) // Without any category { - $sql.=" AND cp.fk_product is null"; + $sql .= " AND cp.fk_product is null"; } elseif ($selected_cat) { // Into a specific category - $sql.= " AND (c.rowid = ".$selected_cat; - if ($subcat) $sql.=" OR c.fk_parent = " . $selected_cat; - $sql.= ")"; - $sql.= " AND cp.fk_categorie = c.rowid AND cp.fk_product = p.rowid"; + $sql .= " AND (c.rowid = ".$selected_cat; + if ($subcat) $sql .= " OR c.fk_parent = ".$selected_cat; + $sql .= ")"; + $sql .= " AND cp.fk_categorie = c.rowid AND cp.fk_product = p.rowid"; } - if($selected_soc > 0) $sql .= " AND soc.rowid=".$selected_soc; - $sql.= " AND f.entity IN (".getEntity('invoice').")"; - $sql.= " GROUP BY p.rowid, p.ref, p.label, p.fk_product_type"; - $sql.= $db->order($sortfield, $sortorder); + if ($selected_soc > 0) $sql .= " AND soc.rowid=".$selected_soc; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; + $sql .= " GROUP BY p.rowid, p.ref, p.label, p.fk_product_type"; + $sql .= $db->order($sortfield, $sortorder); dol_syslog("cabyprodserv", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $i=0; + $i = 0; while ($i < $num) { $obj = $db->fetch_object($result); $amount_ht[$obj->rowid] = $obj->amount; $amount[$obj->rowid] = $obj->amount_ttc; $qty[$obj->rowid] = $obj->qty; - $name[$obj->rowid] = $obj->ref . ' - ' . $obj->label; + $name[$obj->rowid] = $obj->ref.' - '.$obj->label; $type[$obj->rowid] = $obj->product_type; - $catotal_ht+=$obj->amount; - $catotal+=$obj->amount_ttc; - $qtytotal+=$obj->qty; + $catotal_ht += $obj->amount; + $catotal += $obj->amount_ttc; + $qtytotal += $obj->qty; $i++; } } else { @@ -286,25 +288,25 @@ if ($modecompta == 'CREANCES-DETTES') } // Show Array - $i=0; + $i = 0; print ''; // Extra parameters management - foreach($headerparams as $key => $value) + foreach ($headerparams as $key => $value) { print ''; } - $moreforfilter=''; + $moreforfilter = ''; print '
    '; - print '
    '.dol_print_date($db->jdate($objp->dp), 'day')."".$labeltype.' '.$objp->num_paiement."".$labeltype.' '.$objp->num_payment."'; $formsocialcontrib->select_type_socialcontrib($search_typeid, 'search_typeid', 1, 0, 0, 'maxwidth100onsmartphone'); print ' 
    ".$obj->type_label."'; + if ($obj->project_id > 0) + { + print $projectstatic->getNomUrl(1); + } + print ''.dol_print_date($db->jdate($obj->date_ech), 'day').'
    '."\n"; + print '
    '."\n"; // Category filter print ''; print ''; print '\n"; if (count($name)) { - foreach($name as $key=>$value) { + foreach ($name as $key=>$value) { print ''; // Product print "\n"; @@ -463,7 +465,7 @@ if ($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("TurnoverPerProductInCommitmentAccountingNotRelevant") . '
    '; + print '
    '.$langs->trans("TurnoverPerProductInCommitmentAccountingNotRelevant").'
    '; } // End of page diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 684ef337fcd..9be5607b62d 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -407,7 +407,7 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) print ""; for ($annee = $year_start ; $annee <= $year_end ; $annee++) { - $casenow = dol_print_date(mktime(),"%Y-%m"); + $casenow = dol_print_date(dol_now(),"%Y-%m"); $case = dol_print_date(dol_mktime(1,1,1,$mois,1,$annee),"%Y-%m"); $caseprev = dol_print_date(dol_mktime(1,1,1,$mois,1,$annee-1),"%Y-%m"); diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index 5a64728029a..86fb598fb8b 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -279,7 +279,7 @@ if ($action == 'create') if (! empty($conf->banque->enabled)) { print ''; } diff --git a/htdocs/compta/tva/document.php b/htdocs/compta/tva/document.php index 7f860491a8d..037e6baa5c3 100644 --- a/htdocs/compta/tva/document.php +++ b/htdocs/compta/tva/document.php @@ -55,7 +55,7 @@ $result = restrictedArea($user, 'tax', '', 'vat', 'charges'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } @@ -70,8 +70,8 @@ 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'; +$upload_dir = $conf->tax->dir_output.'/vat/'.dol_sanitizeFileName($object->ref); +$modulepart = 'tax-vat'; /* @@ -144,7 +144,6 @@ if ($object->id) dol_fiche_end(); - $modulepart = 'tax'; $permission = $user->rights->tax->charges->creer; $permtoedit = $user->rights->fournisseur->facture->creer; $param = '&id='.$object->id; diff --git a/htdocs/compta/tva/list.php b/htdocs/compta/tva/list.php index 35492d19821..35c5dc2c052 100644 --- a/htdocs/compta/tva/list.php +++ b/htdocs/compta/tva/list.php @@ -53,7 +53,7 @@ $year = GETPOST("year", "int"); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index 24d49040c13..d07b84e1e36 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -90,7 +90,7 @@ $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'ro $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index f1491d73bf4..73862b65b2e 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -218,6 +218,8 @@ if (empty($reshook)) $object->priv = GETPOST("priv", 'int'); $object->note_public = GETPOST("note_public", 'none'); $object->note_private = GETPOST("note_private", 'none'); + $object->roles = GETPOST("roles", 'array'); + $object->statut = 1; //Defult status to Actif // Note: Correct date should be completed with location to have exact GM time of birth. @@ -552,6 +554,8 @@ else setEventMessages($object->error, $object->errors, 'errors'); } + $object->fetchRoles(); + // Show tabs $head = contact_prepare_head($object); @@ -578,7 +582,7 @@ else $object->country = $tmparray['label']; } - $title = $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); + $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); $linkback = ''; print load_fiche_titre($title, $linkback, 'address'); @@ -652,7 +656,7 @@ else // Civility print ''; print ''; @@ -681,13 +685,13 @@ else if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->zip)) == 0) $object->zip = $objsoc->zip; // Predefined with third party if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->town)) == 0) $object->town = $objsoc->town; // Predefined with third party print ''; // Country print ''; @@ -705,7 +709,7 @@ else if ($object->country_id) { - print $formcompany->select_state(GETPOST("state_id", 'alpha') ?GETPOST("state_id", 'alpha') : $object->state_id, $object->country_code, 'state_id'); + print $formcompany->select_state(GETPOST("state_id", 'alpha') ? GETPOST("state_id", 'alpha') : $object->state_id, $object->country_code, 'state_id'); } else { @@ -719,23 +723,23 @@ else // Phone / Fax print ''; - print ''; + print ''; if ($conf->browser->layout == 'phone') print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; if ($conf->browser->layout == 'phone') print ''; print ''; - print ''; + print ''; print ''; if (($objsoc->typent_code == 'TE_PRIVATE' || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->email)) == 0) $object->email = $objsoc->email; // Predefined with third party // Email print ''; - print ''; + print ''; print ''; if (!empty($conf->mailing->enabled)) @@ -755,7 +759,7 @@ else print ''; print ''; - print ''; + print ''; print ''; } print ''; diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index b1eb83eebdb..8d880226ff4 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -64,7 +64,7 @@ class Contact extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>15), 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20), @@ -314,9 +314,9 @@ class Contact extends CommonObject // Clean parameters $this->lastname = $this->lastname ?trim($this->lastname) : trim($this->name); $this->firstname = trim($this->firstname); - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords($this->lastname); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords(strtolower($this->lastname)); if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = strtoupper($this->lastname); - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords($this->firstname); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords(strtolower($this->firstname)); if (empty($this->socid)) $this->socid = 0; 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 @@ -358,7 +358,7 @@ class Contact extends CommonObject if (!$error) { - $result = $this->update($this->id, $user, 1, 'add'); + $result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ... if ($result < 0) { $error++; @@ -427,9 +427,9 @@ class Contact extends CommonObject $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity); // Clean parameters - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords($this->lastname); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->lastname = ucwords(strtolower($this->lastname)); if (!empty($conf->global->MAIN_ALL_TO_UPPER)) $this->lastname = strtoupper($this->lastname); - if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords($this->firstname); + if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->firstname = ucwords(strtolower($this->firstname)); $this->lastname = trim($this->lastname) ?trim($this->lastname) : trim($this->lastname); $this->firstname = trim($this->firstname); @@ -802,20 +802,19 @@ class Contact extends CommonObject /** - * Load object contact + * Load object contact. * - * @param int $id id du contact - * @param User $user Utilisateur (abonnes aux alertes) qui veut les alertes de ce contact - * @param string $ref_ext External reference, not given by Dolibarr - * @param string $email Email - * @return int -1 if KO, 0 if OK but not found, 1 if OK + * @param int $id Id of contact + * @param User $user Load also alerts of this user (subscribing to alerts) that want alerts about this contact + * @param string $ref_ext External reference, not given by Dolibarr + * @param string $email Email + * @param int $loadalsoroles Load also roles + * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found. */ - public function fetch($id, $user = null, $ref_ext = '', $email = '') + public function fetch($id, $user = null, $ref_ext = '', $email = '', $loadalsoroles = 0) { global $langs; - $langs->load("dict"); - dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG); if (empty($id) && empty($ref_ext) && empty($email)) @@ -824,7 +823,7 @@ class Contact extends CommonObject return -1; } - $langs->load("companies"); + $langs->loadLangs(array("dict", "companies")); $sql = "SELECT c.rowid, c.entity, c.fk_soc, c.ref_ext, c.civility as civility_code, c.lastname, c.firstname,"; $sql .= " c.address, c.statut, c.zip, c.town,"; @@ -861,7 +860,15 @@ class Contact extends CommonObject $resql = $this->db->query($sql); if ($resql) { - if ($this->db->num_rows($resql)) + $num = $this->db->num_rows($resql); + if ($num > 1) + { + $this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.'; + dol_syslog($this->error, LOG_ERR); + + return 2; + } + elseif ($num) // $num = 1 { $obj = $this->db->fetch_object($resql); @@ -942,7 +949,11 @@ class Contact extends CommonObject return -1; } - // Charge alertes du user + // Retreive all extrafield + // fetch optionals attributes and labels + $this->fetch_optionals(); + + // Load also alerts of this user if ($user) { $sql = "SELECT fk_user"; @@ -967,13 +978,12 @@ class Contact extends CommonObject } } - // Retreive all extrafield - // fetch optionals attributes and labels - $this->fetch_optionals(); - - $resultRole = $this->fetchRoles(); - if ($resultRole < 0) { - return $resultRole; + // Load also roles of this address + if ($loadalsoroles) { + $resultRole = $this->fetchRoles(); + if ($resultRole < 0) { + return $resultRole; + } } return 1; @@ -1007,7 +1017,7 @@ class Contact extends CommonObject { $this->gender = 'man'; } - elseif(in_array($this->civility_id, array('MME','MLE')) || in_array($this->civility_code, array('MME','MLE'))) + elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) { $this->gender = 'woman'; } @@ -1276,9 +1286,16 @@ class Contact extends CommonObject { global $conf, $langs, $hookmanager; - $result = ''; + $result = ''; $label = ''; - $label = ''.$langs->trans("ShowContact").''; + if (!empty($this->photo) && class_exists('Form')) + { + $label .= '
    '; + $label .= Form::showphoto('contact', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip. + $label .= '
    '; + } + + $label .= ''.$langs->trans("ShowContact").''; $label .= '
    '.$langs->trans("Name").': '.$this->getFullName($langs); //if ($this->civility_id) $label.= '
    ' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code if (!empty($this->poste)) $label .= '
    '.$langs->trans("Poste").': '.$this->poste; @@ -1580,7 +1597,7 @@ class Contact extends CommonObject } /** - * Fetch Role for a contact + * Fetch Roles for a contact * * @return float|int * @throws Exception @@ -1592,14 +1609,14 @@ class Contact extends CommonObject $num = 0; $sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle, sc.rowid as contactroleid"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc "; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_contact as tc"; $sql .= " ON tc.rowid = sc.fk_c_type_contact"; $sql .= " AND sc.fk_socpeople = ".$this->id; $sql .= " AND tc.source = 'external' AND tc.active=1"; $sql .= " AND sc.entity IN (".getEntity('societe').')'; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $this->roles = array(); $resql = $this->db->query($sql); @@ -1636,6 +1653,10 @@ class Contact extends CommonObject { $tab = array(); + if ($element == 'action') { + $element = 'agenda'; + } + $sql = "SELECT sc.fk_socpeople as id, sc.fk_c_type_contact"; $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; $sql .= ", ".MAIN_DB_PREFIX."societe_contacts sc"; @@ -1644,7 +1665,7 @@ class Contact extends CommonObject $sql .= " AND tc.element='".$element."'"; $sql .= " AND tc.active=1"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1684,7 +1705,7 @@ class Contact extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".$this->socid." AND fk_socpeople=".$this->id; ; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if (!$result) { $this->errors[] = $this->db->lasterror().' sql='.$sql; @@ -1704,7 +1725,7 @@ class Contact extends CommonObject $sql .= $valRoles." , "; $sql .= $this->id; $sql .= ")"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if (!$result) diff --git a/htdocs/contact/consumption.php b/htdocs/contact/consumption.php index 458fdae07b1..f27903f559e 100644 --- a/htdocs/contact/consumption.php +++ b/htdocs/contact/consumption.php @@ -45,7 +45,7 @@ $socid = $object->thirdparty->id; $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 8533cb13feb..0825c77a61f 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -57,7 +57,7 @@ $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'ro // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 1d0c3839f4f..d7a8d025e21 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -103,12 +103,12 @@ $view = GETPOST("view", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $userid = GETPOST('userid', 'int'); $begin = GETPOST('begin'); if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "p.lastname"; -if (empty($page) || $page < 0) { $page = 0; } +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } $offset = $limit * $page; $titre = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); @@ -290,7 +290,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql .= " p.rowid, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.no_email,"; -$sql .= " p.socialnetworks,"; +$sql .= " p.socialnetworks, p.photo,"; $sql .= " p.phone as phone_pro, p.phone_mobile, p.phone_perso, p.fax, p.fk_pays, p.priv, p.datec as date_creation, p.tms as date_update,"; $sql .= " co.label as country, co.code as country_code"; // Add fields from extrafields @@ -497,11 +497,11 @@ print ''; print ''; print ''; print ''; -print ''; +//print ''; print ''; print ''; -print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'address', 0, $newcardbutton, '', $limit); +print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'address', 0, $newcardbutton, '', $limit, 0, 0, 1); $topicmail = "Information"; $modelmail = "contact"; @@ -786,7 +786,6 @@ while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); - print ''; $arraysocialnetworks = (array) json_decode($obj->socialnetworks, true); $contactstatic->lastname = $obj->lastname; $contactstatic->firstname = ''; @@ -802,6 +801,9 @@ while ($i < min($num, $limit)) $contactstatic->socialnetworks = $arraysocialnetworks; $contactstatic->country = $obj->country; $contactstatic->country_code = $obj->country_code; + $contactstatic->photo = $obj->photo; + + print ''; // ID if (!empty($arrayfields['p.rowid']['checked'])) diff --git a/htdocs/contrat/agenda.php b/htdocs/contrat/agenda.php index 6b754dc9551..1fb3f572078 100644 --- a/htdocs/contrat/agenda.php +++ b/htdocs/contrat/agenda.php @@ -58,7 +58,7 @@ $result = restrictedArea($user, 'contrat', $id, ''); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 1fc63769af3..4e0e5cb5865 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -1704,7 +1704,7 @@ else if (is_array($extralabelslines) && count($extralabelslines) > 0) { $line = new ContratLigne($db); $line->fetch_optionals($objp->rowid); - print $line->showOptionals($extrafields, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); + print $line->showOptionals($extrafields, 'view', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', 1); } } // Line in mode update @@ -1794,7 +1794,7 @@ else if (is_array($extralabelslines) && count($extralabelslines) > 0) { $line = new ContratLigne($db); $line->fetch_optionals($objp->rowid); - print $line->showOptionals($extrafields, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', empty($conf->global->MAIN_EXTRAFIELDS_IN_ONE_TD) ? 0 : 1); + print $line->showOptionals($extrafields, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', 1); } } diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php index 9d201d6fef1..ecd03ade1a6 100644 --- a/htdocs/contrat/class/api_contracts.class.php +++ b/htdocs/contrat/class/api_contracts.class.php @@ -99,7 +99,8 @@ class Contracts extends DolibarrApi * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" * @return array Array of contract objects * - * @throws RestException + * @throws RestException 404 Not found + * @throws RestException 503 Error */ public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') { @@ -439,8 +440,9 @@ class Contracts extends DolibarrApi * @url DELETE {id}/lines/{lineid} * * @return int - * @throws 401 - * @throws 404 + * + * @throws RestException 401 + * @throws RestException 404 */ public function deleteLine($id, $lineid) { diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 1f77e1905cf..0aee2ed876d 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -225,7 +225,6 @@ class Contrat extends CommonObject 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40), 'date_contrat' =>array('type'=>'datetime', 'label'=>'Date contrat', 'enabled'=>1, 'visible'=>-1, 'position'=>45), - 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed')), 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70), 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk projet', 'enabled'=>1, 'visible'=>-1, 'position'=>75), 'fk_commercial_signature' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk commercial signature', 'enabled'=>1, 'visible'=>-1, 'position'=>80), @@ -239,6 +238,7 @@ class Contrat extends CommonObject 'ref_customer' =>array('type'=>'varchar(50)', 'label'=>'Ref customer', 'enabled'=>1, 'visible'=>-1, 'position'=>130), 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135), 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>140), + 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed')) ); // END MODULEBUILDER PROPERTIES @@ -517,7 +517,7 @@ class Contrat extends CommonObject { $num = $this->ref; } - $this->newref = $num; + $this->newref = dol_sanitizeFileName($num); if ($num) { @@ -2754,8 +2754,8 @@ class ContratLigne extends CommonObjectLine /** * Return label of this contract line status * - * @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 + * @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 */ public function getLibStatut($mode) { @@ -2767,10 +2767,10 @@ class ContratLigne extends CommonObjectLine * Return label of a contract line status * * @param int $status Id status - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto * @param int $expired 0=Not expired, 1=Expired, -1=Both or unknown * @param string $moreatt More attribute - * @return string Libelle + * @return string Label of status */ public static function LibStatut($status, $mode, $expired = -1, $moreatt = '') { diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index aae50630eb7..cb350c61b51 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -57,7 +57,7 @@ $result = restrictedArea($user, 'contrat', $id); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 6dd6fc56e17..1061d47a888 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -39,7 +39,7 @@ $langs->loadLangs(array('products', 'companies', 'contracts')); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $statut = GETPOST('statut') ?GETPOST('statut') : 1; @@ -209,10 +209,10 @@ if (!empty($conf->use_javascript_ajax)) include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphstatus'); print $dolgraph->show($total ? 0 : 1); @@ -363,10 +363,10 @@ if ($result) print ''; print ''; //print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print "\n"; $i++; } diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 328507f6722..09dfe2692b8 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -74,7 +74,7 @@ $optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -705,9 +705,7 @@ while ($i < min($num, $limit)) $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 3) { // We print only number - print ''; print $nbofsalesrepresentative; - print ''; } elseif ($nbofsalesrepresentative > 0) { @@ -741,7 +739,7 @@ while ($i < min($num, $limit)) // Date if (!empty($arrayfields['c.date_contrat']['checked'])) { - print ''; + print ''; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 952a286d773..c8a6c321b6e 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -38,7 +38,7 @@ $langs->loadLangs(array('products', 'contracts', 'companies')); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/contrat/tpl/linkedobjectblock.tpl.php b/htdocs/contrat/tpl/linkedobjectblock.tpl.php index b7ec9574ccb..b200baef726 100644 --- a/htdocs/contrat/tpl/linkedobjectblock.tpl.php +++ b/htdocs/contrat/tpl/linkedobjectblock.tpl.php @@ -63,7 +63,7 @@ foreach($linkedObjectBlock as $key => $objectlink) echo price($totalcontrat); } ?> - + fields[$key]['type'])) { $value = price2num(GETPOST($key, 'none')); // To fix decimal separator according to lang setup } else { - $value = GETPOST($key, 'alpha'); + $value = GETPOST($key, 'alphanohtml'); } if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value = ''; // This is an implicit foreign key field if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') $value = ''; // This is an explicit foreign key field @@ -128,6 +128,13 @@ if ($action == 'update' && !empty($permissiontoadd)) if ($object->fields[$key]['type'] == 'duration') { if (!GETPOSTISSET($key.'hour') || !GETPOSTISSET($key.'min')) continue; // The field was not submited to be edited } + elseif ($object->fields[$key]['type'] == 'boolean') { + if (!GETPOSTISSET($key)) { + $object->$key = 0; // use 0 instead null if the field is defined as not null + continue; + } + } + else { if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index ca2499ab145..bb5a7516fb2 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -23,18 +23,18 @@ * \brief Code for actions on extrafields admin pages */ -$maxsizestring=255; -$maxsizeint=10; -$mesg=array(); +$maxsizestring = 255; +$maxsizeint = 10; +$mesg = array(); -$extrasize=GETPOST('size', 'intcomma'); -$type=GETPOST('type', 'alpha'); -$param=GETPOST('param', 'alpha'); +$extrasize = GETPOST('size', 'intcomma'); +$type = GETPOST('type', 'alpha'); +$param = GETPOST('param', 'alpha'); -if ($type=='double' && strpos($extrasize, ',')===false) $extrasize='24,8'; -if ($type=='date') $extrasize=''; -if ($type=='datetime') $extrasize=''; -if ($type=='select') $extrasize=''; +if ($type == 'double' && strpos($extrasize, ',') === false) $extrasize = '24,8'; +if ($type == 'date') $extrasize = ''; +if ($type == 'datetime') $extrasize = ''; +if ($type == 'select') $extrasize = ''; // Add attribute @@ -43,83 +43,83 @@ if ($action == 'add') if ($_POST["button"] != $langs->trans("Cancel")) { // Check values - if (! $type) + if (!$type) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); + $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'create'; } - if ($type=='varchar' && $extrasize <= 0) + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); + $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type=='varchar' && $extrasize > $maxsizestring) + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); + $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'create'; } - if ($type=='int' && $extrasize > $maxsizeint) + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); + $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'create'; } - if ($type=='select' && !$param) + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForSelectType"); + $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'create'; } - if ($type=='sellist' && !$param) + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForSelectListType"); + $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'create'; } - if ($type=='checkbox' && !$param) + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForCheckBoxType"); + $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'create'; } - if ($type=='link' && !$param) + if ($type == 'link' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForLinkType"); + $mesg[] = $langs->trans("ErrorNoValueForLinkType"); $action = 'create'; } - if ($type=='radio' && !$param) + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForRadioType"); + $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'create'; } - if ((($type=='radio') || ($type=='checkbox')) && $param) + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach($parameters_array as $param_ligne) + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { if (preg_match_all('/,/', $param_ligne, $matches)) { - if (count($matches[0])>1) { + if (count($matches[0]) > 1) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorBadFormatValueList", $param_ligne); + $mesg[] = $langs->trans("ErrorBadFormatValueList", $param_ligne); $action = 'create'; } } @@ -127,14 +127,14 @@ if ($action == 'add') { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorBadFormatValueList", $param_ligne); + $mesg[] = $langs->trans("ErrorBadFormatValueList", $param_ligne); $action = 'create'; } } } } - if (! $error) + if (!$error) { // attrname must be alphabetical and lower case only if (isset($_POST["attrname"]) && preg_match("/^[a-z0-9-_]+$/", $_POST['attrname']) && !is_numeric($_POST["attrname"])) @@ -144,8 +144,8 @@ if ($action == 'add') $parameters = $param; $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression - if ($type=='sellist') { - foreach($parameters_array as $param_ligne) + if ($type == 'sellist') { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } @@ -153,37 +153,38 @@ if ($action == 'add') else { //Esle it's separated key/value and coma list - foreach($parameters_array as $param_ligne) + foreach ($parameters_array as $param_ligne) { - list($key,$value) = explode(',', $param_ligne); + list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } } // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility=3; + if ($type == 'separate') $visibility = 3; - $result=$extrafields->addExtraField( + $result = $extrafields->addExtraField( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), $type, GETPOST('pos', 'int'), $extrasize, $elementtype, - (GETPOST('unique', 'alpha')?1:0), - (GETPOST('required', 'alpha')?1:0), + (GETPOST('unique', 'alpha') ? 1 : 0), + (GETPOST('required', 'alpha') ? 1 : 0), $default_value, $params, - (GETPOST('alwayseditable', 'alpha')?1:0), - (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), + (GETPOST('alwayseditable', 'alpha') ? 1 : 0), + (GETPOST('perms', 'alpha') ?GETPOST('perms', 'alpha') : ''), $visibility, GETPOST('help', 'alpha'), GETPOST('computed_value', 'alpha'), - (GETPOST('entitycurrentorall', 'alpha')?0:''), + (GETPOST('entitycurrentorall', 'alpha') ? 0 : ''), GETPOST('langfile', 'alpha'), 1, - (GETPOST('totalizable', 'alpha')?1:0) + (GETPOST('totalizable', 'alpha') ? 1 : 0), + GETPOST('printable', 'alpha') ); if ($result > 0) { @@ -194,7 +195,7 @@ if ($action == 'add') else { $error++; - $mesg=$extrafields->error; + $mesg = $extrafields->error; setEventMessages($mesg, null, 'errors'); } } @@ -202,7 +203,7 @@ if ($action == 'add') { $error++; $langs->load("errors"); - $mesg=$langs->trans("ErrorFieldCanNotContainSpecialNorUpperCharacters", $langs->transnoentities("AttributeCode")); + $mesg = $langs->trans("ErrorFieldCanNotContainSpecialNorUpperCharacters", $langs->transnoentities("AttributeCode")); setEventMessages($mesg, null, 'errors'); $action = 'create'; } @@ -220,76 +221,76 @@ if ($action == 'update') if ($_POST["button"] != $langs->trans("Cancel")) { // Check values - if (! $type) + if (!$type) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); + $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'edit'; } - if ($type=='varchar' && $extrasize <= 0) + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); + $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type=='varchar' && $extrasize > $maxsizestring) + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); + $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'edit'; } - if ($type=='int' && $extrasize > $maxsizeint) + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); + $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'edit'; } - if ($type=='select' && !$param) + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForSelectType"); + $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'edit'; } - if ($type=='sellist' && !$param) + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForSelectListType"); + $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'edit'; } - if ($type=='checkbox' && !$param) + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForCheckBoxType"); + $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'edit'; } - if ($type=='radio' && !$param) + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorNoValueForRadioType"); + $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'edit'; } - if ((($type=='radio') || ($type=='checkbox')) && $param) + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach($parameters_array as $param_ligne) + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { if (preg_match_all('/,/', $param_ligne, $matches)) { - if (count($matches[0])>1) { + if (count($matches[0]) > 1) { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorBadFormatValueList", $param_ligne); + $mesg[] = $langs->trans("ErrorBadFormatValueList", $param_ligne); $action = 'edit'; } } @@ -297,14 +298,14 @@ if ($action == 'update') { $error++; $langs->load("errors"); - $mesg[]=$langs->trans("ErrorBadFormatValueList", $param_ligne); + $mesg[] = $langs->trans("ErrorBadFormatValueList", $param_ligne); $action = 'edit'; } } } } - if (! $error) + if (!$error) { if (isset($_POST["attrname"]) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $_POST['attrname'])) { @@ -313,8 +314,8 @@ if ($action == 'update') $parameters = $param; $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression - if ($type=='sellist') { - foreach($parameters_array as $param_ligne) + if ($type == 'sellist') { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } @@ -322,37 +323,38 @@ if ($action == 'update') else { //Esle it's separated key/value and coma list - foreach($parameters_array as $param_ligne) + foreach ($parameters_array as $param_ligne) { - list($key,$value) = explode(',', $param_ligne); + list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } } // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility=3; + if ($type == 'separate') $visibility = 3; - $result=$extrafields->update( + $result = $extrafields->update( GETPOST('attrname', 'alpha'), GETPOST('label', 'alpha'), $type, $extrasize, $elementtype, - (GETPOST('unique', 'alpha')?1:0), - (GETPOST('required', 'alpha')?1:0), + (GETPOST('unique', 'alpha') ? 1 : 0), + (GETPOST('required', 'alpha') ? 1 : 0), $pos, $params, - (GETPOST('alwayseditable', 'alpha')?1:0), - (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), + (GETPOST('alwayseditable', 'alpha') ? 1 : 0), + (GETPOST('perms', 'alpha') ?GETPOST('perms', 'alpha') : ''), $visibility, GETPOST('help', 'alpha'), GETPOST('default_value', 'alpha'), GETPOST('computed_value', 'alpha'), - (GETPOST('entitycurrentorall', 'alpha')?0:''), + (GETPOST('entitycurrentorall', 'alpha') ? 0 : ''), GETPOST('langfile'), 1, - (GETPOST('totalizable', 'alpha')?1:0) + (GETPOST('totalizable', 'alpha') ? 1 : 0), + GETPOST('printable', 'alpha') ); if ($result > 0) { @@ -363,7 +365,7 @@ if ($action == 'update') else { $error++; - $mesg=$extrafields->error; + $mesg = $extrafields->error; setEventMessages($mesg, null, 'errors'); } } @@ -371,7 +373,7 @@ if ($action == 'update') { $error++; $langs->load("errors"); - $mesg=$langs->trans("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("AttributeCode")); + $mesg = $langs->trans("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("AttributeCode")); setEventMessages($mesg, null, 'errors'); } } @@ -385,20 +387,20 @@ if ($action == 'update') // Delete attribute if ($action == 'delete') { - if(isset($_GET["attrname"]) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $_GET["attrname"])) + if (isset($_GET["attrname"]) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $_GET["attrname"])) { - $result=$extrafields->delete($_GET["attrname"], $elementtype); + $result = $extrafields->delete($_GET["attrname"], $elementtype); if ($result >= 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } - else $mesg=$extrafields->error; + else $mesg = $extrafields->error; } else { $error++; $langs->load("errors"); - $mesg=$langs->trans("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("AttributeCode")); + $mesg = $langs->trans("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("AttributeCode")); } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 4a00412f800..17e063244df 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -691,11 +691,11 @@ if ($massaction == 'confirm_createbills') // Create bills from orders for ($i = 0; $i < $num; $i++) { - $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); + $desc = ($lines[$i]->desc ? $lines[$i]->desc : ''); // If we build one invoice for several order, we must put the invoice of order on the line if (!empty($createbills_onebythird)) { - $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day', $langs)); + $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day')); } if ($lines[$i]->subprice < 0) @@ -1215,6 +1215,8 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio $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')) && $permissiontodelete) { diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index 9ade3c148a4..313375d1aa1 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -68,6 +68,7 @@ if ($action == 'setModuleOptions') { foreach ($_POST as $key => $val) { + $reg = array(); if (preg_match('/^param(\d*)$/', $key, $reg)) // Works for POST['param'], POST['param1'], POST['param2'], ... { $param = GETPOST("param".$reg[1], 'alpha'); diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index e5aa9cbe4bb..a9a7df300c3 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -48,7 +48,7 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); - $page = GETPOST("page", 'int'); + $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/core/boxes/box_boms.php b/htdocs/core/boxes/box_boms.php index 8f27ff739e0..44102f0aab1 100644 --- a/htdocs/core/boxes/box_boms.php +++ b/htdocs/core/boxes/box_boms.php @@ -86,7 +86,7 @@ class box_boms extends ModeleBoxes if ($user->rights->bom->read) { - $sql = "SELECT p.ref as product_ref"; + $sql = "SELECT p.ref as product_ref, p.tobuy, p.tosell"; $sql.= ", c.rowid"; $sql.= ", c.date_creation"; $sql.= ", c.tms"; @@ -109,11 +109,15 @@ class box_boms extends ModeleBoxes while ($line < $num) { $objp = $this->db->fetch_object($result); $datem=$this->db->jdate($objp->tms); + $bomstatic->id = $objp->rowid; $bomstatic->ref = $objp->ref; $bomstatic->id = $objp->socid; $bomstatic->status = $objp->status; + $productstatic->ref = $objp->product_ref; + $productstatic->status = $objp->tobuy; + $productstatic->status_buy = $objp->tosell; $this->info_box_contents[$line][] = array( 'td' => 'class="nowraponall"', diff --git a/htdocs/core/boxes/box_clients.php b/htdocs/core/boxes/box_clients.php index feb7564cdaf..d82a4aee71e 100644 --- a/htdocs/core/boxes/box_clients.php +++ b/htdocs/core/boxes/box_clients.php @@ -32,9 +32,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; */ class box_clients extends ModeleBoxes { - public $boxcode="lastcustomers"; - public $boximg="object_company"; - public $boxlabel="BoxLastCustomers"; + public $boxcode = "lastcustomers"; + public $boximg = "object_company"; + public $boxlabel = "BoxLastCustomers"; public $depends = array("societe"); /** @@ -61,9 +61,9 @@ class box_clients extends ModeleBoxes $this->db = $db; // disable box for such cases - if (! empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $this->enabled=0; // disabled by this option + if (!empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $this->enabled = 0; // disabled by this option - $this->hidden = ! ($user->rights->societe->lire && empty($user->socid)); + $this->hidden = !($user->rights->societe->lire && empty($user->socid)); } /** @@ -77,33 +77,33 @@ class box_clients extends ModeleBoxes global $user, $langs, $conf; $langs->load("boxes"); - $this->max=$max; + $this->max = $max; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $thirdpartystatic=new Societe($this->db); + $thirdpartystatic = new Societe($this->db); $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedCustomers", $max)); if ($user->rights->societe->lire) { $sql = "SELECT s.nom as name, s.rowid as socid"; - $sql.= ", s.code_client"; - $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->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.client IN (1, 3)"; - $sql.= " AND s.entity IN (".getEntity('societe').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($user->socid) $sql.= " AND s.rowid = $user->socid"; - $sql.= " ORDER BY s.tms DESC"; - $sql.= $this->db->plimit($max, 0); + $sql .= ", s.code_client"; + $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, s.entity"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE s.client IN (1, 3)"; + $sql .= " AND s.entity IN (".getEntity('societe').")"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = $user->socid"; + $sql .= " ORDER BY s.tms DESC"; + $sql .= $this->db->plimit($max, 0); dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); $result = $this->db->query($sql); @@ -115,8 +115,8 @@ class box_clients extends ModeleBoxes while ($line < $num) { $objp = $this->db->fetch_object($result); - $datec=$this->db->jdate($objp->datec); - $datem=$this->db->jdate($objp->tms); + $datec = $this->db->jdate($objp->datec); + $datem = $this->db->jdate($objp->tms); $thirdpartystatic->id = $objp->socid; $thirdpartystatic->name = $objp->name; $thirdpartystatic->code_client = $objp->code_client; @@ -127,6 +127,7 @@ class box_clients extends ModeleBoxes $thirdpartystatic->fournisseur = $objp->fournisseur; $thirdpartystatic->logo = $objp->logo; $thirdpartystatic->email = $objp->email; + $thirdpartystatic->entity = $objp->entity; $this->info_box_contents[$line][] = array( 'td' => '', @@ -147,7 +148,7 @@ class box_clients extends ModeleBoxes $line++; } - if ($num==0) $this->info_box_contents[$line][0] = array('td' => 'class="center"','text'=>$langs->trans("NoRecordedCustomers")); + if ($num == 0) $this->info_box_contents[$line][0] = array('td' => 'class="center"', 'text'=>$langs->trans("NoRecordedCustomers")); $this->db->free($result); } diff --git a/htdocs/core/boxes/box_commandes.php b/htdocs/core/boxes/box_commandes.php index c8a050ea1d4..10b9c52acb0 100644 --- a/htdocs/core/boxes/box_commandes.php +++ b/htdocs/core/boxes/box_commandes.php @@ -72,6 +72,7 @@ class box_commandes extends ModeleBoxes public function loadBox($max = 5) { global $user, $langs, $conf; + $langs->load('orders'); $this->max = $max; diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index 91c6ab23910..caea252c571 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015 Frederic France * Copyright (C) 2018 Josep Lluís Amador + * Copyright (C) 2020 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 @@ -83,6 +84,7 @@ class box_contacts extends ModeleBoxes 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, sp.email as spemail"; $sql .= ", s.nom as socname, s.name_alias, s.email as semail"; $sql .= ", s.client, s.fournisseur, s.code_client, s.code_fournisseur"; diff --git a/htdocs/core/boxes/box_fournisseurs.php b/htdocs/core/boxes/box_fournisseurs.php index 5f26351affe..2f55a379362 100644 --- a/htdocs/core/boxes/box_fournisseurs.php +++ b/htdocs/core/boxes/box_fournisseurs.php @@ -2,6 +2,7 @@ /* Copyright (C) 2004-2006 Destailleur Laurent * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015-2019 Frederic France + * Copyright (C) 2020 Pierre Ardoin * * 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 +32,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; */ class box_fournisseurs extends ModeleBoxes { - public $boxcode="lastsuppliers"; - public $boximg="object_company"; - public $boxlabel="BoxLastSuppliers"; + public $boxcode = "lastsuppliers"; + public $boximg = "object_company"; + public $boxlabel = "BoxLastSuppliers"; public $depends = array("fournisseur"); /** @@ -59,7 +60,7 @@ class box_fournisseurs extends ModeleBoxes $this->db = $db; - $this->hidden = ! ($user->rights->societe->lire && empty($user->socid)); + $this->hidden = !($user->rights->societe->lire && empty($user->socid)); } /** @@ -73,28 +74,28 @@ class box_fournisseurs extends ModeleBoxes global $conf, $user, $langs; $langs->load("boxes"); - $this->max=$max; + $this->max = $max; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $thirdpartystatic=new Societe($this->db); + $thirdpartystatic = new Societe($this->db); include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; - $thirdpartytmp=new Fournisseur($this->db); + $thirdpartytmp = new Fournisseur($this->db); $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedSuppliers", $max)); if ($user->rights->societe->lire) { $sql = "SELECT s.nom as name, s.rowid as socid, s.datec, s.tms, s.status,"; - $sql.= " s.code_fournisseur, s.email as semail,"; - $sql.= " s.logo"; + $sql .= " s.code_fournisseur, s.email as semail,"; + $sql .= " s.logo, s.code_compta_fournisseur, s.entity"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE s.fournisseur = 1"; - $sql.= " AND s.entity IN (".getEntity('societe').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($user->socid) $sql.= " AND s.rowid = ".$user->socid; - $sql.= " ORDER BY s.tms DESC "; - $sql.= $this->db->plimit($max, 0); + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE s.fournisseur = 1"; + $sql .= " AND s.entity IN (".getEntity('societe').")"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " ORDER BY s.tms DESC "; + $sql .= $this->db->plimit($max, 0); $result = $this->db->query($sql); if ($result) @@ -105,13 +106,15 @@ class box_fournisseurs extends ModeleBoxes while ($line < $num) { $objp = $this->db->fetch_object($result); - $datec=$this->db->jdate($objp->datec); - $datem=$this->db->jdate($objp->tms); + $datec = $this->db->jdate($objp->datec); + $datem = $this->db->jdate($objp->tms); $thirdpartytmp->id = $objp->socid; $thirdpartytmp->name = $objp->name; $thirdpartytmp->email = $objp->semail; $thirdpartytmp->code_client = $objp->code_client; $thirdpartytmp->logo = $objp->logo; + $thirdpartytmp->code_compta_fournisseur = $objp->code_compta_fournisseur; + $thirdpartytmp->entity = $objp->entity; $this->info_box_contents[$line][] = array( 'td' => '', @@ -132,7 +135,7 @@ class box_fournisseurs extends ModeleBoxes $line++; } - if ($num==0) $this->info_box_contents[$line][0] = array( + if ($num == 0) $this->info_box_contents[$line][0] = array( 'td' => 'class="center"', 'text'=>$langs->trans("NoRecordedSuppliers"), ); diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 6c0a20bc6db..e78b6e235b1 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -160,6 +160,7 @@ class box_graph_invoices_permonth extends ModeleBoxes } $i++; } + $px1->SetLegend($legend); $px1->SetMaxValue($px1->GetCeilMaxValue()); $px1->SetWidth($WIDTH); diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index c61bc2569be..e8337d74303 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -75,6 +75,7 @@ class box_graph_product_distribution extends ModeleBoxes global $conf, $user, $langs; $this->max = $max; + $dir = $conf->user->dir_temp; $refreshaction = 'refresh_'.$this->boxcode; @@ -145,7 +146,8 @@ class box_graph_product_distribution extends ModeleBoxes $showpointvalue = 1; $nocolor = 0; $mode = 'customer'; $stats_invoice = new FactureStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); - $data1 = $stats_invoice->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24))); + $data1 = $stats_invoice->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); + if (empty($data1)) { $showpointvalue = 0; @@ -159,11 +161,12 @@ class box_graph_product_distribution extends ModeleBoxes $mesg = $px1->isGraphKo(); if (!$mesg) { - $i = 0; $tot = count($data1); $legend = array(); - while ($i <= $tot) + $i = 0; $legend = array(); + + foreach ($data1 as $key => $val) { - $data1[$i][0] = dol_trunc($data1[$i][0], 5); // Required to avoid error "Could not draw pie with labels contained inside canvas" - $legend[] = $data1[$i][0]; + $data1[$key][0] = dol_trunc($data1[$key][0], 32); + $legend[] = $data1[$key][0]; $i++; } @@ -172,11 +175,11 @@ class box_graph_product_distribution extends ModeleBoxes if ($nocolor) $px1->SetDataColor(array(array(220, 220, 220))); $px1->SetLegend($legend); - $px1->setShowLegend(0); + $px1->setShowLegend(2); $px1->setShowPointValue($showpointvalue); $px1->setShowPercent(0); $px1->SetMaxValue($px1->GetCeilMaxValue()); - $px1->SetWidth($WIDTH); + //$px1->SetWidth($WIDTH); $px1->SetHeight($HEIGHT); //$px1->SetYLabel($langs->trans("NumberOfBills")); $px1->SetShading(3); @@ -202,7 +205,7 @@ class box_graph_product_distribution extends ModeleBoxes $showpointvalue = 1; $nocolor = 0; $stats_proposal = new PropaleStats($this->db, $socid, ($userid > 0 ? $userid : 0)); - $data2 = $stats_proposal->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24))); + $data2 = $stats_proposal->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); if (empty($data2)) { $showpointvalue = 0; @@ -217,11 +220,12 @@ class box_graph_product_distribution extends ModeleBoxes $mesg = $px2->isGraphKo(); if (!$mesg) { - $i = 0; $tot = count($data2); $legend = array(); - while ($i <= $tot) + $i = 0; $legend = array(); + + foreach ($data2 as $key => $val) { - $data2[$i][0] = dol_trunc($data2[$i][0], 5); // Required to avoid error "Could not draw pie with labels contained inside canvas" - $legend[] = $data2[$i][0]; + $data2[$key][0] = dol_trunc($data2[$key][0], 32); + $legend[] = $data2[$key][0]; $i++; } @@ -230,11 +234,11 @@ class box_graph_product_distribution extends ModeleBoxes if ($nocolor) $px2->SetDataColor(array(array(220, 220, 220))); $px2->SetLegend($legend); - $px2->setShowLegend(0); + $px2->setShowLegend(2); $px2->setShowPointValue($showpointvalue); $px2->setShowPercent(0); $px2->SetMaxValue($px2->GetCeilMaxValue()); - $px2->SetWidth($WIDTH); + //$px2->SetWidth($WIDTH); $px2->SetHeight($HEIGHT); //$px2->SetYLabel($langs->trans("AmountOfBillsHT")); $px2->SetShading(3); @@ -261,7 +265,7 @@ class box_graph_product_distribution extends ModeleBoxes $showpointvalue = 1; $nocolor = 0; $mode = 'customer'; $stats_order = new CommandeStats($this->db, $socid, $mode, ($userid > 0 ? $userid : 0)); - $data3 = $stats_order->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24))); + $data3 = $stats_order->getAllByProductEntry($year, (GETPOST('action', 'aZ09') == $refreshaction ?-1 : (3600 * 24)), 5); if (empty($data3)) { $showpointvalue = 0; @@ -276,11 +280,12 @@ class box_graph_product_distribution extends ModeleBoxes $mesg = $px3->isGraphKo(); if (!$mesg) { - $i = 0; $tot = count($data3); $legend = array(); - while ($i <= $tot) + $i = 0; $legend = array(); + + foreach ($data3 as $key => $val) { - $data3[$i][0] = dol_trunc($data3[$i][0], 5); // Required to avoid error "Could not draw pie with labels contained inside canvas" - $legend[] = $data3[$i][0]; + $data3[$key][0] = dol_trunc($data3[$key][0], 32); + $legend[] = $data3[$key][0]; $i++; } @@ -289,11 +294,11 @@ class box_graph_product_distribution extends ModeleBoxes if ($nocolor) $px3->SetDataColor(array(array(220, 220, 220))); $px3->SetLegend($legend); - $px3->setShowLegend(0); + $px3->setShowLegend(2); $px3->setShowPointValue($showpointvalue); $px3->setShowPercent(0); $px3->SetMaxValue($px3->GetCeilMaxValue()); - $px3->SetWidth($WIDTH); + //$px3->SetWidth($WIDTH); $px3->SetHeight($HEIGHT); //$px3->SetYLabel($langs->trans("AmountOfBillsHT")); $px3->SetShading(3); diff --git a/htdocs/core/boxes/box_project.php b/htdocs/core/boxes/box_project.php index 0bc6d801e41..9fffc92963f 100644 --- a/htdocs/core/boxes/box_project.php +++ b/htdocs/core/boxes/box_project.php @@ -96,7 +96,7 @@ class box_project extends ModeleBoxes $projectsListId=''; if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); - $sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut, p.public"; + $sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut as status, p.public"; $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql.= " WHERE p.entity IN (".getEntity('project').")"; // Only current entity or severals if permission ok $sql.= " AND p.fk_statut = 1"; // Only open projects @@ -117,6 +117,7 @@ class box_project extends ModeleBoxes $projectstatic->ref = $objp->ref; $projectstatic->title = $objp->title; $projectstatic->public = $objp->public; + $projectstatic->statut = $objp->status; $this->info_box_contents[$i][] = array( 'td' => 'class="nowraponall"', @@ -152,6 +153,7 @@ class box_project extends ModeleBoxes $this->info_box_contents[$i][] = array('td' => 'class="right"', 'text' => round(0)); $this->info_box_contents[$i][] = array('td' => 'class="right"', 'text' => "N/A "); } + $this->info_box_contents[$i][] = array('td' => 'class="right"', 'text' => $projectstatic->getLibStatut(3)); $i++; } @@ -166,22 +168,26 @@ class box_project extends ModeleBoxes // Add the sum à the bottom of the boxes $this->info_box_contents[$i][] = array( - 'td' => '', + 'td' => 'class="liste_total"', 'text' => $langs->trans("Total")." ".$textHead, 'text' => " ", ); $this->info_box_contents[$i][] = array( - 'td' => 'class="right" ', + 'td' => 'class="right liste_total" ', 'text' => round($num, 0)." ".$langs->trans("Projects"), ); $this->info_box_contents[$i][] = array( - 'td' => 'class="right" ', + 'td' => 'class="right liste_total" ', 'text' => (($max < $num) ? '' : (round($totalnbTask, 0)." ".$langs->trans("Tasks"))), ); $this->info_box_contents[$i][] = array( - 'td' => '', + 'td' => 'class="liste_total"', 'text' => " ", ); + $this->info_box_contents[$i][] = array( + 'td' => 'class="liste_total"', + 'text' => " ", + ); } /** diff --git a/htdocs/core/boxes/box_propales.php b/htdocs/core/boxes/box_propales.php index 3cbd9f45514..979723753a0 100644 --- a/htdocs/core/boxes/box_propales.php +++ b/htdocs/core/boxes/box_propales.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2007 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2015-2019 Frederic France + * Copyright (C) 2020 Pierre Ardoin * * 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,10 +33,10 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; */ class box_propales extends ModeleBoxes { - public $boxcode="lastpropals"; - public $boximg="object_propal"; - public $boxlabel="BoxLastProposals"; - public $depends = array("propal"); // conf->propal->enabled + public $boxcode = "lastpropals"; + public $boximg = "object_propal"; + public $boxlabel = "BoxLastProposals"; + public $depends = array("propal"); // conf->propal->enabled /** * @var DoliDB Database handler. @@ -60,7 +61,7 @@ class box_propales extends ModeleBoxes $this->db = $db; - $this->hidden = ! ($user->rights->propale->lire); + $this->hidden = !($user->rights->propale->lire); } /** @@ -73,45 +74,45 @@ class box_propales extends ModeleBoxes { global $user, $langs, $conf; - $this->max=$max; + $this->max = $max; include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $propalstatic=new Propal($this->db); + $propalstatic = new Propal($this->db); $societestatic = new Societe($this->db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE?"":"Modified")."Propals", $max)); + $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."Propals", $max)); if ($user->rights->propale->lire) { - $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client, s.logo, s.email,"; - $sql.= " p.rowid, p.ref, p.fk_statut, p.datep as dp, p.datec, p.fin_validite, p.date_cloture, p.total_ht, p.tva as total_tva, p.total as total_ttc, p.tms"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE p.fk_soc = s.rowid"; - $sql.= " AND p.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if($user->socid) $sql.= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql.= " ORDER BY p.datep DESC, p.ref DESC "; - else $sql.= " ORDER BY p.tms DESC, p.ref DESC "; - $sql.= $this->db->plimit($max, 0); + $sql = "SELECT s.nom as name, s.rowid as socid, s.code_client, s.logo, s.entity, s.email,"; + $sql .= " p.rowid, p.ref, p.fk_statut, p.datep as dp, p.datec, p.fin_validite, p.date_cloture, p.total_ht, p.tva as total_tva, p.total as total_ttc, p.tms"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE p.fk_soc = s.rowid"; + $sql .= " AND p.entity = ".$conf->entity; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY p.datep DESC, p.ref DESC "; + else $sql .= " ORDER BY p.tms DESC, p.ref DESC "; + $sql .= $this->db->plimit($max, 0); $result = $this->db->query($sql); if ($result) { $num = $this->db->num_rows($result); - $now=dol_now(); + $now = dol_now(); $line = 0; while ($line < $num) { $objp = $this->db->fetch_object($result); - $date=$this->db->jdate($objp->dp); - $datec=$this->db->jdate($objp->datec); - $datem=$this->db->jdate($objp->tms); - $dateterm=$this->db->jdate($objp->fin_validite); - $dateclose=$this->db->jdate($objp->date_cloture); + $date = $this->db->jdate($objp->dp); + $datec = $this->db->jdate($objp->datec); + $datem = $this->db->jdate($objp->tms); + $dateterm = $this->db->jdate($objp->fin_validite); + $dateclose = $this->db->jdate($objp->date_cloture); $propalstatic->id = $objp->rowid; $propalstatic->ref = $objp->ref; $propalstatic->total_ht = $objp->total_ht; @@ -122,6 +123,7 @@ class box_propales extends ModeleBoxes $societestatic->code_client = $objp->code_client; $societestatic->logo = $objp->logo; $societestatic->email = $objp->email; + $societestatic->entity = $objp->entity; $late = ''; if ($objp->fk_statut == 1 && $dateterm < ($now - $conf->propal->cloture->warning_delay)) { @@ -159,7 +161,7 @@ class box_propales extends ModeleBoxes $line++; } - if ($num==0) + if ($num == 0) $this->info_box_contents[$line][0] = array( 'td' => 'class="center"', 'text'=>$langs->trans("NoRecordedProposals"), diff --git a/htdocs/core/boxes/box_services_contracts.php b/htdocs/core/boxes/box_services_contracts.php index dbb26408b6f..5b40fc61436 100644 --- a/htdocs/core/boxes/box_services_contracts.php +++ b/htdocs/core/boxes/box_services_contracts.php @@ -91,7 +91,7 @@ class box_services_contracts extends ModeleBoxes $sql = "SELECT s.nom as name, s.rowid as socid, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,"; $sql.= " c.rowid, c.ref, c.statut as contract_status, c.ref_customer, c.ref_supplier,"; $sql.= " cd.rowid as cdid, cd.label, cd.description, cd.tms as datem, cd.statut, cd.product_type as type,"; - $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as plabel, p.fk_product_type as ptype, p.entity"; + $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as plabel, p.fk_product_type as ptype, p.entity, p.tobuy, p.tosell"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."contrat as c ON s.rowid = c.fk_soc"; $sql.= " INNER JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; @@ -165,6 +165,9 @@ class box_services_contracts extends ModeleBoxes $productstatic->ref=$objp->product_ref; $productstatic->entity=$objp->pentity; $productstatic->label=$objp->plabel; + $productstatic->status = $objp->tosell; + $productstatic->status_buy = $objp->tobuy; + $text = $productstatic->getNomUrl(1, '', 20); if ($objp->plabel) { diff --git a/htdocs/core/boxes/box_shipments.php b/htdocs/core/boxes/box_shipments.php index 3b07b5bbd68..26f45bc08db 100644 --- a/htdocs/core/boxes/box_shipments.php +++ b/htdocs/core/boxes/box_shipments.php @@ -77,6 +77,7 @@ class box_shipments extends ModeleBoxes $this->max = $max; include_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $shipmentstatic = new Expedition($this->db); diff --git a/htdocs/core/boxes/box_task.php b/htdocs/core/boxes/box_task.php index 2ae0ede3c21..94983ef6bff 100644 --- a/htdocs/core/boxes/box_task.php +++ b/htdocs/core/boxes/box_task.php @@ -86,6 +86,7 @@ class box_task extends ModeleBoxes $form = new Form($this->db); $cookie_name = 'boxfilter_task'; $boxcontent = ''; + $socid = $user->socid; $textHead = $langs->trans("CurentlyOpenedTasks"); @@ -97,7 +98,6 @@ class box_task extends ModeleBoxes $filterValue = $_COOKIE[$cookie_name]; } - if ($filterValue == 'im_task_contact') { $textHead .= ' : '.$langs->trans("WhichIamLinkedTo"); } @@ -127,15 +127,17 @@ class box_task extends ModeleBoxes $boxcontent .= ''; $boxcontent .= ''."\n"; $boxcontent .= ''."\n"; - $boxcontent .= ''; - // set cookie by js - $boxcontent .= ''; + '; + // set cookie by js + $boxcontent .= ''; + } $this->info_box_contents[0][] = array( 'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"', 'td' => 'class="nohover"', @@ -143,6 +145,10 @@ class box_task extends ModeleBoxes ); + // Get list of project id allowed to user (in a string list separated by coma) + $projectsListId = ''; + if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); + $sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress"; $sql .= ", p.rowid project_id, p.ref project_ref, p.title project_title"; @@ -163,7 +169,7 @@ class box_task extends ModeleBoxes $sql .= " AND p.fk_statut = ".Project::STATUS_VALIDATED; $sql .= " AND (pt.progress < 100 OR pt.progress IS NULL ) "; // 100% is done and not displayed $sql .= " AND p.usage_task = 1 "; - + if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users $sql .= " ORDER BY pt.datee ASC, pt.dateo ASC"; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index aa1aed52822..bba38bddb30 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -144,7 +144,10 @@ class CMailFile } } - $this->subject = $subject; + // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) + if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + + $this->subject = $subject; $this->addr_to = $to; $this->addr_from = $from; $this->msg = $msg; @@ -267,9 +270,6 @@ class CMailFile } } - // Add autocopy to (Note: Adding bcc for specific modules are also done from pages) - if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; - // We set all data according to choosed sending method. // We also set a value for ->msgid if ($this->sendmode == 'mail') diff --git a/htdocs/core/class/CSMSFile.class.php b/htdocs/core/class/CSMSFile.class.php index a02f00fbac9..7c1713b9453 100644 --- a/htdocs/core/class/CSMSFile.class.php +++ b/htdocs/core/class/CSMSFile.class.php @@ -47,6 +47,11 @@ class CSMSFile public $message; public $nostop; + public $socid; + public $contactid; + + public $fk_project; + /** * CSMSFile @@ -125,7 +130,12 @@ class CSMSFile $sms->class=$this->class; $sms->nostop=$this->nostop; + $sms->socid=$this->socid; + $sms->contactid=$this->contactid; + $sms->project=$this->fk_project; + $res=$sms->SmsSend(); + if ($res <= 0) { $this->error=$sms->error; @@ -155,7 +165,12 @@ class CSMSFile $sms->message=$this->message; $sms->nostop=$this->nostop; + $sms->socid=$this->socid; + $sms->contactid=$this->contactid; + $sms->fk_project=$this->fk_project; + $res=$sms->SmsSend(); + $this->error = $sms->error; $this->errors = $sms->errors; if ($res <= 0) diff --git a/htdocs/core/class/canvas.class.php b/htdocs/core/class/canvas.class.php index cfdb09c527e..80c6ff1b7a6 100644 --- a/htdocs/core/class/canvas.class.php +++ b/htdocs/core/class/canvas.class.php @@ -36,7 +36,7 @@ class Canvas /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** * @var string[] Error codes (or messages) @@ -45,13 +45,13 @@ class Canvas public $actiontype; - public $dirmodule; // Module directory - public $targetmodule; // Module concerned by canvas (ex: thirdparty, contact, ...) - public $canvas; // Name of canvas (ex: company, individual, product, service, ...) - public $card; // Tab (sub-canvas) + public $dirmodule; // Module directory + public $targetmodule; // Module concerned by canvas (ex: thirdparty, contact, ...) + public $canvas; // Name of canvas (ex: company, individual, product, service, ...) + public $card; // Tab (sub-canvas) - public $template_dir; // Initialized by getCanvas with templates directory - public $control; // Initialized by getCanvas with controller instance + public $template_dir; // Initialized by getCanvas with templates directory + public $control; // Initialized by getCanvas with controller instance /** @@ -76,9 +76,9 @@ class Canvas private function _cleanaction($action) { $newaction = $action; - if ($newaction == 'add') $newaction='create'; - if ($newaction == 'update') $newaction='edit'; - if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction='view'; + if ($newaction == 'add') $newaction = 'create'; + if ($newaction == 'update') $newaction = 'edit'; + if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction = 'view'; return $newaction; } @@ -114,7 +114,7 @@ class Canvas if (file_exists($controlclassfile)) { // Include actions class (controller) - $this->control_file=$controlclassfile; + $this->control_file = $controlclassfile; require_once $controlclassfile; // Instantiate actions class (controller) @@ -124,9 +124,9 @@ class Canvas // Template dir $this->template_dir = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/'); - if (! is_dir($this->template_dir)) + if (!is_dir($this->template_dir)) { - $this->template_dir=''; + $this->template_dir = ''; } //print 'dimodule='.$dirmodule.' canvas='.$this->canvas.'
    '; @@ -158,7 +158,7 @@ class Canvas { if (empty($this->template_dir)) return 0; - if (file_exists($this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php')) return 1; + if (file_exists($this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php')) return 1; else return 0; } @@ -176,7 +176,8 @@ class Canvas global $db, $conf, $langs, $user, $canvas; global $form, $formfile; - include $this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php'; // Include native PHP template + //var_dump($this->card.'-'.$action); + include $this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php'; // Include native PHP template } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index dc4cbeff1ac..bd3dcb01e76 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -49,6 +49,10 @@ abstract class CommonDocGenerator */ protected $db; + /** + * @var Extrafields object + */ + public $extrafieldsCache; /** * Constructor @@ -217,24 +221,24 @@ 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); $extrafields->fetch_name_optionals_label($object->table_element, true); $object->fetch_optionals(); - foreach($extrafields->attributes[$object->table_element]['label'] as $key=>$label) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key=>$label) { - if($extrafields->attributes[$object->table_element]['type'][$key] == 'price') + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') { $object->array_options['options_'.$key] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency); } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'select' || $extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select' || $extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]]; } - $array_thirdparty = array_merge($array_thirdparty, array ('company_options_'.$key => $object->array_options ['options_' . $key])); + $array_thirdparty = array_merge($array_thirdparty, array('company_options_'.$key => $object->array_options ['options_'.$key])); } } return $array_thirdparty; @@ -254,61 +258,62 @@ abstract class CommonDocGenerator // phpcs:enable global $conf; - if(empty($object->country) && ! empty($object->country_code)) + if (empty($object->country) && !empty($object->country_code)) { - $object->country = $outputlangs->transnoentitiesnoconv("Country" . $object->country_code); + $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); } - if(empty($object->state) && ! empty($object->state_code)) + if (empty($object->state) && !empty($object->state_code)) { $object->state = getState($object->state_code, 0); } $array_contact = array ( - $array_key . '_fullname' => $object->getFullName($outputlangs, 1), - $array_key . '_lastname' => $object->lastname, - $array_key . '_firstname' => $object->firstname, - $array_key . '_address' => $object->address, - $array_key . '_zip' => $object->zip, - $array_key . '_town' => $object->town, - $array_key . '_state_id' => $object->state_id, - $array_key . '_state_code' => $object->state_code, - $array_key . '_state' => $object->state, - $array_key . '_country_id' => $object->country_id, - $array_key . '_country_code' => $object->country_code, - $array_key . '_country' => $object->country, - $array_key . '_poste' => $object->poste, - $array_key . '_socid' => $object->socid, - $array_key . '_statut' => $object->statut, - $array_key . '_code' => $object->code, - $array_key . '_email' => $object->email, - $array_key . '_jabberid' => $object->jabberid, - $array_key . '_phone_pro' => $object->phone_pro, - $array_key . '_phone_perso' => $object->phone_perso, - $array_key . '_phone_mobile' => $object->phone_mobile, - $array_key . '_fax' => $object->fax, - $array_key . '_birthday' => $object->birthday, - $array_key . '_default_lang' => $object->default_lang, - $array_key . '_note_public' => $object->note_public, - $array_key . '_note_private' => $object->note_private + $array_key . '_fullname' => $object->getFullName($outputlangs, 1), + $array_key . '_lastname' => $object->lastname, + $array_key . '_firstname' => $object->firstname, + $array_key . '_address' => $object->address, + $array_key . '_zip' => $object->zip, + $array_key . '_town' => $object->town, + $array_key . '_state_id' => $object->state_id, + $array_key . '_state_code' => $object->state_code, + $array_key . '_state' => $object->state, + $array_key . '_country_id' => $object->country_id, + $array_key . '_country_code' => $object->country_code, + $array_key . '_country' => $object->country, + $array_key . '_poste' => $object->poste, + $array_key . '_socid' => $object->socid, + $array_key . '_statut' => $object->statut, + $array_key . '_code' => $object->code, + $array_key . '_email' => $object->email, + $array_key . '_jabberid' => $object->jabberid, // deprecated + $array_key . '_phone_pro' => $object->phone_pro, + $array_key . '_phone_perso' => $object->phone_perso, + $array_key . '_phone_mobile' => $object->phone_mobile, + $array_key . '_fax' => $object->fax, + $array_key . '_birthday' => $object->birthday, + $array_key . '_default_lang' => $object->default_lang, + $array_key . '_note_public' => $object->note_public, + $array_key . '_note_private' => $object->note_private, + $array_key . '_civility' => $object->civility, ); // Retrieve extrafields - require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extrafields->fetch_name_optionals_label($object->table_element, true); $object->fetch_optionals(); - foreach($extrafields->attributes[$object->table_element]['label'] as $key => $label) + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) { if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') { - $object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency); + $object->array_options['options_'.$key] = price($object->array_options ['options_'.$key], 0, $outputlangs, 0, 0, - 1, $conf->currency); } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'select' || $extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select' || $extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { - $object->array_options['options_' . $key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_' . $key]]; + $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]]; } - $array_contact = array_merge($array_contact, array($array_key.'_options_' . $key => $object->array_options['options_'. $key])); + $array_contact = array_merge($array_contact, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); } return $array_contact; } @@ -474,20 +479,20 @@ abstract class CommonDocGenerator } // Add vat by rates - if (is_array($object->lines) && count($object->lines)>0) + if (is_array($object->lines) && count($object->lines) > 0) { $totalUp = 0; foreach ($object->lines as $line) { // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility - if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0; - $resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva; - $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); + if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0; + $resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; + $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) - $vatformated=vatrate($line->tva_tx); - if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated]=0; - $resarray[$array_key.'_total_vat_'.$vatformated]+=$line->total_tva; - $resarray[$array_key.'_total_vat_locale_'.$vatformated]=price($resarray[$array_key.'_total_vat_'.$vatformated]); + $vatformated = vatrate($line->tva_tx); + if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0; + $resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva; + $resarray[$array_key.'_total_vat_locale_'.$vatformated] = price($resarray[$array_key.'_total_vat_'.$vatformated]); $totalUp += $line->subprice * $line->qty; } @@ -532,14 +537,16 @@ abstract class CommonDocGenerator * * @param Object $line Object line * @param Translate $outputlangs Lang object to use for output + * @param int $linenumber The number of the line for the substitution of "object_line_pos" * @return array Return a substitution array */ - public function get_substitutionarray_lines($line, $outputlangs) + public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0) { // phpcs:enable global $conf; $resarray = array( + 'line_pos' => $linenumber, 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), 'line_product_ref'=>$line->product_ref, 'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines @@ -562,12 +569,12 @@ abstract class CommonDocGenerator 'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs), 'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs), // Dates - 'line_date_start'=>dol_print_date($line->date_start, 'day', 'tzuser'), - 'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzuser', $outputlangs), - 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc', 'tzuser'), - 'line_date_end'=>dol_print_date($line->date_end, 'day', 'tzuser'), - 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzuser', $outputlangs), - 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc', 'tzuser'), + 'line_date_start'=>dol_print_date($line->date_start, 'day'), + 'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs), + 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), + 'line_date_end'=>dol_print_date($line->date_end, 'day'), + 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), + 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), 'line_multicurrency_code' => price2num($line->multicurrency_code), 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), @@ -583,13 +590,13 @@ abstract class CommonDocGenerator // Units if ($conf->global->PRODUCT_USE_UNITS) { - $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long')); - $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short')); + $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); } // Retrieve extrafields - $extrafieldkey=$line->element; - $array_key="line"; + $extrafieldkey = $line->element; + $array_key = "line"; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); $extrafields->fetch_name_optionals_label($extrafieldkey, true); @@ -602,22 +609,33 @@ abstract class CommonDocGenerator { // Add the product supplier extrafields to the substitutions $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels=$extrafields->attributes["product_fournisseur_price"]['label']; - $columns = ""; - foreach ($extralabels as $key => $value) - $columns .= "$key, "; + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; - if ($columns != "") - { - $columns = substr($columns, 0, strlen($columns) - 2); - $resql = $this->db->query("SELECT $columns FROM " . MAIN_DB_PREFIX . "product_fournisseur_price_extrafields AS ex INNER JOIN " . MAIN_DB_PREFIX . "product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '" . $line->ref_supplier . "'"); - if ($this->db->num_rows($resql) > 0) { - $resql = $this->db->fetch_object($resql); + if (!empty($extralabels) && is_array($extralabels)) + { + $columns = ""; - foreach ($extralabels as $key => $value) - $resarray['line_product_supplier_'.$key] = $resql->{$key}; - } - } + foreach ($extralabels as $key) + { + $columns .= "$key, "; + } + + if ($columns != "") + { + $columns = substr($columns, 0, strlen($columns) - 2); + $resql = $this->db->query("SELECT $columns FROM ".MAIN_DB_PREFIX."product_fournisseur_price_extrafields AS ex INNER JOIN ".MAIN_DB_PREFIX."product_fournisseur_price AS f ON ex.fk_object = f.rowid WHERE f.ref_fourn = '".$line->ref_supplier."'"); + + if ($this->db->num_rows($resql) > 0) + { + $resql = $this->db->fetch_object($resql); + + foreach ($extralabels as $key) + { + $resarray['line_product_supplier_'.$key] = $resql->{$key}; + } + } + } + } } // Load product data optional fields to the line -> enables to use "line_options_{extrafield}" @@ -720,14 +738,14 @@ abstract class CommonDocGenerator 'line_qty'=>$line->qty, 'line_qty_shipped'=>$line->qty_shipped, 'line_qty_asked'=>$line->qty_asked, - 'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''), + 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), 'line_price_ht'=>price($line->total_ht), 'line_price_ttc'=>price($line->total_ttc), 'line_price_vat'=>price($line->total_tva), - 'line_weight'=>empty($line->weight) ? '' : $line->weight*$line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), - 'line_length'=>empty($line->length) ? '' : $line->length*$line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), - 'line_surface'=>empty($line->surface) ? '' : $line->surface*$line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), - 'line_volume'=>empty($line->volume) ? '' : $line->volume*$line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), + 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), + 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), + 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), + 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), ); // Retrieve extrafields @@ -788,81 +806,84 @@ abstract class CommonDocGenerator { // phpcs:enable global $conf; - foreach($extrafields->attributes[$object->table_element]['label'] as $key=>$label) - { - if($extrafields->attributes[$object->table_element]['type'][$key] == 'price') + + if (is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key=>$label) { - $object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]); - $object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency); - //Add value to store price with currency - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency'])); - } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'select') - { - $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]]; - } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { - $valArray=explode(',', $object->array_options['options_'.$key]); - $output=array(); - foreach($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt=>$valopt) { - if (in_array($keyopt, $valArray)) { - $output[]=$valopt; + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') + { + $object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]); + $object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency); + //Add value to store price with currency + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency'])); + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'select') + { + $object->array_options['options_'.$key] = $extrafields->attributes[$object->table_element]['param'][$key]['options'][$object->array_options['options_'.$key]]; + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'checkbox') { + $valArray = explode(',', $object->array_options['options_'.$key]); + $output = array(); + foreach ($extrafields->attributes[$object->table_element]['param'][$key]['options'] as $keyopt=>$valopt) { + if (in_array($keyopt, $valArray)) { + $output[] = $valopt; + } } + $object->array_options['options_'.$key] = implode(', ', $output); } - $object->array_options['options_'.$key] = implode(', ', $output); - } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'date') - { - if (strlen($object->array_options['options_'.$key])>0) + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') { - $date = $object->array_options['options_'.$key]; - $object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language - $object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format - $object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format - } - else - { - $object->array_options['options_'.$key] = ''; - $object->array_options['options_'.$key.'_locale'] = ''; - $object->array_options['options_'.$key.'_rfc'] = ''; - } - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); - } - elseif($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime') - { - $datetime = $object->array_options['options_'.$key]; - $object->array_options['options_'.$key] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key], 'dayhour'):''); // using company output language - $object->array_options['options_'.$key.'_locale'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key], 'dayhour', 'tzserver', $outputlangs):''); // using output language format - $object->array_options['options_'.$key.'_rfc'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc'):''); // international format - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); - $array_to_fill=array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); - } - elseif($extrafields->attributes[$object->table_element]['type'][$key] == 'link') - { - $id = $object->array_options['options_'.$key]; - if ($id != "") - { - $param = $extrafields->attributes[$object->table_element]['param'][$key]; - $param_list=array_keys($param['options']); // $param_list='ObjectName:classPath' - $InfoFieldList = explode(":", $param_list[0]); - $classname=$InfoFieldList[0]; - $classpath=$InfoFieldList[1]; - if (! empty($classpath)) + if (strlen($object->array_options['options_'.$key]) > 0) { - dol_include_once($InfoFieldList[1]); - if ($classname && class_exists($classname)) + $date = $object->array_options['options_'.$key]; + $object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language + $object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format + $object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format + } + else + { + $object->array_options['options_'.$key] = ''; + $object->array_options['options_'.$key.'_locale'] = ''; + $object->array_options['options_'.$key.'_rfc'] = ''; + } + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); + } + elseif ($extrafields->attributes[$object->table_element]['label'][$key] == 'datetime') + { + $datetime = $object->array_options['options_'.$key]; + $object->array_options['options_'.$key] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour') : ''); // using company output language + $object->array_options['options_'.$key.'_locale'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour', 'tzserver', $outputlangs) : ''); // using output language format + $object->array_options['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc') : ''); // international format + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale'])); + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc'])); + } + elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'link') + { + $id = $object->array_options['options_'.$key]; + if ($id != "") + { + $param = $extrafields->attributes[$object->table_element]['param'][$key]; + $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath' + $InfoFieldList = explode(":", $param_list[0]); + $classname = $InfoFieldList[0]; + $classpath = $InfoFieldList[1]; + if (!empty($classpath)) { - $tmpobject = new $classname($this->db); - $tmpobject->fetch($id); - // completely replace the id with the linked object name - $object->array_options['options_'.$key] = $tmpobject->name; + dol_include_once($InfoFieldList[1]); + if ($classname && class_exists($classname)) + { + $tmpobject = new $classname($this->db); + $tmpobject->fetch($id); + // completely replace the id with the linked object name + $object->array_options['options_'.$key] = $tmpobject->name; + } } } } - } - $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); + $array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key])); + } } return $array_to_fill; @@ -928,27 +949,27 @@ abstract class CommonDocGenerator uasort($this->cols, array($this, 'columnSort')); // Positionning - $curX = $this->page_largeur-$this->marge_droite; // start from right + $curX = $this->page_largeur - $this->marge_droite; // start from right // Array width - $arrayWidth = $this->page_largeur-$this->marge_droite-$this->marge_gauche; + $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; // Count flexible column $totalDefinedColWidth = 0; $countFlexCol = 0; foreach ($this->cols as $colKey =>& $colDef) { - if(!$this->getColumnStatus($colKey)) continue; // continue if disabled + if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - if(!empty($colDef['scale'])){ + if (!empty($colDef['scale'])) { // In case of column width is defined by percentage $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); } - if(empty($colDef['width'])){ + if (empty($colDef['width'])) { $countFlexCol++; } - else{ + else { $totalDefinedColWidth += $colDef['width']; } } @@ -1070,11 +1091,11 @@ abstract class CommonDocGenerator /** * print standard column content * - * @param PDF $pdf pdf object + * @param TCPDF $pdf pdf object * @param float $curY curent Y position * @param string $colKey the column key * @param string $columnText column text - * @return int new rank on success and -1 on error + * @return null */ public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') { @@ -1090,13 +1111,295 @@ abstract class CommonDocGenerator if (!$reshook) { if (empty($columnText)) return; - $pdf->SetXY($this->getColumnContentXStart($colKey) - 1, $curY); // Set curent position + $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position $colDef = $this->cols[$colKey]; - $pdf->writeHTMLCell($this->getColumnContentWidth($colKey) + 2, 2, $this->getColumnContentXStart($colKey) - 1, $curY, $columnText, 0, 0, 0, true, $colDef['content']['align']); + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); } } + /** + * print description column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param object $object CommonObject + * @param int $i the $object->lines array key + * @param Translate $outputlangs Output language + * @param int $hideref hide ref + * @param int $hidedesc hide desc + * @param int $issupplierline if object need supplier product + * @return null + */ + public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) + { + // load desc col params + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + + // line description + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); + $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + + // Display extrafield if needed + $params = array( + 'display' => 'list', + 'printableEnable' => array(3), + 'printableEnableNotEmpty' => array(4) + ); + $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); + if (!empty($extrafieldDesc)) { + $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); + } + } + + /** + * get extrafield content for pdf writeHtmlCell compatibility + * usage for PDF line columns and object note block + * + * @param object $object common object + * @param string $extrafieldKey the extrafield key + * @return string + */ + public function getExtrafieldContent($object, $extrafieldKey) + { + global $hookmanager; + + if (empty($object->table_element)) { return; } + + $extrafieldsKeyPrefix = "options_"; + + // Cleanup extrafield key to remove prefix if present + $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); + if ($pos === 0) { + $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); + } + + $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + + // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... + if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { + // for lack of anything better we cleanup all html tags + $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); + } + + $parameters = array( + 'object' => $object, + 'extrafields' => $extrafields, + 'extrafieldKey' => $extrafieldKey, + 'extrafieldOutputContent' =>& $extrafieldOutputContent + ); + $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook) + { + $extrafieldOutputContent = $hookmanager->resPrint; + } + + return $extrafieldOutputContent; + } + + + /** + * display extrafields columns content + * + * @param object $object line of common object + * @param Translate $outputlangs Output language + * @param array $params array of additionals parameters + * @return double max y value + */ + public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) + { + global $hookmanager; + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $defaultParams = array( + 'style' => '', + 'display' => 'auto', // auto, table, list + 'printableEnable' => array(1), + 'printableEnableNotEmpty' => array(2), + + 'table' => array( + 'maxItemsInRow' => 2, + 'cellspacing' => 0, + 'cellpadding' => 0, + 'border' => 0, + 'labelcolwidth' => '25%', + 'arrayOfLineBreakType' => array('text', 'html') + ), + + 'list' => array( + 'separator' => '
    ' + ), + + 'auto' => array( + 'list' => 0, // 0 for default + 'table' => 4 // if there more than x extrafield to display + ), + ); + + $params = $params + $defaultParams; + + + /** + * @var $extrafields ExtraFields + */ + + $html = ''; + $fields = array(); + + if (is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Enable extrafield ? + $enabled = 0; + $disableOnEmpty = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { + $enabled = 1; + } + + if (in_array($printable, $params['printableEnableNotEmpty'])) { + $disableOnEmpty = 1; + } + } + + if (empty($enabled)) { + continue; + } + + $field = new stdClass(); + $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); + $field->content = $this->getExtrafieldContent($object, $key); + $field->label = $outputlangs->transnoentities($label); + $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + + // dont display if empty + if ($disableOnEmpty && empty($field->content)) { + continue; + } + + $fields[] = $field; + } + } + + if (!empty($fields)) + { + // Sort extrafields by rank + uasort($fields, function ($a, $b) { + return ($a->rank > $b->rank) ? -1 : 1; + }); + + // define some HTML content with style + $html .= !empty($params['style']) ? '' : ''; + + // auto select display format + if ($params['display'] == 'auto') { + $lastNnumbItems = 0; + foreach ($params['auto'] as $display => $numbItems) { + if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { + $lastNnumbItems = $numbItems; + $params['display'] = $display; + } + } + } + + if ($params['display'] == 'list') { + // Display in list format + $i = 0; + foreach ($fields as $field) { + $html .= !empty($i) ? $params['list']['separator'] : ''; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $i++; + } + } + elseif ($params['display'] == 'table') { + // Display in table format + $html .= '
    '; - print $langs->trans("Category") . ': ' . $formother->select_categories(Categorie::TYPE_PRODUCT, $selected_cat, 'search_categ', true); + print $langs->trans("Category").': '.$formother->select_categories(Categorie::TYPE_PRODUCT, $selected_cat, 'search_categ', true); print ' '; - print $langs->trans("SubCats") . '? '; + print $langs->trans("SubCats").'? '; print ''; // type filter (produit/service) print ' '; - print $langs->trans("Type"). ': '; - $form->select_type_of_lines(isset($selected_type)?$selected_type:-1, 'search_type', 1, 1, 1); + print $langs->trans("Type").': '; + $form->select_type_of_lines(isset($selected_type) ? $selected_type : -1, 'search_type', 1, 1, 1); //select thirdparty print '
    '; - print $langs->trans("ThirdParty") . ': ' . $form->select_thirdparty_list($selected_soc, 'search_soc', '', 1); + print $langs->trans("ThirdParty").': '.$form->select_thirdparty_list($selected_soc, 'search_soc', '', 1); print '
    '; @@ -389,16 +391,16 @@ if ($modecompta == 'CREANCES-DETTES') print "
    "; - $fullname=$name[$key]; + $fullname = $name[$key]; if ($key > 0) { - $linkname=''.img_object($langs->trans("ShowProduct"), $type[$key]==0?'product':'service').' '.$fullname.''; + $linkname = ''.img_object($langs->trans("ShowProduct"), $type[$key] == 0 ? 'product' : 'service').' '.$fullname.''; } else { - $linkname=$langs->trans("PaymentsNotLinkedToProduct"); + $linkname = $langs->trans("PaymentsNotLinkedToProduct"); } print $linkname; print "".dol_print_date(dol_mktime(12,0,0,$mois,1,2000),"%B")."
    '.$langs->trans("BankAccount").''; - $form->select_comptes($_POST["accountid"], "accountid", 0, "courant=1", 1); // Affiche liste des comptes courant + $form->select_comptes(GETPOST("accountid", 'int'), "accountid", 0, "courant=1", 2); // List of bank account available print '
    '; - print $formcompany->select_civility(GETPOSTISSET("civility_code") ?GETPOST("civility_code", 'alpha') : $object->civility_code, 'civility_code'); + print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", 'alpha') : $object->civility_code, 'civility_code'); print '
    / '; - print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha') ?GETPOST("zipcode", 'alpha') : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; - print $formcompany->select_ziptown((GETPOST("town", 'alpha') ?GETPOST("town", 'alpha') : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); + print $formcompany->select_ziptown((GETPOST("zipcode", 'alpha') ? GETPOST("zipcode", 'alpha') : $object->zip), 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6).' '; + print $formcompany->select_ziptown((GETPOST("town", 'alpha') ? GETPOST("town", 'alpha') : $object->town), 'town', array('zipcode', 'selectcountry_id', 'state_id')); print '
    '; - print $form->select_country((GETPOST("country_id", 'alpha') ?GETPOST("country_id", 'alpha') : $object->country_id), 'country_id'); + print $form->select_country((GETPOST("country_id", 'alpha') ? GETPOST("country_id", 'alpha') : $object->country_id), 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print '
    '.img_picto('', 'object_phoning').' '.$form->editfieldkey('PhonePro', 'phone_pro', '', $object, 0).'
    '.img_picto('', 'object_phoning').' '.$form->editfieldkey('PhonePerso', 'phone_perso', '', $object, 0).'
    '.img_picto('', 'object_phoning_mobile').' '.$form->editfieldkey('PhoneMobile', 'phone_mobile', '', $object, 0).'
    '.img_picto('', 'object_phoning_fax').' '.$form->editfieldkey('Fax', 'fax', '', $object, 0).'
    '.img_picto('', 'object_email').' '.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '').'
    '.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ?GETPOST("no_email", 'alpha') : $noemail), 1).''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'alpha') : $noemail), 1).'
    '.dol_print_date($db->jdate($obj->tms), 'dayhour').''.$staticcontrat->LibStatut($obj->statut,2).''.($obj->nb_initial > 0 ? $obj->nb_initial.$staticcontratligne->LibStatut(0, 3) : '').''.($obj->nb_running > 0 ? $obj->nb_running.$staticcontratligne->LibStatut(4, 3, 0) : '').''.($obj->nb_expired > 0 ? $obj->nb_expired.$staticcontratligne->LibStatut(4, 3, 1) : '').''.($obj->nb_closed > 0 ? $obj->nb_closed.$staticcontratligne->LibStatut(5, 3) : '').''.($obj->nb_initial > 0 ? ''.$obj->nb_initial.''.$staticcontratligne->LibStatut(0, 3, -1, 'class="paddingleft"') : '').''.($obj->nb_running > 0 ? ''.$obj->nb_running.''.$staticcontratligne->LibStatut(4, 3, 0, 'class="marginleft"') : '').''.($obj->nb_expired > 0 ? ''.$obj->nb_expired.''.$staticcontratligne->LibStatut(4, 3, 1, 'class="paddingleft"') : '').''.($obj->nb_closed > 0 ? ''.$obj->nb_closed.''.$staticcontratligne->LibStatut(5, 3, -1, 'class="paddingleft"') : '').'
    '.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzuser').''.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').' getLibStatut(7); ?>'.img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>">transnoentitiesnoconv("RemoveLink"), 'unlink'); ?>
    '; + + $html .= ""; + $itemsInRow = 0; + $maxItemsInRow = $params['table']['maxItemsInRow']; + foreach ($fields as $field) { + //$html.= !empty($html)?'
    ':''; + if ($itemsInRow >= $maxItemsInRow) { + // start a new line + $html .= ""; + $itemsInRow = 0; + } + + // for some type we need line break + if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { + if ($itemsInRow > 0) { + // close table row and empty cols + for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { + $html .= ""; + } + $html .= ""; + + // start a new line + $html .= ""; + } + + $itemsInRow = $maxItemsInRow; + $html .= '"; + } else { + $itemsInRow++; + $html .= '"; + + + $html .= '"; + } + } + $html .= ""; + + $html .= '
    '; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $html .= "'; + $html .= ''.$field->label.' :'; + $html .= "'; + $html .= $field->content; + $html .= "
    '; + } + } + + return $html; + } + + /** * get column status from column key * @@ -1114,7 +1417,7 @@ abstract class CommonDocGenerator /** * Print standard column content * - * @param PDF $pdf Pdf object + * @param TCPDI $pdf Pdf object * @param float $tab_top Tab top position * @param float $tab_height Default tab height * @param Translate $outputlangs Output language @@ -1150,21 +1453,123 @@ abstract class CommonDocGenerator } if (empty($hidetop)) { - $pdf->SetXY($colDef['xStartPos'] + $colDef['title']['padding'][3], $tab_top + $colDef['title']['padding'][0]); - $textWidth = $colDef['width'] - $colDef['title']['padding'][3] - $colDef['title']['padding'][1]; - $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); global $outputlangsbis; if (is_object($outputlangsbis)) { - $pdf->SetXY($colDef['xStartPos'] + $colDef['title']['padding'][3], $tab_top + $colDef['title']['padding'][0] + 4); + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); + } + else { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + } + + $pdf->SetXY($colDef['xStartPos'], $tab_top); + $textWidth = $colDef['width']; + $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); + + + if (is_object($outputlangsbis)) { + $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); } - $this->tabTitleHeight = max($pdf->GetY() - $tab_top + $colDef['title']['padding'][2], $this->tabTitleHeight); + $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); } } } return $this->tabTitleHeight; } + + + + /** + * Define Array Column Field for extrafields + * + * @param object $object common object det + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @return null + */ + public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) + { + global $conf; + + if (!empty($hidedetails)) { + return; + } + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + + if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Dont display separator yet even is set to be displayed (not compatible yet) + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') + { + continue; + } + + // Enable extrafield ? + $enabled = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if ($printable === 1 || $printable === 2) { + $enabled = 1; + } + // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols + } + + if (!$enabled) { continue; } // don't wast resourses if we don't need them... + + // Load language if required + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); + + // TODO : add more extrafield customisation capacities for PDF like width, rank... + + // set column definition + $def = array( + 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), + 'width' => 25, // in mm + 'status' => boolval($enabled), + 'title' => array( + 'label' => $outputlangs->transnoentities($label) + ), + 'content' => array( + 'align' => 'C' + ), + 'border-left' => true, // add left line separator + ); + + $alignTypeRight = array('double', 'int', 'price'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { + $def['content']['align'] = 'R'; + } + + $alignTypeLeft = array('text', 'html'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { + $def['content']['align'] = 'L'; + } + + + // for extrafields we use rank of extrafield to place it on PDF + $this->insertNewColumnDef("options_".$key, $def); + } + } + } } diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index c7dbab57b31..e1246d8bc3f 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -337,7 +337,7 @@ abstract class CommonObject /** * @deprecated - * @see $note_public + * @see $note_private */ public $note; @@ -491,6 +491,7 @@ abstract class CommonObject return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : ''); } + /** * Return customer ref for screen output. * @@ -559,6 +560,28 @@ abstract class CommonObject return dol_trunc($ret, $maxlen); } + /** + * Return clicable link of object (with eventually picto) + * + * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link) + * @return string HTML Code for Kanban thumb. + */ + public function getKanbanView($option = '') + { + $return = '
    '; + $return .= '
    '; + $return .= ''; + $return .= ''; // Can be image + $return .= ''; + $return .= '
    '; + $return .= ''.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).''; + $return .= '
    '; + $return .= '
    '; + $return .= '
    '; + + return $return; + } + /** * Return full address of contact * @@ -1080,7 +1103,7 @@ abstract class CommonObject * Get array of all contacts for an object * * @param int $status Status of links to get (-1=all) - * @param string $source Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user) + * @param string $source Source of contact: 'external' or 'thirdparty' (llx_socpeople) or 'internal' (llx_user) * @param int $list 0:Return array contains all properties, 1:Return array contains just id * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...) * @return array|int Array of contacts, -1 if error @@ -1242,14 +1265,15 @@ abstract class CommonObject /** * Return array with list of possible values for type of contacts * - * @param string $source 'internal', 'external' or 'all' - * @param int $option 0=Return array id->label, 1=Return array code->label - * @param int $activeonly 0=all status of contact, 1=only the active - * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') - * @param string $element Filter Element Type - * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) + * @param string $source 'internal', 'external' or 'all' + * @param int $option 0=Return array id->label, 1=Return array code->label + * @param int $activeonly 0=all status of contact, 1=only the active + * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') + * @param string $element Filter on 1 element type + * @param string $excludeelement Exclude 1 element type. Example: 'agenda' + * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) */ - public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '') + public function listeTypeContacts($source = 'internal', $option = 0, $activeonly = 0, $code = '', $element = '', $excludeelement = '') { // phpcs:enable global $langs, $conf; @@ -1260,8 +1284,12 @@ abstract class CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; $sqlWhere = array(); - if (!empty($element)) + if (!empty($element)) { $sqlWhere[] = " tc.element='".$this->db->escape($element)."'"; + } + if (!empty($excludeelement)) { + $sqlWhere[] = " tc.element <> '".$this->db->escape($excludeelement)."'"; + } if ($activeonly == 1) $sqlWhere[] = " tc.active=1"; // only the active types @@ -1278,24 +1306,25 @@ abstract class CommonObject $sql .= $this->db->order('tc.element, tc.position', 'ASC'); - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $num = $this->db->num_rows($resql); if ($num > 0) { while ($obj = $this->db->fetch_object($resql)) { + $modulename = $obj->element; if (strpos($obj->element, 'project') !== false) { - $element = 'projet'; + $modulename = 'projet'; } elseif ($obj->element == 'contrat') { $element = 'contract'; + } elseif ($obj->element == 'action') { + $modulename = 'agenda'; } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') { - $element = 'fournisseur'; + $modulename = 'fournisseur'; } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') { - $element = 'fournisseur'; - } else { - $element = $obj->element; + $modulename = 'fournisseur'; } - if ($conf->{$element}->enabled) { + if ($conf->{$modulename}->enabled) { $libelle_element = $langs->trans('ContactDefault_'.$obj->element); $transkey = "TypeContact_".$this->element."_".$source."_".$obj->code; $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); @@ -1701,7 +1730,7 @@ abstract class CommonObject $sql .= " WHERE ".$id_field." = ".$id; - dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); + dol_syslog(__METHOD__."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1768,14 +1797,14 @@ abstract class CommonObject // this->ismultientitymanaged contains // 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table $aliastablesociete = 's'; - if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element + if ($this->element == 'societe') $aliastablesociete = 'te'; // te as table_element $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) && ! is_numeric($this->ismultientitymanaged)) { + if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { $tmparray = explode('@', $this->ismultientitymanaged); $sql .= ", ".MAIN_DB_PREFIX.$tmparray[1]." as ".($tmparray[1] == 'societe' ? 's' : 'parenttable'); // If we need to link to this table to limit select to entity } @@ -1790,7 +1819,7 @@ abstract class CommonObject if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility $sql .= $filter; } - if (isset($this->ismultientitymanaged) && ! is_numeric($this->ismultientitymanaged)) { + if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged)) { $tmparray = explode('@', $this->ismultientitymanaged); $sql .= ' AND te.'.$tmparray[0].' = '.($tmparray[1] == 'societe' ? 's' : 'parenttable').'.rowid'; // If we need to link to this table to limit select to entity } @@ -1807,7 +1836,7 @@ abstract class CommonObject $sql .= ' AND te.entity IN ('.getEntity($this->element).')'; } } - if (isset($this->ismultientitymanaged) && ! is_numeric($this->ismultientitymanaged) && $this->element != 'societe') { + if (isset($this->ismultientitymanaged) && !is_numeric($this->ismultientitymanaged) && $this->element != 'societe') { $tmparray = explode('@', $this->ismultientitymanaged); $sql .= ' AND parenttable.entity IN ('.getEntity($tmparray[1]).')'; } @@ -2920,7 +2949,7 @@ abstract class CommonObject $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER"; elseif ($this->element == 'facture' || $this->element == 'invoice') $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE"; - elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice') + elseif ($this->element == 'facture_fourn' || $this->element == 'supplier_invoice' || $this->element == 'invoice_supplier') $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE"; elseif ($this->element == 'order_supplier' || $this->element == 'supplier_order') $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER"; @@ -3340,6 +3369,9 @@ abstract class CommonObject elseif ($objecttype == 'subscription') { $classpath = 'adherents/class'; $module = 'adherent'; } + elseif ($objecttype == 'contact') { + $module = 'societe'; + } // Set classfile $classfile = strtolower($subelement); $classname = ucfirst($subelement); @@ -3362,6 +3394,9 @@ abstract class CommonObject elseif ($objecttype == 'subscription') { $classfile = 'subscription'; $classname = 'Subscription'; } + elseif ($objecttype == 'project' || $objecttype == 'projet') { + $classpath = 'projet/class'; $classfile = 'project'; $classname = 'Project'; + } // Here $module, $classfile and $classname are set if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) @@ -4048,6 +4083,7 @@ abstract class CommonObject // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); foreach ($dirtpls as $module => $reldir) { @@ -4090,7 +4126,7 @@ abstract class CommonObject */ public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/core/tpl') { - global $conf, $hookmanager, $langs, $user, $object, $form, $extrafields; + global $conf, $hookmanager, $langs, $user, $form, $extrafields, $object; // TODO We should not use global var for this global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax; @@ -4114,6 +4150,7 @@ abstract class CommonObject { // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); foreach ($dirtpls as $module => $reldir) { @@ -4180,7 +4217,7 @@ abstract class CommonObject * @param string $buyer Object of buyer third party * @param int $selected Object line selected * @param Extrafields $extrafields Object of extrafields - * @param string $defaulttpldir Directory where to find the template + * @param string $defaulttpldir Directory where to find the template (deprecated) * @return void */ public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/core/tpl') @@ -4193,15 +4230,9 @@ abstract class CommonObject $element = $this->element; - $text = ''; $description = ''; $type = 0; + $text = ''; $description = ''; - // Show product and description - $type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type); - // Try to enhance type detection using date_start and date_end for free lines where type was not saved. - if (!empty($line->date_start)) $type = 1; // deprecated - if (!empty($line->date_end)) $type = 1; // deprecated - - // Ligne en mode visu + // Line in view mode if ($action != 'editline' || $selected != $line->id) { // Product @@ -4252,6 +4283,7 @@ abstract class CommonObject // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); foreach ($dirtpls as $module => $reldir) { @@ -4277,12 +4309,12 @@ abstract class CommonObject if ($this->statut == 0 && $action == 'editline' && $selected == $line->id) { $label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : '')); - $placeholder = ' placeholder="'.$langs->trans("Label").'"'; $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU'); // Output template part (modules that overwrite templates must declare this into descriptor) // Use global variables + $dateSelector + $seller and $buyer + // Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine. $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); foreach ($dirtpls as $module => $reldir) { @@ -4744,6 +4776,7 @@ abstract class CommonObject { if (!dol_is_file($srctemplatepath)) { + dol_syslog("Failed to locate template file ".$srctemplatepath, LOG_WARNING); $this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound'; return -1; } @@ -4944,7 +4977,7 @@ abstract class CommonObject global $conf, $_POST; // If param here has been posted, we use this value first. - if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2); + if (GETPOSTISSET($fieldname)) return GETPOST($fieldname, 'alphanohtml', 3); if (isset($alternatevalue)) return $alternatevalue; @@ -5384,7 +5417,7 @@ abstract class CommonObject // Add field of attribute if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator) { - if ($new_array_options[$key] != '') + if ($new_array_options[$key] != '' || $new_array_options[$key] == '0') { $sql .= ",'".$this->db->escape($new_array_options[$key])."'"; } @@ -5486,7 +5519,7 @@ abstract class CommonObject $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value == '') + elseif ($value === '') { $this->array_options["options_".$key] = null; } @@ -5499,7 +5532,7 @@ abstract class CommonObject $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } - elseif ($value == '') + elseif ($value === '') { $this->array_options["options_".$key] = null; } @@ -5557,7 +5590,7 @@ abstract class CommonObject if ($error) { - dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + dol_syslog(__METHOD__.$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -5595,7 +5628,7 @@ abstract class CommonObject $form = new Form($this->db); } - if (! empty($this->fields)) { + if (!empty($this->fields)) { $val = $this->fields[$key]; } @@ -6624,7 +6657,12 @@ abstract class CommonObject if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue; // @todo Add test also on 'enabled' (different than 'list' that is 'visibility') - //$enabled = 1; + $enabled = 1; + if ($enabled && isset($extrafields->attributes[$this->table_element]['enabled'][$key])) + { + $enabled = dol_eval($extrafields->attributes[$this->table_element]['enabled'][$key], 1); + } + if (empty($enabled)) continue; $visibility = 1; if ($visibility && isset($extrafields->attributes[$this->table_element]['list'][$key])) @@ -6757,7 +6795,8 @@ abstract class CommonObject if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' *'; } else { if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired'; - $out .= '">'; + $out .= '"'; + $out .= '>'; if (!empty($extrafields->attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$this->table_element]['help'][$key]); else $out .= $labeltoshow; } diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 4f5602fc5ef..9a804256dac 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -293,30 +293,30 @@ class Conf $rootfortemp = empty($this->global->MAIN_TEMP_DIR) ? $rootfordata : $this->global->MAIN_TEMP_DIR; // Define default dir_output and dir_temp for directories of modules - foreach($this->modules as $module) + foreach ($this->modules as $module) { //var_dump($module); // For multicompany sharings - $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module); - $this->$module->multidir_temp = array($this->entity => $rootfortemp."/".$module."/temp"); + $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module); + $this->$module->multidir_temp = array($this->entity => $rootfortemp."/".$module."/temp"); // For backward compatibility - $this->$module->dir_output = $rootfordata."/".$module; - $this->$module->dir_temp = $rootfortemp."/".$module."/temp"; + $this->$module->dir_output = $rootfordata."/".$module; + $this->$module->dir_temp = $rootfortemp."/".$module."/temp"; } // External modules storage - if (! empty($this->modules_parts['dir'])) + if (!empty($this->modules_parts['dir'])) { - foreach($this->modules_parts['dir'] as $module => $dirs) + foreach ($this->modules_parts['dir'] as $module => $dirs) { - if (! empty($this->$module->enabled)) + if (!empty($this->$module->enabled)) { - foreach($dirs as $type => $name) // $type is 'output' or 'temp' + foreach ($dirs as $type => $name) // $type is 'output' or 'temp' { - $multidirname = 'multidir_'.$type; - $dirname = 'dir_'.$type; + $multidirname = 'multidir_'.$type; + $dirname = 'dir_'.$type; - if($type != 'temp') + if ($type != 'temp') { // For multicompany sharings $this->$module->$multidirname = array($this->entity => $rootfordata."/".$name); @@ -338,90 +338,90 @@ class Conf } // For mycompany storage - $this->mycompany->dir_output = $rootfordata."/mycompany"; - $this->mycompany->dir_temp = $rootfortemp."/mycompany/temp"; + $this->mycompany->dir_output = $rootfordata."/mycompany"; + $this->mycompany->dir_temp = $rootfortemp."/mycompany/temp"; // For admin storage - $this->admin->dir_output = $rootfordata.'/admin'; - $this->admin->dir_temp = $rootfortemp.'/admin/temp'; + $this->admin->dir_output = $rootfordata.'/admin'; + $this->admin->dir_temp = $rootfortemp.'/admin/temp'; // For user storage - $this->user->multidir_output = array($this->entity => $rootfordata."/users"); - $this->user->multidir_temp = array($this->entity => $rootfortemp."/users/temp"); + $this->user->multidir_output = array($this->entity => $rootfordata."/users"); + $this->user->multidir_temp = array($this->entity => $rootfortemp."/users/temp"); // For backward compatibility - $this->user->dir_output = $rootforuser."/users"; - $this->user->dir_temp = $rootfortemp."/users/temp"; + $this->user->dir_output = $rootforuser."/users"; + $this->user->dir_temp = $rootfortemp."/users/temp"; // For usergroup storage - $this->usergroup->dir_output = $rootforuser."/usergroups"; - $this->usergroup->dir_temp = $rootfortemp."/usergroups/temp"; + $this->usergroup->dir_output = $rootforuser."/usergroups"; + $this->usergroup->dir_temp = $rootfortemp."/usergroups/temp"; // For proposal storage - $this->propal->multidir_output = array($this->entity => $rootfordata."/propale"); - $this->propal->multidir_temp = array($this->entity => $rootfortemp."/propale/temp"); + $this->propal->multidir_output = array($this->entity => $rootfordata."/propale"); + $this->propal->multidir_temp = array($this->entity => $rootfortemp."/propale/temp"); // For backward compatibility - $this->propal->dir_output = $rootfordata."/propale"; - $this->propal->dir_temp = $rootfortemp."/propale/temp"; + $this->propal->dir_output = $rootfordata."/propale"; + $this->propal->dir_temp = $rootfortemp."/propale/temp"; // For medias storage - $this->medias->multidir_output = array($this->entity => $rootfordata."/medias"); - $this->medias->multidir_temp = array($this->entity => $rootfortemp."/medias/temp"); + $this->medias->multidir_output = array($this->entity => $rootfordata."/medias"); + $this->medias->multidir_temp = array($this->entity => $rootfortemp."/medias/temp"); // Exception: Some dir are not the name of module. So we keep exception here for backward compatibility. // Sous module bons d'expedition - $this->expedition_bon->enabled=(! empty($this->global->MAIN_SUBMODULE_EXPEDITION)?$this->global->MAIN_SUBMODULE_EXPEDITION:0); + $this->expedition_bon->enabled = (!empty($this->global->MAIN_SUBMODULE_EXPEDITION) ? $this->global->MAIN_SUBMODULE_EXPEDITION : 0); // Sous module bons de livraison - $this->livraison_bon->enabled=(! empty($this->global->MAIN_SUBMODULE_LIVRAISON)?$this->global->MAIN_SUBMODULE_LIVRAISON:0); + $this->livraison_bon->enabled = (!empty($this->global->MAIN_SUBMODULE_LIVRAISON) ? $this->global->MAIN_SUBMODULE_LIVRAISON : 0); // Module fournisseur - if (! empty($this->fournisseur)) + if (!empty($this->fournisseur)) { - $this->fournisseur->commande=new stdClass(); - $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); - $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); - $this->fournisseur->commande->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility - $this->fournisseur->commande->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility + $this->fournisseur->commande = new stdClass(); + $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); + $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); + $this->fournisseur->commande->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility + $this->fournisseur->commande->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility - $this->fournisseur->facture=new stdClass(); - $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); - $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); - $this->fournisseur->facture->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility - $this->fournisseur->facture->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility + $this->fournisseur->facture = new stdClass(); + $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); + $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); + $this->fournisseur->facture->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility + $this->fournisseur->facture->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility - $this->supplierproposal=new stdClass(); - $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal"); - $this->supplierproposal->multidir_temp = array($this->entity => $rootfortemp."/supplier_proposal/temp"); - $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility - $this->supplierproposal->dir_temp = $rootfortemp."/supplier_proposal/temp"; // For backward compatibility + $this->supplierproposal = new stdClass(); + $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal"); + $this->supplierproposal->multidir_temp = array($this->entity => $rootfortemp."/supplier_proposal/temp"); + $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility + $this->supplierproposal->dir_temp = $rootfortemp."/supplier_proposal/temp"; // For backward compatibility - $this->fournisseur->payment=new stdClass(); - $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata."/fournisseur/payment"); - $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/payment/temp"); - $this->fournisseur->payment->dir_output = $rootfordata."/fournisseur/payment"; // For backward compatibility - $this->fournisseur->payment->dir_temp = $rootfortemp."/fournisseur/payment/temp"; // For backward compatibility + $this->fournisseur->payment = new stdClass(); + $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata."/fournisseur/payment"); + $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/payment/temp"); + $this->fournisseur->payment->dir_output = $rootfordata."/fournisseur/payment"; // For backward compatibility + $this->fournisseur->payment->dir_temp = $rootfortemp."/fournisseur/payment/temp"; // For backward compatibility // To prepare split of module fournisseur into fournisseur + supplier_order + supplier_invoice - if (! empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // By default, if module supplier is on, we set new properties + if (!empty($this->fournisseur->enabled) && empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // By default, if module supplier is on, we set new properties { if (empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // This can be set to 1 once modules purchase order and supplier invoice exists { - $this->supplier_order=new stdClass(); - $this->supplier_order->enabled = 1; - $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); - $this->supplier_order->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); - $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility - $this->supplier_order->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility + $this->supplier_order = new stdClass(); + $this->supplier_order->enabled = 1; + $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande"); + $this->supplier_order->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/commande/temp"); + $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility + $this->supplier_order->dir_temp = $rootfortemp."/fournisseur/commande/temp"; // For backward compatibility } if (empty($this->global->MAIN_USE_NEW_SUPPLIERMOD)) // This can be set to 1 once modules purchase order and supplier invoice exists { - $this->supplier_invoice=new stdClass(); - $this->supplier_invoice->enabled = 1; - $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); - $this->supplier_invoice->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); - $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility - $this->supplier_invoice->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility + $this->supplier_invoice = new stdClass(); + $this->supplier_invoice->enabled = 1; + $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture"); + $this->supplier_invoice->multidir_temp = array($this->entity => $rootfortemp."/fournisseur/facture/temp"); + $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility + $this->supplier_invoice->dir_temp = $rootfortemp."/fournisseur/facture/temp"; // For backward compatibility } } } @@ -438,22 +438,22 @@ class Conf $this->service->dir_temp = $rootfortemp."/produit/temp"; // Module productbatch - $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot"); - $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/produitlot/temp"); + $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot"); + $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/produitlot/temp"); // Module contrat - $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); - $this->contrat->multidir_temp = array($this->entity => $rootfortemp."/contract/temp"); + $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); + $this->contrat->multidir_temp = array($this->entity => $rootfortemp."/contract/temp"); // For backward compatibility - $this->contrat->dir_output = $rootfordata."/contract"; - $this->contrat->dir_temp = $rootfortemp."/contract/temp"; + $this->contrat->dir_output = $rootfordata."/contract"; + $this->contrat->dir_temp = $rootfortemp."/contract/temp"; // Module bank $this->bank->multidir_output = array($this->entity => $rootfordata."/bank"); $this->bank->multidir_temp = array($this->entity => $rootfortemp."/bank/temp"); // For backward compatibility - $this->bank->dir_output = $rootfordata."/bank"; - $this->bank->dir_temp = $rootfortemp."/bank/temp"; + $this->bank->dir_output = $rootfordata."/bank"; + $this->bank->dir_temp = $rootfortemp."/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 @@ -527,7 +527,7 @@ class Conf if (empty($this->global->MAIN_THEME)) $this->global->MAIN_THEME = "eldy"; if (!empty($this->global->MAIN_FORCETHEME)) $this->global->MAIN_THEME = $this->global->MAIN_FORCETHEME; $this->theme = $this->global->MAIN_THEME; - $this->css = "/theme/".$this->theme."/style.css.php"; + $this->css = "/theme/".$this->theme."/style.css.php"; // conf->email_from = email pour envoi par dolibarr des mails automatiques $this->email_from = "robot@example.com"; @@ -681,10 +681,10 @@ 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; - if (!isset($this->global->MAIN_USE_OLD_TITLE_BUTTON)) $this->global->MAIN_USE_OLD_TITLE_BUTTON = 0; + if (!isset($this->global->MAIN_JS_GRAPH)) $this->global->MAIN_JS_GRAPH = 'chart'; // Use chart.js library + if (empty($this->global->MAIN_MODULE_DOLISTORE_API_SRV)) $this->global->MAIN_MODULE_DOLISTORE_API_SRV = 'https://www.dolistore.com'; if (empty($this->global->MAIN_MODULE_DOLISTORE_API_KEY)) $this->global->MAIN_MODULE_DOLISTORE_API_KEY = 'dolistorecatalogpublickey1234567'; diff --git a/htdocs/core/class/coreobject.class.php b/htdocs/core/class/coreobject.class.php index 672697cd0a3..999b01341f0 100644 --- a/htdocs/core/class/coreobject.class.php +++ b/htdocs/core/class/coreobject.class.php @@ -36,7 +36,7 @@ class CoreObject extends CommonObject /** * @var Array $_fields Fields to synchronize with Database */ - protected $fields=array(); + protected $fields = array(); /** * Constructor @@ -70,8 +70,8 @@ class CoreObject extends CommonObject else $this->{$field} = ''; } - $this->to_delete=false; - $this->is_clone=false; + $this->to_delete = false; + $this->is_clone = false; return true; } @@ -110,7 +110,7 @@ class CoreObject extends CommonObject public function fetch($id, $loadChild = true) { $res = $this->fetchCommon($id); - if($res>0) { + if ($res > 0) { if ($loadChild) $this->fetchChild(); } @@ -129,11 +129,11 @@ class CoreObject extends CommonObject */ public function addChild($tabName, $id = 0, $key = 'id', $try_to_load = false) { - if(!empty($id)) + if (!empty($id)) { - foreach($this->{$tabName} as $k=>&$object) + foreach ($this->{$tabName} as $k=>&$object) { - if($object->{$key} === $id) return $k; + if ($object->{$key} === $id) return $k; } } @@ -141,7 +141,7 @@ class CoreObject extends CommonObject $className = ucfirst($tabName); $this->{$tabName}[$k] = new $className($this->db); - if($id>0 && $key==='id' && $try_to_load) + if ($id > 0 && $key === 'id' && $try_to_load) { $this->{$tabName}[$k]->fetch($id); } @@ -181,20 +181,20 @@ class CoreObject extends CommonObject { if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { - foreach($this->childtables as &$childTable) + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); - $this->{$className}=array(); + $this->{$className} = array(); $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$childTable.' WHERE '.$this->fk_element.' = '.$this->id; $res = $this->db->query($sql); - if($res) + if ($res) { - while($obj = $this->db->fetch_object($res)) + while ($obj = $this->db->fetch_object($res)) { - $o=new $className($this->db); + $o = new $className($this->db); $o->fetch($obj->rowid); $this->{$className}[] = $o; @@ -216,19 +216,19 @@ class CoreObject extends CommonObject */ public function saveChild(User &$user) { - if($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) + if ($this->withChild && !empty($this->childtables) && !empty($this->fk_element)) { - foreach($this->childtables as &$childTable) + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); - if(!empty($this->{$className})) + if (!empty($this->{$className})) { - foreach($this->{$className} as $i => &$object) + foreach ($this->{$className} as $i => &$object) { $object->{$this->fk_element} = $this->id; $object->update($user); - if($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete==true) unset($this->{$className}[$i]); + if ($this->unsetChildDeleted && isset($object->to_delete) && $object->to_delete == true) unset($this->{$className}[$i]); } } } @@ -245,7 +245,7 @@ class CoreObject extends CommonObject public function update(User &$user) { if (empty($this->id)) return $this->create($user); // To test, with that, no need to test on high level object, the core decide it, update just needed - elseif (isset($this->to_delete) && $this->to_delete==true) return $this->delete($user); + elseif (isset($this->to_delete) && $this->to_delete == true) return $this->delete($user); $error = 0; $this->db->begin(); @@ -253,7 +253,7 @@ class CoreObject extends CommonObject $res = $this->updateCommon($user); if ($res) { - $result = $this->call_trigger(strtoupper($this->element). '_UPDATE', $user); + $result = $this->call_trigger(strtoupper($this->element).'_UPDATE', $user); if ($result < 0) $error++; else $this->saveChild($user); } @@ -284,17 +284,17 @@ class CoreObject extends CommonObject */ public function create(User &$user) { - if($this->id > 0) return $this->update($user); + if ($this->id > 0) return $this->update($user); $error = 0; $this->db->begin(); $res = $this->createCommon($user); - if($res) + if ($res) { $this->id = $this->db->last_insert_id($this->table_element); - $result = $this->call_trigger(strtoupper($this->element). '_CREATE', $user); + $result = $this->call_trigger(strtoupper($this->element).'_CREATE', $user); if ($result < 0) $error++; else $this->saveChild($user); } @@ -330,20 +330,20 @@ class CoreObject extends CommonObject $error = 0; $this->db->begin(); - $result = $this->call_trigger(strtoupper($this->element). '_DELETE', $user); + $result = $this->call_trigger(strtoupper($this->element).'_DELETE', $user); if ($result < 0) $error++; if (!$error) { $this->deleteCommon($user); - if($this->withChild && !empty($this->childtables)) + if ($this->withChild && !empty($this->childtables)) { - foreach($this->childtables as &$childTable) + foreach ($this->childtables as &$childTable) { $className = ucfirst($childTable); if (!empty($this->{$className})) { - foreach($this->{$className} as &$object) + foreach ($this->{$className} as &$object) { $object->delete($user); } @@ -376,7 +376,7 @@ class CoreObject extends CommonObject */ public function getDate($field, $format = '') { - if(empty($this->{$field})) return ''; + if (empty($this->{$field})) return ''; else { return dol_print_date($this->{$field}, $format); @@ -416,24 +416,20 @@ class CoreObject extends CommonObject { foreach ($Tab as $key => $value) { - if($this->checkFieldType($key, 'date')) + if ($this->checkFieldType($key, 'date')) { $this->setDate($key, $value); } - elseif( $this->checkFieldType($key, 'array')) - { - $this->{$key} = $value; - } - elseif( $this->checkFieldType($key, 'float') ) + elseif ($this->checkFieldType($key, 'float')) { $this->{$key} = (double) price2num($value); } - elseif( $this->checkFieldType($key, 'int') ) { + elseif ($this->checkFieldType($key, 'int')) { $this->{$key} = (int) price2num($value); } else { - $this->{$key} = $value; + $this->{$key} = dol_string_nohtmltag($value); } } diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index ca40910aacd..c3707b18972 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -504,15 +504,16 @@ class DiscountAbsolute * @param string $filter Filtre autre * @param int $maxvalue Filter on max value for discount * @param int $discount_type 0 => customer discount, 1 => supplier discount + * @param int $multicurrency Return multicurrency_amount instead of amount * @return int <0 if KO, amount otherwise */ - public function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0) + public function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0) { global $conf; dol_syslog(get_class($this)."::getAvailableDiscounts discount_type=".$discount_type, LOG_DEBUG); - $sql = "SELECT SUM(rc.amount_ttc) as amount"; + $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"; $sql .= " WHERE rc.entity = ".$conf->entity; $sql .= " AND rc.discount_type=".intval($discount_type); @@ -535,6 +536,11 @@ class DiscountAbsolute //print 'zz'.$obj->amount; //$obj = $this->db->fetch_object($resql); //} + if ($multicurrency) + { + return $obj->amount_multicurrency; + } + return $obj->amount; } return -1; @@ -604,14 +610,14 @@ 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 as f'; $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; - $sql .= ' AND (f.type = 2 OR f.type = 0)'; // Find discount coming from credit note or excess received + $sql .= ' AND f.type IN (' . $invoice::TYPE_STANDARD . ', ' . $invoice::TYPE_CREDIT_NOTE . ', ' . $invoice::TYPE_SITUATION . ')'; // Find discount coming from credit note or excess received } elseif ($invoice->element == 'invoice_supplier') { $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 paid + $sql .= ' AND f.type IN (' . $invoice::TYPE_STANDARD . ', ' . $invoice::TYPE_CREDIT_NOTE . ')'; // Find discount coming from credit note or excess paid } else { diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 06b6ec2d949..de5ef1f2e9f 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -85,44 +85,6 @@ class DolEditor if ($okforextendededitor === 'ace') $this->tool = 'ace'; //if ($conf->dol_use_jmobile) $this->tool = 'textarea'; // ckeditor and ace seems ok with mobile - // Define content and some properties - if ($this->tool == 'ckeditor') - { - $content = dol_htmlentitiesbr($content); // If content is not HTML, we convert to HTML. - } - if ($this->tool == 'fckeditor') - { - require_once DOL_DOCUMENT_ROOT.'/includes/fckeditor/fckeditor.php'; - - $content = dol_htmlentitiesbr($content); // If content is not HTML, we convert to HTML. - - $this->editor = new FCKeditor($htmlname); - $this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/'; - $this->editor->Value = $content; - $this->editor->Height = $height; - if (!empty($width)) $this->editor->Width = $width; - $this->editor->ToolbarSet = $shorttoolbarname; // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js - $this->editor->Config['AutoDetectLanguage'] = 'true'; // Language of user (browser) - $this->editor->Config['ToolbarLocation'] = $toolbarlocation ? $toolbarlocation : 'In'; - $this->editor->Config['ToolbarStartExpanded'] = $toolbarstartexpanded; - - // Rem: Le forcage de ces 2 parametres ne semble pas fonctionner. - // Dolibarr utilise toujours liens avec modulepart='fckeditor' quelque soit modulepart. - // Ou se trouve donc cette valeur /viewimage.php?modulepart=fckeditor&file=' ? - $modulepart = 'fckeditor'; - $this->editor->Config['UserFilesPath'] = '/viewimage.php?modulepart='.$modulepart.'&entity='.$conf->entity.'&file='; - $this->editor->Config['UserFilesAbsolutePath'] = DOL_DATA_ROOT.'/'.$modulepart.'/'; - - $this->editor->Config['LinkBrowser'] = ($uselocalbrowser ? 'true' : 'false'); - $this->editor->Config['ImageBrowser'] = ($uselocalbrowser ? 'true' : 'false'); - - if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js')) - { - $this->editor->Config['CustomConfigurationsPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js'; - $this->editor->Config['SkinPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/'; - } - } - // Define some properties if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) { @@ -172,7 +134,8 @@ class DolEditor { $found = 1; //$out.= ''; diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 9aa54498edc..d59ab8ce6bc 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -30,10 +30,10 @@ * $dolgraph->SetTitle($langs->transnoentities('MyTitle').'
    '.$langs->transnoentities('MyTitlePercent').'%'); * $dolgraph->SetMaxValue(50); * $dolgraph->SetData($data); - * $dolgraph->setShowLegend(1); + * $dolgraph->setShowLegend(2); * $dolgraph->setShowPercent(1); * $dolgraph->SetType(array('pie')); - * $dolgraph->setWidth('100%'); + * $dolgraph->setHeight('200'); * $dolgraph->draw('idofgraph'); * print $dolgraph->show($total?0:1); */ @@ -92,31 +92,13 @@ class DolGraph /** * Constructor * - * @param string $library 'jflot' (default) or 'artichow' (no more supported) + * @param string $library 'auto' (default) */ - public function __construct($library = 'jflot') + public function __construct($library = 'auto') { global $conf; global $theme_bordercolor, $theme_datacolor, $theme_bgcolor; - // To use old feature - if ($library == 'artichow') - { - $this->_library = 'artichow'; - - // Test if module GD present - $modules_list = get_loaded_extensions(); - $isgdinstalled = 0; - foreach ($modules_list as $module) - { - if ($module == 'gd') $isgdinstalled = 1; - } - if (!$isgdinstalled) - { - $this->error = "Error: PHP GD module is not available. It is required to build graphics."; - } - } - $this->bordercolor = array(235, 235, 224); $this->datacolor = array(array(120, 130, 150), array(160, 160, 180), array(190, 190, 220)); $this->bgcolor = array(235, 235, 224); @@ -130,23 +112,14 @@ class DolGraph if (isset($theme_bgcolor)) $this->bgcolor = $theme_bgcolor; } //print 'bgcolor: '.join(',',$this->bgcolor).'
    '; + + $this->_library = $library; + if ($this->_library == 'auto') { + $this->_library = (empty($conf->global->MAIN_JS_GRAPH) ? 'jflot' : $conf->global->MAIN_JS_GRAPH); + } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Set Y precision - * - * @param float $which_prec Precision - * @return boolean - * @deprecated - */ - public function SetPrecisionY($which_prec) - { - // phpcs:enable - return true; - } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2 @@ -287,7 +260,8 @@ class DolGraph /** * Set type * - * @param array $type Array with type for each serie. Example: array('pie'), array('lines',...,'bars') + * @param array $type Array with type for each serie. Example: array('type1', 'type2', ...) where type can be: + * 'pie', 'piesemicircle', 'polar', 'lines', 'linesnopoint', 'bars', ... * @return void */ public function SetType($type) @@ -448,7 +422,7 @@ class DolGraph /** * Show legend or not * - * @param int $showlegend 1=Show legend (default), 0=Hide legend + * @param int $showlegend 1=Show legend (default), 0=Hide legend, 2=Show legend on right * @return void */ public function setShowLegend($showlegend) @@ -561,6 +535,8 @@ class DolGraph public function GetMaxValueInData() { // phpcs:enable + if (!is_array($this->data)) return 0; + $k = 0; $vals = array(); @@ -588,6 +564,8 @@ class DolGraph public function GetMinValueInData() { // phpcs:enable + if (!is_array($this->data)) return 0; + $k = 0; $vals = array(); @@ -686,188 +664,6 @@ class DolGraph call_user_func_array(array($this, $call), array($file, $fileurl)); } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Build a graph onto disk using Artichow library and return img string to it - * - * @param string $file Image file name to use if we save onto disk - * @param string $fileurl Url path to show image if saved onto disk - * @return void - */ - private function draw_artichow($file, $fileurl) - { - // phpcs:enable - global $artichow_defaultfont; - - dol_syslog(get_class($this)."::draw_artichow this->type=".join(',', $this->type)); - - if (!defined('SHADOW_RIGHT_TOP')) define('SHADOW_RIGHT_TOP', 3); - if (!defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND', 2); - if (!defined('LEGEND_LINE')) define('LEGEND_LINE', 1); - - // Create graph - $classname = ''; - if (!isset($this->type[0]) || $this->type[0] == 'bars') $classname = 'BarPlot'; // Only one type (first one) is supported by artichow - elseif ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname = 'LinePlot'; - else $classname = 'TypeUnknown'; - include_once ARTICHOW_PATH.$classname.'.class.php'; - - // Definition de couleurs - $bgcolor = new Color($this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]); - $bgcolorgrid = new Color($this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]); - $colortrans = new Color(0, 0, 0, 100); - $colorsemitrans = new Color(255, 255, 255, 60); - $colorgradient = new LinearGradient(new Color(235, 235, 235), new Color(255, 255, 255), 0); - $colorwhite = new Color(255, 255, 255); - - // Graph - $graph = new Graph($this->width, $this->height); - $graph->border->hide(); - $graph->setAntiAliasing(true); - if (isset($this->title)) - { - $graph->title->set($this->title); - //print $artichow_defaultfont;exit; - $graph->title->setFont(new $artichow_defaultfont(10)); - } - - if (is_array($this->bgcolor)) $graph->setBackgroundColor($bgcolor); - else $graph->setBackgroundGradient($colorgradient); - - $group = new PlotGroup; - //$group->setSpace(5, 5, 0, 0); - - $paddleft = 50; - $paddright = 10; - $strl = dol_strlen(max(abs($this->MaxValue), abs($this->MinValue))); - if ($strl > 6) $paddleft += ($strl * 4); - $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->setBackgroundColor($colorsemitrans); - - if (is_array($this->bgcolorgrid)) $group->grid->setBackgroundColor($bgcolorgrid); - else $group->grid->setBackgroundColor($colortrans); - - if ($this->hideXGrid) $group->grid->hideVertical(true); - if ($this->hideYGrid) $group->grid->hideHorizontal(true); - - // On boucle sur chaque lot de donnees - $legends = array(); - $i = 0; - $nblot = count($this->data[0]) - 1; - - while ($i < $nblot) - { - $x = 0; - $values = array(); - foreach ($this->data as $key => $valarray) - { - $legends[$x] = $valarray[0]; - $values[$x] = $valarray[$i + 1]; - $x++; - } - - // We fix unknown values to null - $newvalues = array(); - foreach ($values as $val) - { - $newvalues[] = (is_numeric($val) ? $val : null); - } - - - if ($this->type[0] == 'bars') - { - //print "Lot de donnees $i
    "; - //print_r($values); - //print '
    '; - - $color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20); - $colorbis = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 50); - - $colorgrey = new Color(100, 100, 100); - $colorborder = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]); - - if ($this->mode == 'side') $plot = new BarPlot($newvalues, $i + 1, $nblot); - if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot - $i - 1) * 5); - - $plot->barBorder->setColor($colorgrey); - //$plot->setBarColor($color); - $plot->setBarGradient(new LinearGradient($colorbis, $color, 90)); - - if ($this->mode == 'side') $plot->setBarPadding(0.1, 0.1); - if ($this->mode == 'depth') $plot->setBarPadding(0.1, 0.4); - if ($this->mode == 'side') $plot->setBarSpace(5); - if ($this->mode == 'depth') $plot->setBarSpace(2); - - $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->setSize(1, 0.96); - //$plot->setCenter(0.5, 0.52); - - // Le mode automatique est plus efficace - $plot->SetYMax($this->MaxValue); - $plot->SetYMin($this->MinValue); - } - - if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') - { - $color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20); - $colorbis = new Color(min($this->datacolor[$i][0] + 20, 255), min($this->datacolor[$i][1] + 20, 255), min($this->datacolor[$i][2] + 20, 255), 60); - $colorter = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 90); - - $plot = new LinePlot($newvalues); - //$plot->setSize(1, 0.96); - //$plot->setCenter(0.5, 0.52); - - $plot->setColor($color); - $plot->setThickness(1); - - // Set line background gradient - $plot->setFillGradient(new LinearGradient($colorter, $colorbis, 90)); - - $plot->xAxis->setLabelText($legends); - - // Le mode automatique est plus efficace - $plot->SetYMax($this->MaxValue); - $plot->SetYMin($this->MinValue); - //$plot->setYAxis(0); - //$plot->hideLine(true); - } - - //$plot->reduce(80); // Evite temps d'affichage trop long et nombre de ticks absisce satures - - $group->legend->setTextFont(new $artichow_defaultfont(10)); // This is to force Artichow to use awFileFontDriver to - // solve a bug in Artichow with UTF8 - if (count($this->Legend)) - { - if ($this->type[0] == 'bars') $group->legend->add($plot, $this->Legend[$i], LEGEND_BACKGROUND); - if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $group->legend->add($plot, $this->Legend[$i], LEGEND_LINE); - } - $group->add($plot); - - $i++; - } - - $group->axis->bottom->setLabelText($legends); - $group->axis->bottom->label->setFont(new $artichow_defaultfont(7)); - - //print $group->axis->bottom->getLabelNumber(); - if ($this->labelInterval > 0) $group->axis->bottom->setLabelInterval($this->labelInterval); - - $graph->add($group); - - // Generate file - $graph->draw($file); - - $this->stringtoshow = ''.dol_escape_htmltag($this->title ? $this->title : $this->YLabel).''; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Build a graph using JFlot library. Input when calling this method should be: @@ -875,7 +671,7 @@ class DolGraph * $this->data = array(array(0=>'labelxA',1=>yA1,...,n=>yAn), array('labelxB',yB1,...yBn)); // or when there is n series to show for each x * $this->data = array(array('label'=>'labelxA','data'=>yA), array('labelxB',yB)); // Syntax deprecated * $this->legend= array("Val1",...,"Valn"); // list of n series name - * $this->type = array('bars',...'lines'); or array('pie') + * $this->type = array('bars',...'lines','linesnopoint'); or array('pie') or array('polar') * $this->mode = 'depth' ??? * $this->bgcolorgrid * $this->datacolor @@ -888,7 +684,7 @@ class DolGraph private function draw_jflot($file, $fileurl) { // phpcs:enable - global $langs; + global $conf, $langs; dol_syslog(get_class($this)."::draw_jflot this->type=".join(',', $this->type)." this->MaxValue=".$this->MaxValue); @@ -924,8 +720,7 @@ class DolGraph $x++; } - // TODO Avoid push by adding generated long array... - if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie') + if (isset($this->type[$firstlot]) && in_array($this->type[$firstlot], array('pie', 'piesemicircle', 'polar'))) { foreach ($values as $x => $y) { if (isset($y)) $serie[$i] .= 'd'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n"; @@ -943,38 +738,46 @@ class DolGraph } $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); - $this->stringtoshow = ''."\n"; + $this->stringtoshow = ''."\n"; if (!empty($this->title)) $this->stringtoshow .= '
    '.$this->title.'
    '; if (!empty($this->shownographyet)) { $this->stringtoshow .= '
    '; - $this->stringtoshow .= '
    '.$langs->trans("NotEnoughDataYet").'
    '; + $this->stringtoshow .= '
    '.$langs->trans("NotEnoughDataYet").'...
    '; return; } - $this->stringtoshow .= '
    '."\n"; + + // Start the div that will contains all the graph + $dolxaxisvertical = ''; + if (count($this->data) > 20) $dolxaxisvertical = 'dol-xaxis-vertical'; + $this->stringtoshow .= '
    '."\n"; $this->stringtoshow .= ''."\n"; } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Build a graph using Chart library. Input when calling this method should be: + * $this->data = array(array(0=>'labelxA',1=>yA), array('labelxB',yB)); + * $this->data = array(array(0=>'labelxA',1=>yA1,...,n=>yAn), array('labelxB',yB1,...yBn)); // or when there is n series to show for each x + * $this->data = array(array('label'=>'labelxA','data'=>yA), array('labelxB',yB)); // Syntax deprecated + * $this->legend= array("Val1",...,"Valn"); // list of n series name + * $this->type = array('bars',...'lines', 'linesnopoint'); or array('pie') or array('polar') or array('piesemicircle'); + * $this->mode = 'depth' ??? + * $this->bgcolorgrid + * $this->datacolor + * $this->shownodatagraph + * + * @param string $file Image file name to use to save onto disk (also used as javascript unique id) + * @param string $fileurl Url path to show image if saved onto disk. Never used here. + * @return void + */ + private function draw_chart($file, $fileurl) + { + // phpcs:enable + global $conf, $langs; + + dol_syslog(get_class($this)."::draw_chart this->type=".join(',', $this->type)." this->MaxValue=".$this->MaxValue); + + if (empty($this->width) && empty($this->height)) + { + print 'Error width or height not set'; + return; + } + + $showlegend = $this->showlegend; + + $legends = array(); + $nblot = 0; + if (is_array($this->data)) { + foreach ($this->data as $valarray) // Loop on each x + { + $nblot = max($nblot, count($valarray) - 1); // -1 to remove legend + } + } + //var_dump($nblot); + 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 + + $serie = array(); $arrayofgroupslegend = array(); + //var_dump($this->data); + + $i = $firstlot; + while ($i < $nblot) // Loop on each serie + { + $values = array(); // Array with horizontal y values (specific values of a serie) for each abscisse x (with x=0,1,2,...) + $serie[$i] = ""; + + // Fill array $values + $x = 0; + foreach ($this->data as $valarray) // Loop on each x + { + $legends[$x] = (array_key_exists('label', $valarray) ? $valarray['label'] : $valarray[0]); + $array_of_ykeys = array_keys($valarray); + $alabelexists = 1; + $tmpykey = explode('_', ($array_of_ykeys[$i + ($alabelexists ? 1 : 0)]), 3); + if (!empty($tmpykey[2]) || $tmpykey[2] == '0') { // This is a 'Group by' array + $tmpvalue = (array_key_exists('y_'.$tmpykey[1].'_'.$tmpykey[2], $valarray) ? $valarray['y_'.$tmpykey[1].'_'.$tmpykey[2]] : $valarray[$i + 1]); + $values[$x] = (is_numeric($tmpvalue) ? $tmpvalue : null); + $arrayofgroupslegend[$i] = array( + 'stacknum'=> $tmpykey[1], + 'legend' => $this->Legend[$tmpykey[1]], + 'legendwithgroup' => $this->Legend[$tmpykey[1]].' - '.$tmpykey[2] + ); + } else { + $tmpvalue = (array_key_exists('y_'.$i, $valarray) ? $valarray['y_'.$i] : $valarray[$i + 1]); + //var_dump($i.'_'.$x.'_'.$tmpvalue); + $values[$x] = (is_numeric($tmpvalue) ? $tmpvalue : null); + } + $x++; + } + //var_dump($values); + $j = 0; + foreach ($values as $x => $y) { + if (isset($y)) { + $serie[$i] .= ($j > 0 ? ", " : "").$y; + } else { + $serie[$i] .= ($j > 0 ? ", " : "").'null'; + } + $j++; + } + + $values = null; // Free mem + $i++; + } + //var_dump($serie); + //var_dump($arrayofgroupslegend); + + $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); + + $this->stringtoshow = ''."\n"; + if (!empty($this->title)) $this->stringtoshow .= '
    '.$this->title.'
    '; + if (!empty($this->shownographyet)) + { + $this->stringtoshow .= '
    '; + $this->stringtoshow .= '
    '.$langs->trans("NotEnoughDataYet").'...
    '; + return; + } + + // Start the div that will contains all the graph + $dolxaxisvertical=''; + if (count($this->data) > 20) $dolxaxisvertical='dol-xaxis-vertical'; + // No height for the pie grah + $cssfordiv = 'dolgraphchart'; + if (isset($this->type[$firstlot])) $cssfordiv .= ' dolgraphchar'.$this->type[$firstlot]; + $this->stringtoshow .= '
    '."\n"; + + $this->stringtoshow .= ''."\n"; + } + + /** * Output HTML string to total value * @@ -1155,11 +1313,11 @@ class DolGraph if ($shownographyet) { $s = '
    '; - $s .= '
    '; + $s .= '
    '; if (is_numeric($shownographyet)) { - $s .= $langs->trans("NotEnoughDataYet"); + $s .= $langs->trans("NotEnoughDataYet").'...'; } else { - $s .= $shownographyet; + $s .= $shownographyet.'...'; } $s .= '
    '; return $s; diff --git a/htdocs/core/class/dolreceiptprinter.class.php b/htdocs/core/class/dolreceiptprinter.class.php index e8e43281d79..d241c2a8c5a 100644 --- a/htdocs/core/class/dolreceiptprinter.class.php +++ b/htdocs/core/class/dolreceiptprinter.class.php @@ -49,6 +49,8 @@ * Print object total tax * Print object local tax * Print object total + * Print order lines for Printer1 + * Print order lines for Printer2 * Print payment method * * Code which can be placed everywhere @@ -59,8 +61,6 @@ * Replaced by month number * Replaced by day number * Replaced by day number - * Replaced by table number (for restaurant, bar...) - * Replaced by number of cutlery (for restaurant) * Replaced by object id * Replaced by object ref * Replaced by customer firstname @@ -180,8 +180,6 @@ class dolReceiptPrinter extends Printer 'dol_value_month', 'dol_value_day', 'dol_value_day_letters', - 'dol_value_table', - 'dol_value_cutlery', 'dol_print_payment', 'dol_print_logo', 'dol_print_logo_old', @@ -192,6 +190,8 @@ class dolReceiptPrinter extends Printer 'dol_print_object_local_tax', 'dol_print_object_total', 'dol_print_object_number', + 'dol_print_order_lines_printer1', + 'dol_print_order_lines_printer2', 'dol_value_customer_firstname', 'dol_value_customer_lastname', 'dol_value_customer_mail', @@ -579,15 +579,13 @@ class dolReceiptPrinter extends Printer $this->template = str_replace('', $object->vendor_firstname, $this->template); $this->template = str_replace('', $object->vendor_lastname, $this->template); $this->template = str_replace('', $object->vendor_mail, $this->template); - $this->template = str_replace('', $object->date, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->date_time, $this->template); - $this->template = str_replace('', $object->table, $this->template); - $this->template = str_replace('', $object->cutlery, $this->template); + $this->template = str_replace('', dol_print_date($object->date, 'day'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, 'dayhour'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%Y'), $this->template); + $this->template = str_replace('', $langs->trans("Month".dol_print_date($object->date, '%m')), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%m'), $this->template); + $this->template = str_replace('', dol_print_date($object->date, '%d'), $this->template); + $this->template = str_replace('', $langs->trans("Day".dol_print_date($object->date, '%m')[1]), $this->template); // parse template $p = xml_parser_create(); @@ -726,6 +724,28 @@ class dolReceiptPrinter extends Printer case 'DOL_BEEP': $this->printer->getPrintConnector() -> write("\x1e"); break; + case 'DOL_PRINT_ORDER_LINES_PRINTER1': + foreach ($object->lines as $line) { + if ($line->special_code==1) + { + $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); + $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n"); + } + } + break; + case 'DOL_PRINT_ORDER_LINES_PRINTER2': + foreach ($object->lines as $line) { + if ($line->special_code==2) + { + $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; + $spaces = str_repeat(' ', $spacestoadd); + $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); + $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n"); + } + } + break; default: $this->printer->text($vals[$tplline]['tag']); $this->printer->text($vals[$tplline]['value']); diff --git a/htdocs/core/class/evalmath.class.php b/htdocs/core/class/evalmath.class.php new file mode 100644 index 00000000000..a520ebb3a21 --- /dev/null +++ b/htdocs/core/class/evalmath.class.php @@ -0,0 +1,507 @@ + + * + * ================================================================================ + * + * NAME + * EvalMath - safely evaluate math expressions + * + * SYNOPSIS + * include('evalmath.class.php'); + * $m = new EvalMath; + * // basic evaluation: + * $result = $m->evaluate('2+2'); + * // supports: order of operation; parentheses; negation; built-in functions + * $result = $m->evaluate('-8(5/2)^2*(1-sqrt(4))-8'); + * // create your own variables + * $m->evaluate('a = e^(ln(pi))'); + * // or functions + * $m->evaluate('f(x,y) = x^2 + y^2 - 2x*y + 1'); + * // and then use them + * $result = $m->evaluate('3*f(42,a)'); + * + * DESCRIPTION + * Use the EvalMath class when you want to evaluate mathematical expressions + * from untrusted sources. You can define your own variables and functions, + * which are stored in the object. Try it, it's fun! + * + * METHODS + * $m->evalute($expr) + * Evaluates the expression and returns the result. If an error occurs, + * prints a warning and returns false. If $expr is a function assignment, + * returns true on success. + * + * $m->e($expr) + * A synonym for $m->evaluate(). + * + * $m->vars() + * Returns an associative array of all user-defined variables and values. + * + * $m->funcs() + * Returns an array of all user-defined functions. + * + * PARAMETERS + * $m->suppress_errors + * Set to true to turn off warnings when evaluating expressions + * + * $m->last_error + * If the last evaluation failed, contains a string describing the error. + * (Useful when suppress_errors is on). + * + * $m->last_error_code + * If the last evaluation failed, 2 element array with numeric code and extra info + * + * AUTHOR INFORMATION + * Copyright 2005, Miles Kaufmann. + * + * LICENSE + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * 1 Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * \file core/class/evalmath.class.php + * \ingroup core + * \brief This file for Math evaluation + */ + +/** + * Class EvalMath + */ +class EvalMath +{ + + public $suppress_errors = false; + + public $last_error = null; + + public $last_error_code = null; + + public $v = array('e' => 2.71,'pi' => 3.14159); + + // variables (and constants) + public $f = array(); + + // user-defined functions + public $vb = array('e','pi'); + + // constants + public $fb = array( // built-in functions + 'sin','sinh','arcsin','asin','arcsinh','asinh','cos','cosh','arccos','acos','arccosh','acosh','tan','tanh','arctan','atan','arctanh','atanh','sqrt','abs','ln','log','intval'); + + /** + * Constructor + */ + public function __construct() + { + // make the variables a little more accurate + $this->v['pi'] = pi(); + $this->v['e'] = exp(1); + } + + /** + * Evaluate + * + * @param string $expr String + * @return boolean|number|NULL|mixed Result + */ + public function e($expr) + { + return $this->evaluate($expr); + } + + /** + * Evaluate + * + * @param string $expr String + * @return boolean|number|NULL|mixed Result + */ + public function evaluate($expr) + { + $this->last_error = null; + $this->last_error_code = null; + $expr = trim($expr); + if (substr($expr, - 1, 1) == ';') + $expr = substr($expr, 0, strlen($expr) - 1); // strip semicolons at the end + // =============== + // is it a variable assignment? + $matches = array(); + if (preg_match('/^\s*([a-z]\w*)\s*=\s*(.+)$/', $expr, $matches)) { + if (in_array($matches[1], $this->vb)) { // make sure we're not assigning to a constant + return $this->trigger(1, "cannot assign to constant '$matches[1]'", $matches[1]); + } + if (($tmp = $this->pfx($this->nfx($matches[2]))) === false) + return false; // get the result and make sure it's good + $this->v[$matches[1]] = $tmp; // if so, stick it in the variable array + return $this->v[$matches[1]]; // and return the resulting value + // =============== + // is it a function assignment? + } elseif (preg_match('/^\s*([a-z]\w*)\s*\(\s*([a-z]\w*(?:\s*,\s*[a-z]\w*)*)\s*\)\s*=\s*(.+)$/', $expr, $matches)) { + $fnn = $matches[1]; // get the function name + if (in_array($matches[1], $this->fb)) { // make sure it isn't built in + return $this->trigger(2, "cannot redefine built-in function '$matches[1]()'", $matches[1]); + } + $args = explode(",", preg_replace("/\s+/", "", $matches[2])); // get the arguments + if (($stack = $this->nfx($matches[3])) === false) + return false; // see if it can be converted to postfix + $nbstack = count($stack); + for ($i = 0; $i < $nbstack; $i ++) { // freeze the state of the non-argument variables + $token = $stack[$i]; + if (preg_match('/^[a-z]\w*$/', $token) and ! in_array($token, $args)) { + if (array_key_exists($token, $this->v)) { + $stack[$i] = $this->v[$token]; + } else { + return $this->trigger(3, "undefined variable '$token' in function definition", $token); + } + } + } + $this->f[$fnn] = array('args' => $args,'func' => $stack); + return true; + // =============== + } else { + return $this->pfx($this->nfx($expr)); // straight up evaluation, woo + } + } + + /** + * vars + * + * @return string Output + */ + private function vars() + { + $output = $this->v; + unset($output['pi']); + unset($output['e']); + return $output; + } + + /** + * vars + * + * @return string Output + */ + private function funcs() + { + $output = array(); + foreach ($this->f as $fnn => $dat) + $output[] = $fnn . '(' . implode(',', $dat['args']) . ')'; + return $output; + } + + // ===================== HERE BE INTERNAL METHODS ====================\\ + + /** + * Convert infix to postfix notation + * + * @param string $expr Expression + * @return string Output + */ + private function nfx($expr) + { + $index = 0; + $stack = new EvalMathStack(); + $output = array(); // postfix form of expression, to be passed to pfx() + $expr = trim(strtolower($expr)); + + $ops = array('+','-','*','/','^','_'); + $ops_r = array('+' => 0,'-' => 0,'*' => 0,'/' => 0,'^' => 1); // right-associative operator? + $ops_p = array('+' => 0,'-' => 0,'*' => 1,'/' => 1,'_' => 1,'^' => 2); // operator precedence + + $expecting_op = false; // we use this in syntax-checking the expression + // and determining when a - is a negation + + $matches = array(); + if (preg_match("/[^\w\s+*^\/()\.,-]/", $expr, $matches)) { // make sure the characters are all good + return $this->trigger(4, "illegal character '{$matches[0]}'", $matches[0]); + } + + while (1) { // 1 Infinite Loop ;) + $op = substr($expr, $index, 1); // get the first character at the current index + // find out if we're currently at the beginning of a number/variable/function/parenthesis/operand + $match = array(); + $ex = preg_match('/^([a-z]\w*\(?|\d+(?:\.\d*)?|\.\d+|\()/', substr($expr, $index), $match); + // =============== + if ($op == '-' and ! $expecting_op) { // is it a negation instead of a minus? + $stack->push('_'); // put a negation on the stack + $index ++; + } elseif ($op == '_') { // we have to explicitly deny this, because it's legal on the stack + return $this->trigger(4, "illegal character '_'", "_"); // but not in the input expression + // =============== + } elseif ((in_array($op, $ops) or $ex) and $expecting_op) { // are we putting an operator on the stack? + if ($ex) { // are we expecting an operator but have a number/variable/function/opening parethesis? + $op = '*'; + $index --; // it's an implicit multiplication + } + // heart of the algorithm: + while ($stack->count > 0 and ($o2 = $stack->last()) and in_array($o2, $ops) and ($ops_r[$op] ? $ops_p[$op] < $ops_p[$o2] : $ops_p[$op] <= $ops_p[$o2])) { + $output[] = $stack->pop(); // pop stuff off the stack into the output + } + // many thanks: http://en.wikipedia.org/wiki/Reverse_Polish_notation#The_algorithm_in_detail + $stack->push($op); // finally put OUR operator onto the stack + $index ++; + $expecting_op = false; + // =============== + } elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis? + while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last ( + if (is_null($o2)) + return $this->trigger(5, "unexpected ')'", ")"); + else + $output[] = $o2; + } + if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function? + $fnn = $matches[1]; // get the function name + $arg_count = $stack->pop(); // see how many arguments there were (cleverly stored on the stack, thank you) + $output[] = $stack->pop(); // pop the function and push onto the output + if (in_array($fnn, $this->fb)) { // check the argument count + if ($arg_count > 1) + return $this->trigger(6, "wrong number of arguments ($arg_count given, 1 expected)", array($arg_count,1)); + } elseif (array_key_exists($fnn, $this->f)) { + if ($arg_count != count($this->f[$fnn]['args'])) + return $this->trigger(6, "wrong number of arguments ($arg_count given, " . count($this->f[$fnn]['args']) . " expected)", array($arg_count,count($this->f[$fnn]['args']))); + } else { // did we somehow push a non-function on the stack? this should never happen + return $this->trigger(7, "internal error"); + } + } + $index ++; + // =============== + } elseif ($op == ',' and $expecting_op) { // did we just finish a function argument? + while (($o2 = $stack->pop()) != '(') { + if (is_null($o2)) + return $this->trigger(5, "unexpected ','", ","); // oops, never had a ( + else + $output[] = $o2; // pop the argument expression stuff and push onto the output + } + // make sure there was a function + if (! preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) + return $this->trigger(5, "unexpected ','", ","); + $stack->push($stack->pop() + 1); // increment the argument count + $stack->push('('); // put the ( back on, we'll need to pop back to it again + $index ++; + $expecting_op = false; + // =============== + } elseif ($op == '(' and ! $expecting_op) { + $stack->push('('); // that was easy + $index ++; + $allow_neg = true; + // =============== + } elseif ($ex and ! $expecting_op) { // do we now have a function/variable/number? + $expecting_op = true; + $val = $match[1]; + if (preg_match("/^([a-z]\w*)\($/", $val, $matches)) { // may be func, or variable w/ implicit multiplication against parentheses... + if (in_array($matches[1], $this->fb) or array_key_exists($matches[1], $this->f)) { // it's a func + $stack->push($val); + $stack->push(1); + $stack->push('('); + $expecting_op = false; + } else { // it's a var w/ implicit multiplication + $val = $matches[1]; + $output[] = $val; + } + } else { // it's a plain old var or num + $output[] = $val; + } + $index += strlen($val); + // =============== + } elseif ($op == ')') { // miscellaneous error checking + return $this->trigger(5, "unexpected ')'", ")"); + } elseif (in_array($op, $ops) and ! $expecting_op) { + return $this->trigger(8, "unexpected operator '$op'", $op); + } else { // I don't even want to know what you did to get here + return $this->trigger(9, "an unexpected error occured"); + } + if ($index == strlen($expr)) { + if (in_array($op, $ops)) { // did we end with an operator? bad. + return $this->trigger(10, "operator '$op' lacks operand", $op); + } else { + break; + } + } + while (substr($expr, $index, 1) == ' ') { // step the index past whitespace (pretty much turns whitespace + $index ++; // into implicit multiplication if no operator is there) + } + } + while (! is_null($op = $stack->pop())) { // pop everything off the stack and push onto output + if ($op == '(') + return $this->trigger(11, "expecting ')'", ")"); // if there are (s on the stack, ()s were unbalanced + $output[] = $op; + } + return $output; + } + + /** + * evaluate postfix notation + * + * @param string $tokens Expression + * @param array $vars Array + * @return string Output + */ + private function pfx($tokens, $vars = array()) + { + if ($tokens == false) + return false; + + $stack = new EvalMathStack(); + + foreach ($tokens as $token) { // nice and easy + // if the token is a binary operator, pop two values off the stack, do the operation, and push the result back on + $matches = array(); + if (in_array($token, array('+','-','*','/','^'))) { + if (is_null($op2 = $stack->pop())) + return $this->trigger(12, "internal error"); + if (is_null($op1 = $stack->pop())) + return $this->trigger(13, "internal error"); + switch ($token) { + case '+': + $stack->push($op1 + $op2); + break; + case '-': + $stack->push($op1 - $op2); + break; + case '*': + $stack->push($op1 * $op2); + break; + case '/': + if ($op2 == 0) + return $this->trigger(14, "division by zero"); + $stack->push($op1 / $op2); + break; + case '^': + $stack->push(pow($op1, $op2)); + break; + } + // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on + } elseif ($token == "_") { + $stack->push(- 1 * $stack->pop()); + // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on + } elseif (preg_match("/^([a-z]\w*)\($/", $token, $matches)) { // it's a function! + $fnn = $matches[1]; + if (in_array($fnn, $this->fb)) { // built-in function: + if (is_null($op1 = $stack->pop())) + return $this->trigger(15, "internal error"); + $fnn = preg_replace("/^arc/", "a", $fnn); // for the 'arc' trig synonyms + if ($fnn == 'ln') + $fnn = 'log'; + eval('$stack->push(' . $fnn . '($op1));'); // perfectly safe eval() + } elseif (array_key_exists($fnn, $this->f)) { // user function + // get args + $args = array(); + for ($i = count($this->f[$fnn]['args']) - 1; $i >= 0; $i --) { + if (is_null($args[$this->f[$fnn]['args'][$i]] = $stack->pop())) + return $this->trigger(16, "internal error"); + } + $stack->push($this->pfx($this->f[$fnn]['func'], $args)); // yay... recursion!!!! + } + // if the token is a number or variable, push it on the stack + } else { + if (is_numeric($token)) { + $stack->push($token); + } elseif (array_key_exists($token, $this->v)) { + $stack->push($this->v[$token]); + } elseif (array_key_exists($token, $vars)) { + $stack->push($vars[$token]); + } else { + return $this->trigger(17, "undefined variable '$token'", $token); + } + } + } + // when we're out of tokens, the stack should have a single element, the final result + if ($stack->count != 1) + return $this->trigger(18, "internal error"); + return $stack->pop(); + } + + /** + * trigger an error, but nicely, if need be + * + * @param string $code Code + * @param string $msg Msg + * @param string|null $info String + * @return boolean False + */ + public function trigger($code, $msg, $info = null) + { + $this->last_error = $msg; + $this->last_error_code = array($code,$info); + if (! $this->suppress_errors) + trigger_error($msg, E_USER_WARNING); + return false; + } +} + +/** + * Class for internal use + */ +class EvalMathStack +{ + + public $stack = array(); + + public $count = 0; + + /** + * push + * + * @param string $val Val + * @return void + */ + public function push($val) + { + $this->stack[$this->count] = $val; + $this->count ++; + } + + /** + * pop + * + * @return mixed Stack + */ + public function pop() + { + if ($this->count > 0) { + $this->count --; + return $this->stack[$this->count]; + } + return null; + } + + /** + * last + * + * @param int $n N + * @return mixed Stack + */ + public function last($n = 1) + { + if (isset($this->stack[$this->count - $n])) { + return $this->stack[$this->count - $n]; + } + return; + } +} diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 5d5540d77b8..94504686718 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -225,9 +225,10 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK */ - public function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) + public function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { if (empty($attrname)) return -1; if (empty($label)) return -1; @@ -245,7 +246,7 @@ class ExtraFields if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate') { // Add declaration of field into table - $result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable); + $result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled, $totalizable, $printable); $err2 = $this->errno; if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) { @@ -374,9 +375,11 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is a measure. Must show a total on lists + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK + * @throws Exception */ - private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) + private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { // phpcs:enable global $conf, $user; @@ -390,6 +393,7 @@ class ExtraFields if (empty($required)) $required = 0; if (empty($unique)) $unique = 0; if (empty($alwayseditable)) $alwayseditable = 0; + if (empty($totalizable)) $totalizable = 0; if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname) && !is_numeric($attrname)) { @@ -421,6 +425,7 @@ class ExtraFields $sql .= " perms,"; $sql .= " langs,"; $sql .= " list,"; + $sql .= " printable,"; $sql .= " fielddefault,"; $sql .= " fieldcomputed,"; $sql .= " fk_user_author,"; @@ -444,6 +449,7 @@ class ExtraFields $sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").","; $sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").","; $sql .= " '".$this->db->escape($list)."',"; + $sql .= " '".$this->db->escape($printable)."',"; $sql .= " ".($default ? "'".$this->db->escape($default)."'" : "null").","; $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; $sql .= " ".(is_object($user) ? $user->id : 0).","; @@ -451,7 +457,7 @@ class ExtraFields $sql .= "'".$this->db->idate(dol_now())."',"; $sql .= " ".($enabled ? "'".$this->db->escape($enabled)."'" : "1").","; $sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null").","; - $sql .= " ".($totalizable ? '1' : '0'); + $sql .= " ".($totalizable ? 'TRUE' : 'FALSE'); $sql .= ')'; dol_syslog(get_class($this)."::create_label", LOG_DEBUG); @@ -590,9 +596,11 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF * @return int >0 if OK, <=0 if KO + * @throws Exception */ - public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) + public function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { if ($elementtype == 'thirdparty') $elementtype = 'societe'; if ($elementtype == 'contact') $elementtype = 'socpeople'; @@ -642,7 +650,7 @@ class ExtraFields { if ($label) { - $result = $this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable); + $result = $this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable, $printable); } if ($result > 0) { @@ -700,13 +708,15 @@ class ExtraFields * @param string $langfile Language file * @param string $enabled Condition to have the field enabled or not * @param int $totalizable Is extrafield totalizable on list + * @param int $printable Is extrafield displayed on PDF * @return int <=0 if KO, >0 if OK + * @throws Exception */ - private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0) + private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0, $printable = 0) { // phpcs:enable global $conf, $user; - dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable); + dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable.", ".$printable); // Clean parameters if ($elementtype == 'thirdparty') $elementtype = 'societe'; @@ -771,6 +781,7 @@ class ExtraFields $sql .= " alwayseditable,"; $sql .= " param,"; $sql .= " list,"; + $sql .= " printable,"; $sql .= " totalizable,"; $sql .= " fielddefault,"; $sql .= " fieldcomputed,"; @@ -794,7 +805,8 @@ class ExtraFields $sql .= " '".$this->db->escape($alwayseditable)."',"; $sql .= " '".$this->db->escape($params)."',"; $sql .= " '".$this->db->escape($list)."', "; - $sql .= " ".$totalizable.","; + $sql .= " '".$this->db->escape($printable)."', "; + $sql .= " ".($totalizable ? 'TRUE' : 'FALSE').","; $sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").","; $sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").","; $sql .= " ".$user->id.","; @@ -871,7 +883,7 @@ class ExtraFields }*/ // We should not have several time this request. If we have, there is some optimization to do by calling a simple $extrafields->fetch_optionals() in top of code and not into subcode - $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,printable,totalizable,fielddefault,fieldcomputed,entity,enabled,help"; $sql .= " FROM ".MAIN_DB_PREFIX."extrafields"; //$sql.= " WHERE entity IN (0,".$conf->entity.")"; // Filter is done later if ($elementtype) $sql .= " WHERE elementtype = '".$elementtype."'"; // Filed with object->table_element @@ -933,7 +945,8 @@ class ExtraFields $this->attributes[$tab->elementtype]['perms'][$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms); $this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs; $this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list; - $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = $tab->totalizable; + $this->attributes[$tab->elementtype]['printable'][$tab->name] = $tab->printable; + $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = ($tab->totalizable ? 1 : 0); $this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity; $this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled; $this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help; @@ -1931,6 +1944,10 @@ class ExtraFields { $align = "right"; } + elseif ($type == 'price') + { + $align="right"; + } elseif ($type == 'double') { $align = "right"; diff --git a/htdocs/core/class/fiscalyear.class.php b/htdocs/core/class/fiscalyear.class.php index 0eed1a56580..10015e3c363 100644 --- a/htdocs/core/class/fiscalyear.class.php +++ b/htdocs/core/class/fiscalyear.class.php @@ -1,5 +1,7 @@ +/* Copyright (C) 2014-2020 Alexandre Spangaro + * Copyright (C) 2020 OScss-Shop + * * * 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 @@ -381,13 +383,19 @@ class Fiscalyear extends CommonObject * @param int $dateend Date end to scan * @return string Number of entries */ - public function getAccountancyEntriesByFiscalYear($datestart, $dateend) + public function getAccountancyEntriesByFiscalYear($datestart = '', $dateend = '') { global $conf; + if(empty($datestart) ) + $datestart = $this->date_start; + if(empty($dateend) ) + $dateend = $this->date_end; + $sql = "SELECT count(DISTINCT piece_num) as nb"; - $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping "; - $sql.= " WHERE doc_date >= '".$datestart."' and doc_date <= '".$dateend."'"; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping"; + $sql.= " WHERE entity IN (".getEntity('bookkeeping', 0).")"; + $sql.= " AND doc_date >= '".$this->db->idate($datestart)."' and doc_date <= '".$this->db->idate($dateend)."'"; $resql=$this->db->query($sql); if ($resql) @@ -407,13 +415,19 @@ class Fiscalyear extends CommonObject * @param int $dateend Date end to scan * @return string Number of movements */ - public function getAccountancyMovementsByFiscalYear($datestart, $dateend) + public function getAccountancyMovementsByFiscalYear($datestart = '', $dateend = '') { global $conf; + if(empty($datestart) ) + $datestart = $this->date_start; + if(empty($dateend) ) + $dateend = $this->date_end; + $sql = "SELECT count(rowid) as nb"; $sql.= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping "; - $sql.= " WHERE doc_date >= '".$datestart."' AND doc_date <= '".$dateend."'"; + $sql.= " WHERE entity IN (".getEntity('bookkeeping', 0).")"; + $sql.= " AND doc_date >= '".$this->db->idate($datestart)."' and doc_date <= '".$this->db->idate($dateend)."'"; $resql=$this->db->query($sql); if ($resql) diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php index 39493825377..437ac507462 100644 --- a/htdocs/core/class/hookmanager.class.php +++ b/htdocs/core/class/hookmanager.class.php @@ -177,6 +177,7 @@ class HookManager 'getFormatedCustomerRef', 'getFormatedSupplierRef', 'getIdProfUrl', + 'getInputIdProf', 'moveUploadedFile', 'moreHtmlStatus', 'pdf_build_address', diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index a74872d4a98..2c22e83f786 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -202,7 +202,7 @@ class Form $ret .= ''; if (empty($notabletag)) $ret .= ''; if (empty($notabletag)) $ret .= ''; $arraypriceupdaters = $price_updaters->listUpdaters(); - if (! empty($arraypriceupdaters)) + if (!empty($arraypriceupdaters)) { foreach ($arraypriceupdaters as $i=>$entry) { $code = ""; @@ -308,19 +308,19 @@ if ($action == 'create_updater' || $action == 'edit_updater') { print ''; //Description print ''; print ''; - print ''; + print ''; print ''; //Type print ''; print ''; print ''; //Interval print ''; print ''; - print ''; + print ''; print ''; print '
    '; - if (preg_match('/^(string|email)/', $typeofdata)) + if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) { $tmp = explode(':', $typeofdata); $ret .= ''; @@ -276,6 +276,7 @@ class Form if (preg_match('/^(email)/', $typeofdata)) $ret .= dol_print_email($value, 0, 0, 0, 0, 1); elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : ''); elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) $ret .= dol_htmlentitiesbr($value); + elseif (preg_match('/^safehtmlstring/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value); elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= dol_print_date($value, 'day'); elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= dol_print_date($value, 'dayhour'); elseif (preg_match('/^select;/', $typeofdata)) @@ -298,9 +299,13 @@ class Form $firstline = preg_replace('/[\n\r].*/', '', $firstline); $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : ''); } - $ret .= $tmpcontent; + // We dont use dol_escape_htmltag to get the html formating active, but this need we must also + // clean data from some dangerous html + $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent)); + } + else { + $ret .= dol_escape_htmltag($value); } - else $ret .= dol_escape_htmltag($value); if ($formatfunc && method_exists($object, $formatfunc)) { @@ -461,8 +466,6 @@ class Form */ public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0) { - global $conf; - if ($incbefore) $text = $incbefore.$text; if (!$htmltext) return $text; @@ -470,9 +473,7 @@ class Form if ($notabs == 2) $tag = 'div'; if ($notabs == 3) $tag = 'span'; // Sanitize tooltip - //$htmltext=str_replace("\\","\\\\",$htmltext); - $htmltext = str_replace("\r", "", $htmltext); - $htmltext = str_replace("\n", "", $htmltext); + $htmltext = str_replace(array("\r", "\n"), '', $htmltext); $extrastyle = ''; if ($direction < 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-left: 3px !important;'; } @@ -484,7 +485,7 @@ class Form if ($tooltiptrigger == '') { - $htmltext = str_replace('"', """, $htmltext); + $htmltext = str_replace('"', '"', $htmltext); } else { @@ -1617,7 +1618,7 @@ class Form public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false) { // phpcs:enable - global $conf, $user, $langs; + global $conf, $user, $langs, $hookmanager; // If no preselected user defined, we take current user if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected = $user->id; @@ -1678,6 +1679,10 @@ class Form if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql .= " AND u.statut <> 0"; if (!empty($morefilter)) $sql .= " ".$morefilter; + //Add hook to filter on user (for exemple on usergroup define in custom modules) + $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action); + if (!empty($reshook)) $sql .= $hookmanager->resPrint; + if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname { $sql .= " ORDER BY u.firstname ASC"; @@ -2109,7 +2114,7 @@ class Form } } - $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; + $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression"; if (count($warehouseStatusArray)) { $selectFieldsGrouped = ", sum(".$db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock @@ -2400,9 +2405,10 @@ class Form * @param string $selected Preselected value * @param int $hidepriceinlabel Hide price in label * @param string $filterkey Filter key to highlight + * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on. * @return void */ - protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '') + protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0) { global $langs, $conf, $user, $db; @@ -2431,6 +2437,7 @@ class Form $outlabel = $objp->label; $outdesc = $objp->description; $outbarcode = $objp->barcode; + $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid; $outtype = $objp->fk_product_type; $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : ''; @@ -2478,7 +2485,7 @@ class Form $opt .= ($objp->rowid == $selected) ? ' selected' : ''; if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) { - $opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"'; + $opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqup="'.$objp->price_by_qty_unitprice.'" data-pbqbase="'.$objp->price_by_qty_price_base_type.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"'; } if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { @@ -2638,7 +2645,7 @@ class Form } $outval .= $langs->transnoentities("Stock").':'.$objp->stock; $outval .= ''; - if (!empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation + if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation { $langs->load("stocks"); @@ -2664,7 +2671,7 @@ class Form } $opt .= "\n"; - $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit); + $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'pbq'=>$outpbq); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -2736,13 +2743,15 @@ class Form $out = ''; $outarray = array(); + $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO); + $langs->load('stocks'); // Units if ($conf->global->PRODUCT_USE_UNITS) { $langs->load('other'); } - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,"; + $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type,"; $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,"; $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,"; $sql .= " pfp.supplier_reputation"; @@ -2750,7 +2759,7 @@ class Form if ($conf->global->PRODUCT_USE_UNITS) { $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units"; } - if (!empty($conf->barcode->enabled)) $sql .= " ,pfp.barcode"; + if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; if ($socid) $sql .= " AND pfp.fk_soc = ".$socid; @@ -2813,6 +2822,7 @@ class Form $outref = $objp->ref; $outval = ''; + $outbarcode = $objp->barcode; $outqty = 1; $outdiscount = 0; $outtype = $objp->fk_product_type; @@ -2863,12 +2873,22 @@ class Form if ($filterkey && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey).')/i', '$1', $label, 1); $optlabel = $objp->ref; - if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) + if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) { $optlabel .= ' ('.$objp->ref_fourn.')'; + } + if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) { + $optlabel .= ' ('.$outbarcode.')'; + } + $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle); $outvallabel = $objRef; - if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) + if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) { $outvallabel .= ' ('.$objRefFourn.')'; + } + if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) { + $outvallabel .= ' ('.$outbarcode.')'; + } + $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle); // Units $optlabel .= $outvalUnits; @@ -2891,7 +2911,7 @@ class Form $objp->fprice = $price_result; if ($objp->quantity >= 1) { - $objp->unitprice = $objp->fprice / $objp->quantity; + $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice } } } @@ -2930,12 +2950,6 @@ class Form $optlabel .= " - ".dol_trunc($objp->name, 8); $outvallabel .= " - ".dol_trunc($objp->name, 8); } - if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) - { - //$optlabel .= " - ".$objp->barcode; - $optlabel .= " - ".$objp->barcode; - $outvallabel .= " - ".$objp->barcode; - } if ($objp->supplier_reputation) { //TODO dictionary @@ -2964,7 +2978,7 @@ class Form if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt .= ' disabled'; if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) { - $opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"'; + $opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqup="'.$objp->unitprice.'" data-pbqpercent="'.$objp->remise_percent.'"'; } $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"'; $opt .= '>'; @@ -2979,7 +2993,7 @@ class Form // "key" value of json key array is used by jQuery automatically as selected value // "label" value of json key array is used by jQuery automatically as text for combo box $out .= $opt; - array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false))); + array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'up'=>$objp->unitprice, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false))); // Exemple of var_dump $outarray // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp" // ["label"]=>string(76) "ppp (fff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)" @@ -3023,7 +3037,7 @@ class Form $langs->load('stocks'); - $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,"; + $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,"; $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,"; $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name"; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; @@ -3498,6 +3512,7 @@ class Form // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Return list of payment methods + * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want. * * @param string $selected Id du mode de paiement pre-selectionne * @param string $htmlname Nom de la zone select @@ -3513,7 +3528,7 @@ class Form public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '') { // phpcs:enable - global $langs, $user; + global $langs, $user, $conf; dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG); @@ -3524,6 +3539,9 @@ class Form $this->load_cache_types_paiements(); + // Set default value if not already set by caller + if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID; + print ' jQuery(document).ready(function () { $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () { - console.log("A new field was added/removed") - $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\') + console.log("A new field was added/removed, we edit field input[name=formfilteraction]"); + + $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST + var title = $(this).val() + ","; if ($(this).is(\':checked\')) { $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val()); @@ -6691,8 +6712,10 @@ class Form $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') ) } // Now, we submit page - $(this).parents(\'form:first\').submit(); + //$(this).parents(\'form:first\').submit(); }); + + }); @@ -7058,7 +7081,6 @@ class Form jQuery(".linkto").click(function() { console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\')); jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle(); - jQuery(this).toggle(); }); }); @@ -7306,21 +7328,21 @@ class Form } elseif ($fieldref != 'none') { - $ret.=dol_htmlentities($object->$fieldref); + $ret .= dol_htmlentities($object->$fieldref); } if ($morehtmlref) { // don't add a additional space, when "$morehtmlref" starts with a HTML div tag - if(substr($morehtmlref, 0, 4) != 'trans("Filters"); $ret .= ''; //$ret .= ''; - $ret .= '
    '; - $ret .= ''; + $ret .= '
    '; + $texttoshow = '
    '.$langs->trans("Search").'
    '; + + $ret .= '
    '.$texttoshow.'
    '; $ret .= '
    '; - foreach($arrayofcriterias as $criterias) { - foreach($criterias as $criteriafamilykey => $criteriafamilyval) { + $ret .= ''; + // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields + foreach ($arrayofcriterias as $criterias) { + foreach ($criterias as $criteriafamilykey => $criteriafamilyval) { if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) continue; if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) continue; if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) { diff --git a/htdocs/core/class/html.formaccounting.class.php b/htdocs/core/class/html.formaccounting.class.php index 64e027db537..19fa3f6fb26 100644 --- a/htdocs/core/class/html.formaccounting.class.php +++ b/htdocs/core/class/html.formaccounting.class.php @@ -461,12 +461,12 @@ class FormAccounting extends Form $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping"; $sql .= " WHERE entity IN (".getEntity('accountancy').")"; $sql .= " ORDER BY date_format(doc_date, '%Y')"; - dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { $this->error = "Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR); + dol_syslog(__METHOD__.$this->error, LOG_ERR); return -1; } while ($obj = $this->db->fetch_object($resql)) { diff --git a/htdocs/core/class/html.formadmin.class.php b/htdocs/core/class/html.formadmin.class.php index 7012b813f7d..21c15b3b7c6 100644 --- a/htdocs/core/class/html.formadmin.class.php +++ b/htdocs/core/class/html.formadmin.class.php @@ -50,7 +50,7 @@ class FormAdmin * @param string $selected Language pre-selected * @param string $htmlname Name of HTML select * @param int $showauto Show 'auto' choice - * @param array $filter Array of keys to exclude in list + * @param array $filter Array of keys to exclude in list (opposite of $onlykeys) * @param string $showempty '1'=Add empty value or string to show * @param int $showwarning Show a warning if language is not complete * @param int $disabled Disable edit of select @@ -58,16 +58,18 @@ class FormAdmin * @param int $showcode 1=Add language code into label at begining, 2=Add language code into label at end * @param int $forcecombo Force to use combo box (so no ajax beautify effect) * @param int $multiselect Make the combo a multiselect + * @param array $onlykeys Show only the following keys (opposite of $filter) + * @param int $mainlangonly 1=Show only main languages ('fr_FR' no' fr_BE', 'es_ES' not 'es_MX', ...) * @return string Return HTML select string with list of languages */ - public function select_language($selected = '', $htmlname = 'lang_id', $showauto = 0, $filter = null, $showempty = '', $showwarning = 0, $disabled = 0, $morecss = '', $showcode = 0, $forcecombo = 0, $multiselect = 0) + public function select_language($selected = '', $htmlname = 'lang_id', $showauto = 0, $filter = null, $showempty = '', $showwarning = 0, $disabled = 0, $morecss = '', $showcode = 0, $forcecombo = 0, $multiselect = 0, $onlykeys = array(), $mainlangonly = 0) { // phpcs:enable global $conf, $langs; if (!empty($conf->global->MAIN_DEFAULT_LANGUAGE_FILTER)) $filter[$conf->global->MAIN_DEFAULT_LANGUAGE_FILTER] = 1; - $langs_available=$langs->get_available_languages(DOL_DOCUMENT_ROOT, 12); + $langs_available=$langs->get_available_languages(DOL_DOCUMENT_ROOT, 12, 0, $mainlangonly); $out=''; @@ -94,19 +96,28 @@ class FormAdmin { $valuetoshow=$value; if ($showcode == 1) $valuetoshow=$key.' - '.$value; - if ($showcode == 2) $valuetoshow=$value.' ('.$key.')'; + if ($showcode == 2) { + if ($mainlangonly) $valuetoshow=$value.' ('.preg_replace('/[_-].*$/', '', $key).')'; + else $valuetoshow=$value.' ('.$key.')'; + } - if ($filter && is_array($filter) && array_key_exists($key, $filter)) - { + $keytouse = $key; + if ($mainlangonly) $keytouse = preg_replace('/[_-].*$/', '', $key); + + if ($filter && is_array($filter) && array_key_exists($keytouse, $filter)) { continue; } - elseif ($selected == $key) + if ($onlykeys && is_array($onlykeys) && ! array_key_exists($keytouse, $onlykeys)) { + continue; + } + + if ($selected == $keytouse) { - $out.= ''; + $out.= ''; } else { - $out.= ''; + $out.= ''; } } $out.= ''; @@ -134,49 +145,49 @@ class FormAdmin public function select_menu($selected, $htmlname, $dirmenuarray, $moreattrib = '') { // phpcs:enable - global $langs,$conf; + global $langs, $conf; // Clean parameters // Check parameters - if (! is_array($dirmenuarray)) return -1; + if (!is_array($dirmenuarray)) return -1; - $menuarray=array(); + $menuarray = array(); foreach ($conf->file->dol_document_root as $dirroot) { - foreach($dirmenuarray as $dirtoscan) + foreach ($dirmenuarray as $dirtoscan) { - $dir=$dirroot.$dirtoscan; + $dir = $dirroot.$dirtoscan; //print $dir.'
    '; if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') { - if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files - if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files + if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - $filelib=preg_replace('/\.php$/i', '', $file); - $prefix=''; + $filelib = preg_replace('/\.php$/i', '', $file); + $prefix = ''; // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other - if (preg_match('/^eldy/i', $file)) $prefix='0'; - elseif (preg_match('/^smartphone/i', $file)) $prefix='2'; - else $prefix='3'; + if (preg_match('/^eldy/i', $file)) $prefix = '0'; + elseif (preg_match('/^smartphone/i', $file)) $prefix = '2'; + else $prefix = '3'; if ($file == $selected) { - $menuarray[$prefix.'_'.$file]=''; + $menuarray[$prefix.'_'.$file] = ''; } else { - $menuarray[$prefix.'_'.$file]=''; + $menuarray[$prefix.'_'.$file] = ''; } } } @@ -188,26 +199,26 @@ class FormAdmin ksort($menuarray); // Output combo list of menus - print ''; + $oldprefix = ''; foreach ($menuarray as $key => $val) { - $tab=explode('_', $key); - $newprefix=$tab[0]; - if ($newprefix=='1' && ($conf->global->MAIN_FEATURES_LEVEL < 1)) continue; - if ($newprefix=='2' && ($conf->global->MAIN_FEATURES_LEVEL < 2)) continue; + $tab = explode('_', $key); + $newprefix = $tab[0]; + if ($newprefix == '1' && ($conf->global->MAIN_FEATURES_LEVEL < 1)) continue; + if ($newprefix == '2' && ($conf->global->MAIN_FEATURES_LEVEL < 2)) continue; if ($newprefix != $oldprefix) // Add separators { // Affiche titre print ''; - $oldprefix=$newprefix; + $oldprefix = $newprefix; } - print $val."\n"; // Show menu entry + print $val."\n"; // Show menu entry } print ''; } @@ -224,37 +235,37 @@ class FormAdmin public function select_menu_families($selected, $htmlname, $dirmenuarray) { // phpcs:enable - global $langs,$conf; + global $langs, $conf; //$expdevmenu=array('smartphone_backoffice.php','smartphone_frontoffice.php'); // Menu to disable if $conf->global->MAIN_FEATURES_LEVEL is not set - $expdevmenu=array(); + $expdevmenu = array(); - $menuarray=array(); + $menuarray = array(); - foreach($dirmenuarray as $dirmenu) + foreach ($dirmenuarray as $dirmenu) { foreach ($conf->file->dol_document_root as $dirroot) { - $dir=$dirroot.$dirmenu; + $dir = $dirroot.$dirmenu; if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { - $filelib=preg_replace('/(_backoffice|_frontoffice)?\.php$/i', '', $file); + $filelib = preg_replace('/(_backoffice|_frontoffice)?\.php$/i', '', $file); if (preg_match('/^index/i', $filelib)) continue; if (preg_match('/^default/i', $filelib)) continue; if (preg_match('/^empty/i', $filelib)) continue; if (preg_match('/\.lib/i', $filelib)) continue; if (empty($conf->global->MAIN_FEATURES_LEVEL) && in_array($file, $expdevmenu)) continue; - $menuarray[$filelib]=1; + $menuarray[$filelib] = 1; } - $menuarray['all']=1; + $menuarray['all'] = 1; } closedir($handle); } @@ -266,11 +277,11 @@ class FormAdmin // Affichage liste deroulante des menus print ''; + $out .= ''; + $out .= ''; return $out; } diff --git a/htdocs/core/class/html.formcategory.class.php b/htdocs/core/class/html.formcategory.class.php new file mode 100644 index 00000000000..4dd8bed247b --- /dev/null +++ b/htdocs/core/class/html.formcategory.class.php @@ -0,0 +1,58 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/class/html.formcategory.class.php + * \ingroup core + * \brief File of class to build HTML component for category filtering + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; + +class FormCategory extends Form +{ + /** + * Return a HTML filter box for a list filter view + * + * @param string $type The categorie type (e.g Categorie::TYPE_WAREHOUSE) + * @param Array $preSelected A list with the elements that should pre-selected + * @return string A HTML filter box (Note: selected results can get with GETPOST("search_category_".$type."_list")) + */ + public function getFilterBox($type, $preSelected) + { + // phpcs:enable + global $langs; + + if (empty($preSelected) || !is_array($preSelected)) + { + $preSelected = array(); + } + + $htmlName = "search_category_".$type."_list"; + + $categoryArray = $this->select_all_categories($type, "", "", 64, 0, 1); + $categoryArray[-2] = "- ".$langs->trans('NotCategorized')." -"; + + $filter = ''; + $filter .= '
    '; + $filter .= $langs->trans('Categories').": "; + $filter .= Form::multiselectarray($htmlName, $categoryArray, $preSelected, 0, 0, "minwidth300"); + $filter .= "
    "; + + return $filter; + } +} diff --git a/htdocs/core/class/html.formcompany.class.php b/htdocs/core/class/html.formcompany.class.php index a08694560ec..d92de8f683b 100644 --- a/htdocs/core/class/html.formcompany.class.php +++ b/htdocs/core/class/html.formcompany.class.php @@ -249,8 +249,7 @@ class FormCompany extends Form } } - if ((!empty($selected) && $selected == $obj->rowid) - || (empty($selected) && !empty($conf->global->MAIN_FORCE_DEFAULT_STATE_ID) && $conf->global->MAIN_FORCE_DEFAULT_STATE_ID == $obj->rowid)) + if (!empty($selected) && $selected == $obj->rowid) { $out .= '
    '.$langs->trans("VariableToUpdate").''; $globals_list = array(); foreach ($price_globals->listGlobalVariables() as $entry) { - $globals_list[$entry->id]=$entry->code; + $globals_list[$entry->id] = $entry->code; } - print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable)?0:$price_updaters->fk_variable)); + print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable) ? 0 : $price_updaters->fk_variable)); print '
    '.$langs->trans("Description").'
    '.$langs->trans("Type").''; - $type = empty($price_updaters->type)?0:$price_updaters->type; + $type = empty($price_updaters->type) ? 0 : $price_updaters->type; $type_list = array(); foreach ($price_updaters->types as $val) { $type_list[$val] = $langs->trans("GlobalVariableUpdaterType".$val); @@ -342,14 +342,14 @@ if ($action == 'create_updater' || $action == 'edit_updater') { $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'
    '.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).''; print '
    '.$form->textwithpicto($langs->trans("Parameters"), $help, 1).''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('parameters', empty($price_updaters->parameters)?'':$price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); + $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); $doleditor->Create(); print '
    '.$langs->trans("UpdateInterval").'
    '; diff --git a/htdocs/product/admin/product.php b/htdocs/product/admin/product.php index 3df07bf36c3..f3ef5441144 100644 --- a/htdocs/product/admin/product.php +++ b/htdocs/product/admin/product.php @@ -37,31 +37,31 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formbarcode.class.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","products")); +$langs->loadLangs(array("admin", "products")); // Security check -if (! $user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) +if (!$user->admin || (empty($conf->product->enabled) && empty($conf->service->enabled))) accessforbidden(); $action = GETPOST('action', 'alpha'); $value = GETPOST('value', 'alpha'); $label = GETPOST('label', 'alpha'); $scandir = GETPOST('scan_dir', 'alpha'); -$type='product'; +$type = 'product'; // Pricing Rules -$select_pricing_rules=array( - 'PRODUCT_PRICE_UNIQ'=>$langs->trans('PriceCatalogue'), // Unique price - 'PRODUIT_MULTIPRICES'=>$langs->trans('MultiPricesAbility'), // Several prices according to a customer level - 'PRODUIT_CUSTOMER_PRICES'=>$langs->trans('PriceByCustomer'), // Different price for each customer +$select_pricing_rules = array( + 'PRODUCT_PRICE_UNIQ'=>$langs->trans('PriceCatalogue'), // Unique price + 'PRODUIT_MULTIPRICES'=>$langs->trans('MultiPricesAbility'), // Several prices according to a customer level + 'PRODUIT_CUSTOMER_PRICES'=>$langs->trans('PriceByCustomer'), // Different price for each customer ); -$keyforparam='PRODUIT_CUSTOMER_PRICES_BY_QTY'; -if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || ! empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice -$keyforparam='PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; -if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || ! empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility') . '+' . $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; +$keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; +if ($conf->global->MAIN_FEATURES_LEVEL >= 1 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY'] = $langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // TODO If this is enabled, price must be hidden when price by qty is enabled, also price for quantity must be used when adding product into order/propal/invoice +$keyforparam = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; +if ($conf->global->MAIN_FEATURES_LEVEL >= 2 || !empty($conf->global->$keyforparam)) $select_pricing_rules['PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'] = $langs->trans('MultiPricesAbility').'+'.$langs->trans('PriceByQuantity').' ('.$langs->trans("VersionExperimental").')'; // Clean param -if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) { +if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_MULTIPRICES_LIMIT)) { dolibarr_set_const($db, 'PRODUIT_MULTIPRICES_LIMIT', 5, 'chaine', 0, '', $conf->entity); } @@ -72,7 +72,7 @@ $error = 0; * Actions */ -$nomessageinsetmoduleoptions=1; +$nomessageinsetmoduleoptions = 1; include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php'; if ($action == 'setcodeproduct') @@ -91,12 +91,12 @@ if ($action == 'setcodeproduct') if ($action == 'other' && GETPOST('value_PRODUIT_LIMIT_SIZE') >= 0) { $res = dolibarr_set_const($db, "PRODUIT_LIMIT_SIZE", GETPOST('value_PRODUIT_LIMIT_SIZE'), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; } if ($action == 'other' && GETPOST('value_PRODUIT_MULTIPRICES_LIMIT') > 0) { $res = dolibarr_set_const($db, "PRODUIT_MULTIPRICES_LIMIT", GETPOST('value_PRODUIT_MULTIPRICES_LIMIT'), 'chaine', 0, '', $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; } if ($action == 'other') { @@ -114,8 +114,8 @@ if ($action == 'other') } else { - $multirule=explode('&', $princingrules); - foreach($multirule as $rulesselected) + $multirule = explode('&', $princingrules); + foreach ($multirule as $rulesselected) { $res = dolibarr_set_const($db, $rulesselected, 1, 'chaine', 0, '', $conf->entity); } @@ -123,7 +123,7 @@ if ($action == 'other') } else // We clear this mode { - if (strpos($rule, '&')===false) { + if (strpos($rule, '&') === false) { $res = dolibarr_set_const($db, $rule, 0, 'chaine', 0, '', $conf->entity); } } @@ -156,24 +156,36 @@ if ($action == 'other') $resql_new = $db->query($sql_new); } } + + $value = GETPOST('activate_useProdSupplierPackaging', 'alpha'); + $res = dolibarr_set_const($db, "PRODUCT_USE_SUPPLIER_PACKAGING", $value, 'chaine', 0, '', $conf->entity); + if ($value) { + $sql_test = "SELECT count(packaging) as cpt FROM ".MAIN_DB_PREFIX."product_fournisseur_price WHERE 1"; + $resql = $db->query($sql_test); + if (!$resql && $db->lasterrno == 'DB_ERROR_NOSUCHFIELD') // if the field does not exist, we create it + { + $sql_new = "ALTER TABLE ".MAIN_DB_PREFIX."product_fournisseur_price ADD COLUMN packaging double(24,8) DEFAULT 1"; + $resql_new = $db->query($sql_new); + } + } } if ($action == 'specimen') // For products { - $modele= GETPOST('module', 'alpha'); + $modele = GETPOST('module', 'alpha'); $product = new Product($db); $product->initAsSpecimen(); // Search template files - $file=''; $classname=''; $filefound=0; - $dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach($dirmodels as $reldir) + $file = ''; $classname = ''; $filefound = 0; + $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) { - $file=dol_buildpath($reldir."core/modules/product/doc/pdf_".$modele.".modules.php", 0); + $file = dol_buildpath($reldir."core/modules/product/doc/pdf_".$modele.".modules.php", 0); if (file_exists($file)) { - $filefound=1; + $filefound = 1; $classname = "pdf_".$modele; break; } @@ -243,7 +255,7 @@ if ($action == 'set') $value = GETPOST('value'); if (GETPOST('value', 'alpha')) $res = dolibarr_set_const($db, $const, $value, 'chaine', 0, '', $conf->entity); else $res = dolibarr_del_const($db, $const, $conf->entity); - if (! $res > 0) $error++; + if (!$res > 0) $error++; } //if ($action == 'other') @@ -255,7 +267,7 @@ if ($action == 'set') if ($action) { - if (! $error) + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } @@ -269,7 +281,7 @@ if ($action) * View */ -$formbarcode=new FormBarCode($db); +$formbarcode = new FormBarCode($db); $title = $langs->trans('ProductServiceSetup'); $tab = $langs->trans("ProductsAndServices"); @@ -286,17 +298,17 @@ elseif (empty($conf->service->enabled)) llxHeader('', $title); -$linkback=''.$langs->trans("BackToModuleList").''; +$linkback = ''.$langs->trans("BackToModuleList").''; print load_fiche_titre($title, $linkback, 'title_setup'); $head = product_admin_prepare_head(); dol_fiche_head($head, 'general', $tab, -1, 'product'); -$form=new Form($db); +$form = new Form($db); // Module to manage product / services code -$dirproduct=array('/core/modules/product/'); -$dirmodels=array_merge(array('/'), (array) $conf->modules_parts['models']); +$dirproduct = array('/core/modules/product/'); +$dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); print load_fiche_titre($langs->trans("ProductCodeChecker"), '', ''); @@ -318,16 +330,16 @@ foreach ($dirproduct as $dirroot) if (is_resource($handle)) { // Loop on each module find in opened directory - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (substr($file, 0, 16) == 'mod_codeproduct_' && substr($file, -3) == 'php') { - $file = substr($file, 0, dol_strlen($file)-4); + $file = substr($file, 0, dol_strlen($file) - 4); try { dol_include_once($dirroot.$file.'.php'); } - catch(Exception $e) + catch (Exception $e) { dol_syslog($e->getMessage(), LOG_ERR); } @@ -335,7 +347,7 @@ foreach ($dirproduct as $dirroot) $modCodeProduct = new $file; // Show modules according to features level - if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; + if ($modCodeProduct->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) continue; if ($modCodeProduct->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) continue; $var = !$var; @@ -344,7 +356,7 @@ foreach ($dirproduct as $dirroot) print ''.$modCodeProduct->info($langs).''."\n"; print ''.$modCodeProduct->getExample($langs).''."\n"; - if (! empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) + if (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) && $conf->global->PRODUCT_CODEPRODUCT_ADDON == $file) { print ''."\n"; print img_picto($langs->trans("Activated"), 'switch_on'); @@ -353,16 +365,16 @@ foreach ($dirproduct as $dirroot) else { $disabled = false; - if (! empty($conf->multicompany->enabled) && (is_object($mc) && ! empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true); + if (!empty($conf->multicompany->enabled) && (is_object($mc) && !empty($mc->sharings['referent']) && $mc->sharings['referent'] == $conf->entity) ? false : true); print ''; - if (! $disabled) print ''; + if (!$disabled) print ''; print img_picto($langs->trans("Disabled"), 'switch_off'); - if (! $disabled) print ''; + if (!$disabled) print ''; print ''; } print ''; - $s=$modCodeProduct->getToolTip($langs, null, -1); + $s = $modCodeProduct->getToolTip($langs, null, -1); print $form->textwithpicto('', $s, 1); print ''; @@ -377,14 +389,14 @@ print ''; // Module to build doc $def = array(); $sql = "SELECT nom"; -$sql.= " FROM ".MAIN_DB_PREFIX."document_model"; -$sql.= " WHERE type = '".$type."'"; -$sql.= " AND entity = ".$conf->entity; -$resql=$db->query($sql); +$sql .= " FROM ".MAIN_DB_PREFIX."document_model"; +$sql .= " WHERE type = '".$type."'"; +$sql .= " AND entity = ".$conf->entity; +$resql = $db->query($sql); if ($resql) { $i = 0; - $num_rows=$db->num_rows($resql); + $num_rows = $db->num_rows($resql); while ($i < $num_rows) { $array = $db->fetch_array($resql); @@ -415,41 +427,41 @@ clearstatcache(); foreach ($dirmodels as $reldir) { - foreach (array('','/doc') as $valdir) + foreach (array('', '/doc') as $valdir) { $dir = dol_buildpath($reldir."core/modules/product".$valdir); if (is_dir($dir)) { - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { - $filelist[]=$file; + $filelist[] = $file; } closedir($handle); arsort($filelist); - foreach($filelist as $file) + foreach ($filelist as $file) { if (preg_match('/\.modules\.php$/i', $file) && preg_match('/^(pdf_|doc_)/', $file)) { if (file_exists($dir.'/'.$file)) { - $name = substr($file, 4, dol_strlen($file) -16); - $classname = substr($file, 0, dol_strlen($file) -12); + $name = substr($file, 4, dol_strlen($file) - 16); + $classname = substr($file, 0, dol_strlen($file) - 12); require_once $dir.'/'.$file; $module = new $classname($db); - $modulequalified=1; - if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified=0; - if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified=0; + $modulequalified = 1; + if ($module->version == 'development' && $conf->global->MAIN_FEATURES_LEVEL < 2) $modulequalified = 0; + if ($module->version == 'experimental' && $conf->global->MAIN_FEATURES_LEVEL < 1) $modulequalified = 0; if ($modulequalified) { print ''; - print (empty($module->name)?$name:$module->name); + print (empty($module->name) ? $name : $module->name); print "\n"; if (method_exists($module, 'info')) print $module->info($langs); else print $module->description; @@ -484,15 +496,15 @@ foreach ($dirmodels as $reldir) print ''; // Info - $htmltooltip = ''.$langs->trans("Name").': '.$module->name; - $htmltooltip.='
    '.$langs->trans("Type").': '.($module->type?$module->type:$langs->trans("Unknown")); + $htmltooltip = ''.$langs->trans("Name").': '.$module->name; + $htmltooltip .= '
    '.$langs->trans("Type").': '.($module->type ? $module->type : $langs->trans("Unknown")); if ($module->type == 'pdf') { - $htmltooltip.='
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; + $htmltooltip .= '
    '.$langs->trans("Width").'/'.$langs->trans("Height").': '.$module->page_largeur.'/'.$module->page_hauteur; } - $htmltooltip.='

    '.$langs->trans("FeaturesSupported").':'; - $htmltooltip.='
    '.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); - $htmltooltip.='
    '.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); + $htmltooltip .= '

    '.$langs->trans("FeaturesSupported").':'; + $htmltooltip .= '
    '.$langs->trans("Logo").': '.yn($module->option_logo, 1, 1); + $htmltooltip .= '
    '.$langs->trans("MultiLanguage").': '.yn($module->option_multilang, 1, 1); print ''; @@ -549,10 +561,10 @@ print ' '."\n"; */ $rowspan = 4; -if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $rowspan++; +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $rowspan++; if (empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) $rowspan++; -if (! empty($conf->global->MAIN_MULTILANGS)) $rowspan++; -if (! empty($conf->fournisseur->enabled)) $rowspan++; +if (!empty($conf->global->MAIN_MULTILANGS)) $rowspan++; +if (!empty($conf->fournisseur->enabled)) $rowspan++; print ''; @@ -566,10 +578,10 @@ else } print ''; $current_rule = 'PRODUCT_PRICE_UNIQ'; -if (!empty($conf->global->PRODUIT_MULTIPRICES)) $current_rule='PRODUIT_MULTIPRICES'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) $current_rule='PRODUIT_CUSTOMER_PRICES_BY_QTY'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $current_rule='PRODUIT_CUSTOMER_PRICES'; -if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $current_rule='PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; +if (!empty($conf->global->PRODUIT_MULTIPRICES)) $current_rule = 'PRODUIT_MULTIPRICES'; +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY'; +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES'; +if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $current_rule = 'PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'; print $form->selectarray("princingrule", $select_pricing_rules, $current_rule); print ''; print ''; @@ -578,7 +590,7 @@ print ''; // multiprix nombre de prix a proposer -if (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) +if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { print ''; print ''.$langs->trans("MultiPricesNumPrices").''; @@ -608,7 +620,7 @@ if (empty($conf->use_javascript_ajax)) else { print ''; - $arrval=array( + $arrval = array( '0'=>$langs->trans("No"), '1'=>$langs->trans("Yes").' ('.$langs->trans("NumberOfKeyToSearch", 1).')', '2'=>$langs->trans("Yes").' ('.$langs->trans("NumberOfKeyToSearch", 2).')', @@ -658,31 +670,38 @@ print ''; */ // View product description in thirdparty language -if (! empty($conf->global->MAIN_MULTILANGS)) +if (!empty($conf->global->MAIN_MULTILANGS)) { print ''; print ''.$langs->trans("ViewProductDescInThirdpartyLanguageAbility").''; print ''; - print $form->selectyesno("activate_viewProdTextsInThirdpartyLanguage", (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)?$conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE:0), 1); + print $form->selectyesno("activate_viewProdTextsInThirdpartyLanguage", (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) ? $conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE : 0), 1); print ''; print ''; } -if (! empty($conf->fournisseur->enabled)) +if (!empty($conf->fournisseur->enabled)) { print ''; print ''.$langs->trans("UseProductFournDesc").''; print ''; - print $form->selectyesno("activate_useProdFournDesc", (! empty($conf->global->PRODUIT_FOURN_TEXTS)?$conf->global->PRODUIT_FOURN_TEXTS:0), 1); + print $form->selectyesno("activate_useProdFournDesc", (!empty($conf->global->PRODUIT_FOURN_TEXTS) ? $conf->global->PRODUIT_FOURN_TEXTS : 0), 1); print ''; print ''; + + print ''; + print ''.$langs->trans("UseProductSupplierPackaging").''; + print ''; + print $form->selectyesno("activate_useProdSupplierPackaging", (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING) ? $conf->global->PRODUCT_USE_SUPPLIER_PACKAGING : 0), 1); + print ''; + print ''; } -if (! empty($conf->global->PRODUCT_CANVAS_ABILITY)) +if (!empty($conf->global->PRODUCT_CANVAS_ABILITY)) { // Add canvas feature - $dir = DOL_DOCUMENT_ROOT . "/product/canvas/"; + $dir = DOL_DOCUMENT_ROOT."/product/canvas/"; print ''; print ''.$langs->trans("ProductSpecial").''."\n"; @@ -691,12 +710,12 @@ if (! empty($conf->global->PRODUCT_CANVAS_ABILITY)) if (is_dir($dir)) { - require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php'; + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - $handle=opendir($dir); + $handle = opendir($dir); if (is_resource($handle)) { - while (($file = readdir($handle))!==false) + while (($file = readdir($handle)) !== false) { if (file_exists($dir.$file.'/product.'.$file.'.class.php')) { diff --git a/htdocs/product/agenda.php b/htdocs/product/agenda.php index 33eec8c5375..6cb3430f105 100644 --- a/htdocs/product/agenda.php +++ b/htdocs/product/agenda.php @@ -56,7 +56,7 @@ $result=restrictedArea($user, 'produit|service', $id, 'product&product'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 08ee8624d30..d9e0295c7a2 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -8,7 +8,7 @@ * Copyright (C) 2010-2015 Juanjo Menent * Copyright (C) 2013-2016 Marcos García * Copyright (C) 2012-2013 Cédric Salvador - * Copyright (C) 2011-2017 Alexandre Spangaro + * Copyright (C) 2011-2020 Alexandre Spangaro * Copyright (C) 2014 Cédric Gross * Copyright (C) 2014-2015 Ferran Marcet * Copyright (C) 2015 Jean-François Ferry @@ -17,7 +17,7 @@ * Copyright (C) 2016 Meziane Sof * Copyright (C) 2017 Josep Lluís Amador * Copyright (C) 2019 Frédéric France - * Copyright (C) 2019 Thibault FOUCART + * Copyright (C) 2019-2020 Thibault FOUCART * * 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 @@ -320,18 +320,22 @@ if (empty($reshook)) $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + $accountancy_code_buy_intra = GETPOST('accountancy_code_buy_intra', 'alpha'); + $accountancy_code_buy_export = GETPOST('accountancy_code_buy_export', 'alpha'); if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } if ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; } if ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; } + if ($accountancy_code_buy_intra <= 0) { $object->accountancy_code_buy_intra = ''; } else { $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; } + if ($accountancy_code_buy_export <= 0) { $object->accountancy_code_buy_export = ''; } else { $object->accountancy_code_buy_export = $accountancy_code_buy_export; } // MultiPrix if (!empty($conf->global->PRODUIT_MULTIPRICES)) { for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { - if (isset($_POST["price_".$i])) + if (GETPOSTISSET("price_".$i)) { $object->multiprices["$i"] = price2num($_POST["price_".$i], 'MU'); $object->multiprices_base_type["$i"] = $_POST["multiprices_base_type_".$i]; @@ -461,11 +465,15 @@ if (empty($reshook)) $accountancy_code_sell_intra = GETPOST('accountancy_code_sell_intra', 'alpha'); $accountancy_code_sell_export = GETPOST('accountancy_code_sell_export', 'alpha'); $accountancy_code_buy = GETPOST('accountancy_code_buy', 'alpha'); + $accountancy_code_buy_intra = GETPOST('accountancy_code_buy_intra', 'alpha'); + $accountancy_code_buy_export = GETPOST('accountancy_code_buy_export', 'alpha'); if ($accountancy_code_sell <= 0) { $object->accountancy_code_sell = ''; } else { $object->accountancy_code_sell = $accountancy_code_sell; } if ($accountancy_code_sell_intra <= 0) { $object->accountancy_code_sell_intra = ''; } else { $object->accountancy_code_sell_intra = $accountancy_code_sell_intra; } if ($accountancy_code_sell_export <= 0) { $object->accountancy_code_sell_export = ''; } else { $object->accountancy_code_sell_export = $accountancy_code_sell_export; } if ($accountancy_code_buy <= 0) { $object->accountancy_code_buy = ''; } else { $object->accountancy_code_buy = $accountancy_code_buy; } + if ($accountancy_code_buy_intra <= 0) { $object->accountancy_code_buy_intra = ''; } else { $object->accountancy_code_buy_intra = $accountancy_code_buy_intra; } + if ($accountancy_code_buy_export <= 0) { $object->accountancy_code_buy_export = ''; } else { $object->accountancy_code_buy_export = $accountancy_code_buy_export; } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -545,7 +553,7 @@ if (empty($reshook)) if ($result < 1) { $db->rollback(); - setEventMessage($langs->trans('ErrorProductClone'), null, 'errors'); + setEventMessages($langs->trans('ErrorProductClone'), null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"]."?id=".$originalId); exit; } @@ -1235,10 +1243,10 @@ else // Accountancy_code_sell print ''.$langs->trans("ProductAccountancySellCode").''; print ''; - if ($type = 0) { - $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell') ?GETPOST('accountancy_code_sell', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT); + if ($type == 0) { + $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell') ? GETPOST('accountancy_code_sell', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT); } else { - $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell') ?GETPOST('accountancy_code_sell', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT); + $accountancy_code_sell = (GETPOSTISSET('accountancy_code_sell') ? GETPOST('accountancy_code_sell', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell, 'accountancy_code_sell', 1, null, 1, 1, ''); print ''; @@ -1248,10 +1256,10 @@ else { print ''.$langs->trans("ProductAccountancySellIntraCode").''; print ''; - if ($type = 0) { - $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra') ?GETPOST('accountancy_code_sell_intra', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT); + if ($type == 0) { + $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra') ? GETPOST('accountancy_code_sell_intra', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_INTRA_ACCOUNT); } else { - $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra') ?GETPOST('accountancy_code_sell_intra', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT); + $accountancy_code_sell_intra = (GETPOSTISSET('accountancy_code_sell_intra') ? GETPOST('accountancy_code_sell_intra', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_INTRA_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell_intra, 'accountancy_code_sell_intra', 1, null, 1, 1, ''); print ''; @@ -1260,11 +1268,11 @@ else // Accountancy_code_sell_export print ''.$langs->trans("ProductAccountancySellExportCode").''; print ''; - if ($type = 0) + if ($type == 0) { - $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ?GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT); + $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ? GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_SOLD_EXPORT_ACCOUNT); } else { - $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ?GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT); + $accountancy_code_sell_export = (GETPOST('accountancy_code_sell_export') ? GETPOST('accountancy_code_sell_export', 'alpha') : $conf->global->ACCOUNTING_SERVICE_SOLD_EXPORT_ACCOUNT); } print $formaccounting->select_account($accountancy_code_sell_export, 'accountancy_code_sell_export', 1, null, 1, 1, ''); print ''; @@ -1274,6 +1282,32 @@ else print ''; print $formaccounting->select_account(GETPOST('accountancy_code_buy', 'alpha'), 'accountancy_code_buy', 1, null, 1, 1, ''); print ''; + + // Accountancy_code_buy_intra + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("ProductAccountancyBuyIntraCode").''; + print ''; + if ($type == 0) { + $accountancy_code_buy_intra = (GETPOSTISSET('accountancy_code_buy_intra') ? GETPOST('accountancy_code_buy_intra', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_BUY_INTRA_ACCOUNT); + } else { + $accountancy_code_buy_intra = (GETPOSTISSET('accountancy_code_buy_intra') ? GETPOST('accountancy_code_buy_intra', 'alpha') : $conf->global->ACCOUNTING_SERVICE_BUY_INTRA_ACCOUNT); + } + print $formaccounting->select_account($accountancy_code_buy_intra, 'accountancy_code_buy_intra', 1, null, 1, 1, ''); + print ''; + } + + // Accountancy_code_buy_export + print ''.$langs->trans("ProductAccountancyBuyExportCode").''; + print ''; + if ($type == 0) + { + $accountancy_code_buy_export = (GETPOST('accountancy_code_buy_export') ? GETPOST('accountancy_code_buy_export', 'alpha') : $conf->global->ACCOUNTING_PRODUCT_BUY_EXPORT_ACCOUNT); + } else { + $accountancy_code_buy_export = (GETPOST('accountancy_code_buy_export') ? GETPOST('accountancy_code_buy_export', 'alpha') : $conf->global->ACCOUNTING_SERVICE_BUY_EXPORT_ACCOUNT); + } + print $formaccounting->select_account($accountancy_code_buy_export, 'accountancy_code_buy_export', 1, null, 1, 1, ''); + print ''; } else // For external software { @@ -1299,6 +1333,19 @@ else print ''.$langs->trans("ProductAccountancyBuyCode").''; print ''; print ''; + + // Accountancy_code_buy_intra + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("ProductAccountancyBuyIntraCode").''; + print ''; + print ''; + } + + // Accountancy_code_buy_export + print ''.$langs->trans("ProductAccountancyBuyExportCode").''; + print ''; + print ''; } print ''; @@ -1513,7 +1560,7 @@ else // Net Measure print ''.$langs->trans("NetMeasure").''; print ' '; - print $formproduct->selectMeasuringUnits($object->net_measure_units, '', 0, 0, 0); + print $formproduct->selectMeasuringUnits("net_measure_units", "", $object->net_measure_units, 0, 0); print ''; } } @@ -1554,8 +1601,10 @@ else $c = new Categorie($db); $cats = $c->containing($object->id, Categorie::TYPE_PRODUCT); $arrayselected = array(); - foreach ($cats as $cat) { - $arrayselected[] = $cat->id; + if (is_array($cats)) { + foreach ($cats as $cat) { + $arrayselected[] = $cat->id; + } } print $form->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%'); print ""; @@ -1606,6 +1655,21 @@ else print ''; print $formaccounting->select_account($object->accountancy_code_buy, 'accountancy_code_buy', 1, '', 1, 1); print ''; + + // Accountancy_code_buy_intra + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("ProductAccountancyBuyIntraCode").''; + print ''; + print $formaccounting->select_account($object->accountancy_code_buy_intra, 'accountancy_code_buy_intra', 1, '', 1, 1); + print ''; + } + + // Accountancy_code_buy_export + print ''.$langs->trans("ProductAccountancyBuyExportCode").''; + print ''; + print $formaccounting->select_account($object->accountancy_code_buy_export, 'accountancy_code_buy_export', 1, '', 1, 1); + print ''; } else // For external software { @@ -1631,6 +1695,19 @@ else print ''.$langs->trans("ProductAccountancyBuyCode").''; print ''; print ''; + + // Accountancy_code_buy_intra + if ($mysoc->isInEEC()) + { + print ''.$langs->trans("ProductAccountancyBuyIntraCode").''; + print ''; + print ''; + } + + // Accountancy_code_buy_export + print ''.$langs->trans("ProductAccountancyBuyExportCode").''; + print ''; + print ''; } print ''; @@ -1812,6 +1889,45 @@ else } print ''; + // Accountancy buy code intra-community + if ($mysoc->isInEEC()) + { + print ''; + print $langs->trans("ProductAccountancyBuyIntraCode"); + print ''; + if (!empty($conf->accounting->enabled)) + { + if (!empty($object->accountancy_code_buy_intra)) + { + $accountingaccount5 = new AccountingAccount($db); + $accountingaccount5->fetch('', $object->accountancy_code_buy_intra, 1); + + print $accountingaccount5->getNomUrl(0, 1, 1, '', 1); + } + } else { + print $object->accountancy_code_buy_intra; + } + print ''; + } + + // Accountancy buy code export + print ''; + print $langs->trans("ProductAccountancyBuyExportCode"); + print ''; + if (!empty($conf->accounting->enabled)) + { + if (!empty($object->accountancy_code_buy_export)) + { + $accountingaccount6 = new AccountingAccount($db); + $accountingaccount6->fetch('', $object->accountancy_code_buy_export, 1); + + print $accountingaccount6->getNomUrl(0, 1, 1, '', 1); + } + } else { + print $object->accountancy_code_buy_export; + } + print ''; + // Batch number management (to batch) if (!empty($conf->productbatch->enabled)) { @@ -1955,7 +2071,7 @@ else print ''.$langs->trans("NetMeasure").''; if ($object->net_measure != '') { - print $object->net_measure." ".measuringUnitString(0, "weight", $object->net_measure_units); + print $object->net_measure." ".measuringUnitString($object->net_measure_units); } else { diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index 1e189026366..d7d72e28b7c 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -73,9 +73,9 @@ class Products extends DolibarrApi * @param bool $includesubproducts Load information about subproducts * @return array|mixed Data without useless information * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ public function get($id, $includestockdata = 0, $includesubproducts = false) { @@ -95,9 +95,9 @@ class Products extends DolibarrApi * * @url GET ref/{ref} * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ public function getByRef($ref, $includestockdata = 0, $includesubproducts = false) { @@ -117,9 +117,9 @@ class Products extends DolibarrApi * * @url GET ref_ext/{ref_ext} * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false) { @@ -139,9 +139,9 @@ class Products extends DolibarrApi * * @url GET barcode/{barcode} * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false) { @@ -263,9 +263,8 @@ class Products extends DolibarrApi * @param array $request_data Datas * @return int * - * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 */ public function put($id, $request_data = null) { @@ -385,8 +384,8 @@ class Products extends DolibarrApi * @return array * * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * * @url GET {id}/subproducts */ @@ -423,8 +422,8 @@ class Products extends DolibarrApi * @return int * * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * * @url POST {id}/subproducts/add */ @@ -454,9 +453,8 @@ class Products extends DolibarrApi * @param int $subproduct_id Id of child product/service * @return int * - * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * * @url DELETE {id}/subproducts/remove */ @@ -632,6 +630,73 @@ class Products extends DolibarrApi ); } + /** + * Add/Update purchase prices for a product. + * + * @param int $id ID of Product + * @param float $qty Min quantity for which price is valid + * @param float $buyprice Purchase price for the quantity min + * @param string $price_base_type HT or TTC + * @param int $fourn_id Supplier ID + * @param int $availability Product availability + * @param string $ref_fourn Supplier ref + * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string) + * @param string $charges costs affering to product + * @param float $remise_percent Discount regarding qty (percent) + * @param float $remise Discount regarding qty (amount) + * @param int $newnpr Set NPR or not + * @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined. + * @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER) + * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function). + * @param string $newdefaultvatcode Default vat code + * @param float $multicurrency_buyprice Purchase price for the quantity min in currency + * @param string $multicurrency_price_base_type HT or TTC in currency + * @param float $multicurrency_tx Rate currency + * @param string $multicurrency_code Currency code + * @param string $desc_fourn Custom description for product_fourn_price + * @param string $barcode Barcode + * @param int $fk_barcode_type Barcode type + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url POST {id}/purchase_prices + */ + public function addPurchasePrice($id, $qty, $buyprice, $price_base_type, $fourn_id, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = null) + { + if(! DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } + + $result = $this->productsupplier->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty); + if ($result < 0) { + throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror()); + } + + $fourn = new Fournisseur($this->db); + $result = $fourn->fetch($fourn_id); + if ($result <= 0) { + throw new RestException(404, 'Supplier not found'); + } + + $result = $this->productsupplier->update_buyprice($qty, $buyprice, DolibarrApiAccess::$user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges, $remise_percent, $remise, $newnpr, $delivery_time_days, $supplier_reputation, $localtaxes_array, $newdefaultvatcode, $multicurrency_buyprice, $multicurrency_price_base_type, $multicurrency_tx, $multicurrency_code, $desc_fourn, $barcode, $fk_barcode_type); + + if ($result <= 0) { + throw new RestException(500, "Error updating buy price : ".$this->db->lasterror()); + } + return (int) $this->productsupplier->product_fourn_price_id; + } + /** * Delete purchase price for a product * @@ -642,8 +707,8 @@ class Products extends DolibarrApi * * @return int * - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * */ public function deletePurchasePrice($id, $priceid) @@ -769,9 +834,9 @@ class Products extends DolibarrApi * * @url GET {id}/purchase_prices * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 * */ public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '') @@ -829,8 +894,8 @@ class Products extends DolibarrApi * @return array * * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * * @url GET attributes/{id} */ @@ -856,8 +921,8 @@ class Products extends DolibarrApi * @param string $ref Reference of Attribute * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url GET attributes/ref/{ref} */ @@ -893,8 +958,8 @@ class Products extends DolibarrApi * @param string $label Label of Attribute * @return int * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url POST attributes */ @@ -923,8 +988,8 @@ class Products extends DolibarrApi * @return array * * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 401 + * @throws RestException 404 * * @url PUT attributes/{id} */ @@ -968,8 +1033,8 @@ class Products extends DolibarrApi * @param int $id ID of Attribute * @return int Result of deletion * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url DELETE attributes/{id} */ @@ -996,8 +1061,8 @@ class Products extends DolibarrApi * @param int $id ID of Attribute value * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url GET attributes/values/{id} */ @@ -1037,8 +1102,8 @@ class Products extends DolibarrApi * @param string $ref Ref of Attribute value * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url GET attributes/{id}/values/ref/{ref} */ @@ -1078,8 +1143,7 @@ class Products extends DolibarrApi * @param string $ref Ref of Attribute value * @return int * - * @throws RestException - * @throws 401 + * @throws RestException 401 * * @url DELETE attributes/{id}/values/ref/{ref} */ @@ -1104,8 +1168,8 @@ class Products extends DolibarrApi * @param int $id ID of an Attribute * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 401 + * @throws RestException 500 * * @url GET attributes/{id}/values */ @@ -1125,8 +1189,7 @@ class Products extends DolibarrApi * @param string $ref Ref of an Attribute * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 401 * * @url GET attributes/ref/{ref}/values */ @@ -1165,8 +1228,8 @@ class Products extends DolibarrApi * @param string $value Value of Attribute value * @return int * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url POST attributes/{id}/values */ @@ -1198,8 +1261,8 @@ class Products extends DolibarrApi * @param array $request_data Datas * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 401 + * @throws RestException 500 * * @url PUT attributes/values/{id} */ @@ -1243,8 +1306,8 @@ class Products extends DolibarrApi * @param int $id ID of Attribute value * @return int * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url DELETE attributes/values/{id} */ @@ -1269,8 +1332,8 @@ class Products extends DolibarrApi * @param int $id ID of Product * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url GET {id}/variants */ @@ -1297,8 +1360,8 @@ class Products extends DolibarrApi * @param string $ref Ref of Product * @return array * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url GET ref/{ref}/variants */ @@ -1329,20 +1392,21 @@ class Products extends DolibarrApi * * "features" is a list of attributes pairs id_attribute=>id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) * - * @param int $id ID of Product - * @param float $weight_impact Weight impact of variant - * @param float $price_impact Price impact of variant - * @param bool $price_impact_is_percent Price impact in percent (true or false) - * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * @param int $id ID of Product + * @param float $weight_impact Weight impact of variant + * @param float $price_impact Price impact of variant + * @param bool $price_impact_is_percent Price impact in percent (true or false) + * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * @param bool|string $reference Customized reference of variant * @return int * - * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 500 + * @throws RestException 401 + * @throws RestException 404 * * @url POST {id}/variants */ - public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features) + public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = false) { if (!DolibarrApiAccess::$user->rights->produit->creer) { throw new RestException(401); @@ -1372,17 +1436,13 @@ class Products extends DolibarrApi } $prodcomb = new ProductCombination($this->db); - if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $features)) + + $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference); + if ($result > 0) { - $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact); - if ($result > 0) - { - return $result; - } else { - throw new RestException(500, "Error creating new product variant"); - } + return $result; } else { - return $prodcomb->id; + throw new RestException(500, "Error creating new product variant"); } } @@ -1398,9 +1458,9 @@ class Products extends DolibarrApi * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) * @return int * - * @throws RestException - * @throws 401 - * @throws 404 + * @throws RestException 500 + * @throws RestException 401 + * @throws RestException 404 * * @url POST ref/{ref}/variants */ @@ -1455,8 +1515,8 @@ class Products extends DolibarrApi * @param array $request_data Datas * @return int * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url PUT variants/{id} */ @@ -1489,8 +1549,8 @@ class Products extends DolibarrApi * @param int $id ID of Variant * @return int Result of deletion * - * @throws RestException - * @throws 401 + * @throws RestException 500 + * @throws RestException 401 * * @url DELETE variants/{id} */ @@ -1570,9 +1630,9 @@ class Products extends DolibarrApi * @param bool $includesubproducts Load information about subproducts * @return array|mixed Data without useless information * - * @throws 401 - * @throws 403 - * @throws 404 + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 */ private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false) { diff --git a/htdocs/product/class/html.formproduct.class.php b/htdocs/product/class/html.formproduct.class.php index af78ab5b59d..6443b0d03a3 100644 --- a/htdocs/product/class/html.formproduct.class.php +++ b/htdocs/product/class/html.formproduct.class.php @@ -254,6 +254,9 @@ class FormProduct $out.= $comboenhancement; } + if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $selected = $conf->global->MAIN_DEFAULT_WAREHOUSE; + if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $selected = $user->fk_warehouse; + $out.=''; print ''; print ''; - print ''; + //print ''; print ''; if (empty($arrayfields['p.fk_product_type']['checked'])) print ''; - print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'products', 0, $newcardbutton, '', $limit); + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'products', 0, $newcardbutton, '', $limit, 0, 0, 1); $topicmail = "Information"; $modelmail = "product"; @@ -630,6 +645,12 @@ if ($resql) print ''; } + // Finished + if (!empty($arrayfields['p.finished']['checked'])) + { + print ''; + print ''; + } // Weight if (!empty($arrayfields['p.weight']['checked'])) { @@ -762,7 +783,9 @@ if ($resql) if (!empty($arrayfields['p.accountancy_code_sell_intra']['checked'])) print ''; if (!empty($arrayfields['p.accountancy_code_sell_export']['checked'])) print ''; // Accountancy code buy - if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) print ''; + if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) print ''; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; // Fields from hook @@ -819,6 +842,10 @@ if ($resql) if (!empty($arrayfields['p.duration']['checked'])) { print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"], "p.duration", "", $param, '', $sortfield, $sortorder, 'center '); } + if (!empty($arrayfields['p.finished']['checked'])) { + print_liste_field_titre($arrayfields['p.finished']['label'], $_SERVER["PHP_SELF"], "p.finished", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.weight']['checked'])) print_liste_field_titre($arrayfields['p.weight']['label'], $_SERVER['PHP_SELF'], 'p.weight', '', $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['p.weight_units']['checked'])) print_liste_field_titre($arrayfields['p.weight_units']['label'], $_SERVER['PHP_SELF'], 'p.weight_units', '', $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['p.length']['checked'])) print_liste_field_titre($arrayfields['p.length']['label'], $_SERVER['PHP_SELF'], 'p.length', '', $param, '', $sortfield, $sortorder, 'center '); @@ -874,6 +901,12 @@ if ($resql) if (!empty($arrayfields['p.accountancy_code_buy']['checked'])) { print_liste_field_titre($arrayfields['p.accountancy_code_buy']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_buy", "", $param, '', $sortfield, $sortorder); } + if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) { + print_liste_field_titre($arrayfields['p.accountancy_code_buy_intra']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_buy_intra", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) { + print_liste_field_titre($arrayfields['p.accountancy_code_buy_export']['label'], $_SERVER["PHP_SELF"], "p.accountancy_code_buy_export", "", $param, '', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -927,6 +960,7 @@ if ($resql) $product_static->ref_fourn = $obj->ref_supplier; // deprecated $product_static->ref_supplier = $obj->ref_supplier; $product_static->label = $obj->label; + $product_static->finished = $obj->finished; $product_static->type = $obj->fk_product_type; $product_static->status_buy = $obj->tobuy; $product_static->status = $obj->tosell; @@ -937,6 +971,8 @@ if ($resql) $product_static->accountancy_code_sell_export = $obj->accountancy_code_sell_export; $product_static->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra; $product_static->accountancy_code_buy = $obj->accountancy_code_buy; + $product_static->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra; + $product_static->accountancy_code_buy_export = $obj->accountancy_code_buy_export; $product_static->length = $obj->length; $product_static->length_units = $obj->length_units; $product_static->width = $obj->width; @@ -1038,6 +1074,15 @@ if ($resql) if (!$i) $totalarray['nbfield']++; } + // Finished + if (!empty($arrayfields['p.finished']['checked'])) + { + print ''; + print $product_static->getLibFinished(); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Weight if (!empty($arrayfields['p.weight']['checked'])) { @@ -1284,6 +1329,16 @@ if ($resql) print ''.$obj->accountancy_code_buy.''; if (!$i) $totalarray['nbfield']++; } + if (!empty($arrayfields['p.accountancy_code_buy_intra']['checked'])) + { + print ''.$obj->accountancy_code_buy_intra.''; + if (!$i) $totalarray['nbfield']++; + } + if (!empty($arrayfields['p.accountancy_code_buy_export']['checked'])) + { + print ''.$obj->accountancy_code_buy_export.''; + if (!$i) $totalarray['nbfield']++; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Fields from hook diff --git a/htdocs/product/popucom.php b/htdocs/product/popucom.php new file mode 100644 index 00000000000..7b89e04bf61 --- /dev/null +++ b/htdocs/product/popucom.php @@ -0,0 +1,217 @@ + + * Copyright (C) 2004-2005 Laurent Destailleur + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Marcos García + * Copyright (C) 2015 Jean-François Ferry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/product/popucom.php + * \ingroup commande, produit + * \brief Liste des produits/services par popularite + */ + +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + +// Load translation files required by the page +//Required to translate NbOfCommande +$langs->load('commande'); + +$type=GETPOST("type", "int"); + +// Security check +if (! empty($user->socid)) $socid=$user->socid; +$result=restrictedArea($user, 'produit|service'); + +$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (! $sortfield) $sortfield="c"; +if (! $sortorder) $sortorder="DESC"; +$offset = $limit * $page ; +$pageprev = $page - 1; +$pagenext = $page + 1; + + +$staticproduct=new Product($db); + + +/* + * View + */ + +$helpurl=''; +if ($type == '0') +{ + $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; +} +elseif ($type == '1') +{ + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; +} +else +{ + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; +} +$title=$langs->trans("Statistics"); + + +llxHeader('', $title, $helpurl); + +print load_fiche_titre($title, $mesg, 'products'); + + +$param = ''; +$title = $langs->trans("ListProductServiceByPopularity"); +if ((string) $type == '1') { + $title = $langs->trans("ListServiceByPopularity"); +} +if ((string) $type == '0') { + $title = $langs->trans("ListProductByPopularity"); +} + +if ($type != '') $param .= '&type='.$type; + + +$h=0; +$head = array(); + +$head[$h][0] = DOL_URL_ROOT.'/product/stats/card.php?id=all'; +$head[$h][1] = $langs->trans("Chart"); +$head[$h][2] = 'chart'; +$h++; + +$head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'; +$head[$h][1] = $langs->trans("PopuProp"); +$head[$h][2] = 'popularityprop'; +$h++; + +$head[$h][0] = DOL_URL_ROOT.'/product/popucom.php'; +$head[$h][1] = $langs->trans("PopuCom"); +$head[$h][2] = 'popularitycommande'; +$h++; + +dol_fiche_head($head, 'popularitycommande', $langs->trans("Statistics"), -1); + + +// Array of liens to show +$infoprod=array(); + + +// Add lines for commande +$sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type as type, SUM(pd.qty) as c"; +$sql.= " FROM ".MAIN_DB_PREFIX."commandedet as pd"; +$sql.= ", ".MAIN_DB_PREFIX."product as p"; +$sql.= ' WHERE p.entity IN ('.getEntity('product').')'; +$sql.= " AND p.rowid = pd.fk_product"; +if ($type !== '') { + $sql.= " AND fk_product_type = ".$type; +} +$sql.= " GROUP BY p.rowid, p.label, p.ref, p.fk_product_type"; + +$result=$db->query($sql); +if ($result) +{ + $totalnboflines = $db->num_rows($result); +} + +$sql.= $db->order($sortfield, $sortorder); +$sql.= $db->plimit($limit+1, $offset); + +$resql=$db->query($sql); +if ($resql) +{ + $num = $db->num_rows($resql); + $i = 0; + + while ($i < $num) + { + $objp = $db->fetch_object($resql); + + $infoprod[$objp->rowid]=array('type'=>$objp->type, 'ref'=>$objp->ref, 'label'=>$objp->label); + $infoprod[$objp->rowid]['nblinecommande']=$objp->c; + + $i++; + } + $db->free($resql); +} +else +{ + dol_print_error($db); +} +//var_dump($infoprod); + + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, "", $num, $totalnboflines, ''); + +print ''; + +print ""; +print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'p.ref', '', $param, '', $sortfield, $sortorder); +print_liste_field_titre('Type', $_SERVER["PHP_SELF"], 'p.fk_product_type', '', $param, '', $sortfield, $sortorder); +print_liste_field_titre('Label', $_SERVER["PHP_SELF"], 'p.label', '', $param, '', $sortfield, $sortorder); +print_liste_field_titre('NbOfQtyInOrders', $_SERVER["PHP_SELF"], 'c', '', $param, '', $sortfield, $sortorder, 'right '); +print "\n"; + +foreach($infoprod as $prodid => $vals) +{ + // Multilangs + if (! empty($conf->global->MAIN_MULTILANGS)) // si l'option est active + { + $sql = "SELECT label"; + $sql.= " FROM ".MAIN_DB_PREFIX."product_lang"; + $sql.= " WHERE fk_product=".$prodid; + $sql.= " AND lang='". $langs->getDefaultLang() ."'"; + $sql.= " LIMIT 1"; + + $resultp = $db->query($sql); + if ($resultp) + { + $objtp = $db->fetch_object($resultp); + if (! empty($objtp->label)) $vals['label'] = $objtp->label; + } + } + + print ""; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $i++; +} + +print "
    '; + if ($vals['type'] == 1) print img_object($langs->trans("ShowService"), "service"); + else print img_object($langs->trans("ShowProduct"), "product"); + print " "; + print $vals['ref'].''; + if ($vals['type'] == 1) print $langs->trans("Service"); + else print $langs->trans("Product"); + print ''.$vals['label'].''.$vals['nblinecommande'].'
    "; + + + +dol_fiche_end(); + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/popuprop.php b/htdocs/product/popuprop.php index 95bf2b965a2..770a02fded5 100644 --- a/htdocs/product/popuprop.php +++ b/htdocs/product/popuprop.php @@ -42,7 +42,7 @@ $result=restrictedArea($user, 'produit|service'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (! $sortfield) $sortfield="c"; if (! $sortorder) $sortorder="DESC"; @@ -99,11 +99,16 @@ $head[$h][1] = $langs->trans("Chart"); $head[$h][2] = 'chart'; $h++; -$head[$h][0] = $_SERVER['PHP_SELF']; -$head[$h][1] = $title; +$head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'; +$head[$h][1] = $langs->trans("PopuProp"); $head[$h][2] = 'popularityprop'; $h++; +$head[$h][0] = DOL_URL_ROOT.'/product/popucom.php'; +$head[$h][1] = $langs->trans("PopuCom"); +$head[$h][2] = 'popularitycommande'; +$h++; + dol_fiche_head($head, 'popularityprop', $langs->trans("Statistics"), -1); diff --git a/htdocs/product/reassort.php b/htdocs/product/reassort.php index c107693b8c6..1af1cebfbb5 100644 --- a/htdocs/product/reassort.php +++ b/htdocs/product/reassort.php @@ -54,7 +54,7 @@ $fourn_id = GETPOST("fourn_id", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; if (!$sortfield) $sortfield = "p.ref"; if (!$sortorder) $sortorder = "ASC"; @@ -256,14 +256,14 @@ if ($resql) } $param = ''; - if ($tosell) $param .= "&tosell=".$tosell; - if ($tobuy) $param .= "&tobuy=".$tobuy; - if ($type) $param .= "&type=".$type; - if ($fourn_id) $param .= "&fourn_id=".$fourn_id; - if ($snom) $param .= "&snom=".$snom; - if ($sref) $param .= "&sref=".$sref; - if ($toolowstock) $param .= "&toolowstock=".$toolowstock; - if ($search_categ) $param .= "&search_categ=".$search_categ; + if ($tosell) $param .= "&tosell=".urlencode($tosell); + if ($tobuy) $param .= "&tobuy=".urlencode($tobuy); + if ($type) $param .= "&type=".urlencode($type); + if ($fourn_id) $param .= "&fourn_id=".urlencode($fourn_id); + if ($snom) $param .= "&snom=".urlencode($snom); + if ($sref) $param .= "&sref=".urlencode($sref); + if ($toolowstock) $param .= "&toolowstock=".urlencode($toolowstock); + if ($search_categ) $param .= "&search_categ=".urlencode($search_categ); $formProduct = new FormProduct($db); $formProduct->loadWarehouses(); @@ -362,7 +362,7 @@ if ($resql) // Real stock print ''; if ($objp->seuil_stock_alerte != '' && ($objp->stock_physique < $objp->seuil_stock_alerte)) print img_warning($langs->trans("StockTooLow")).' '; - print $objp->stock_physique | 0; + print price2num($objp->stock_physique, 'MS'); print ''; // Details per warehouse diff --git a/htdocs/product/reassortlot.php b/htdocs/product/reassortlot.php index e07dcf0536d..cd65b2c09f7 100644 --- a/htdocs/product/reassortlot.php +++ b/htdocs/product/reassortlot.php @@ -58,7 +58,7 @@ $fourn_id = GETPOST("fourn_id", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page < 0) $page = 0; if (!$sortfield) $sortfield = "p.ref"; if (!$sortorder) $sortorder = "ASC"; diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index 24387ef8b73..e2a30b51a87 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -161,10 +161,15 @@ if (empty($id) & empty($ref)) } $head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'.($type != '' ? '?type='.$type : ''); - $head[$h][1] = $title; + $head[$h][1] = $langs->trans("PopuProp"); $head[$h][2] = 'popularityprop'; $h++; + $head[$h][0] = DOL_URL_ROOT.'/product/popucom.php'.($type != '' ? '?type='.$type : ''); + $head[$h][1] = $langs->trans("PopuCom"); + $head[$h][2] = 'popularitycommande'; + $h++; + dol_fiche_head($head, 'chart', $langs->trans("Statistics"), -1); } @@ -294,6 +299,12 @@ if ($result || empty($id)) 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsContracts") : $langs->transnoentitiesnoconv("NumberOfContracts"))); } + if ($conf->mrp->enabled) { + $graphfiles['mrp'] = array('modulepart'=>'productstats_mrp', + 'file' => $object->id.'/mos12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year ? '_year'.$search_year : '').'.png', + 'label' => ($mode == 'byunit' ? $langs->transnoentitiesnoconv("NumberOfUnitsMos") : $langs->transnoentitiesnoconv("NumberOfMos"))); + } + $px = new DolGraph(); if (!$error && count($graphfiles) > 0) @@ -333,6 +344,7 @@ if ($result || empty($id)) if ($key == 'invoicessuppliers') $graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'orderssuppliers') $graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); if ($key == 'contracts') $graph_data = $object->get_nb_contract($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'mrp') $graph_data = $object->get_nb_mos($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); // TODO Save cachefile $graphfiles[$key]['file'] } @@ -343,6 +355,7 @@ if ($result || empty($id)) $px->SetYLabel($graphfiles[$key]['label']); $px->SetMaxValue($px->GetCeilMaxValue() < 0 ? 0 : $px->GetCeilMaxValue()); $px->SetMinValue($px->GetFloorMinValue() > 0 ? 0 : $px->GetFloorMinValue()); + $px->setShowLegend(0); $px->SetWidth($WIDTH); $px->SetHeight($HEIGHT); $px->SetHorizTickIncrement(1); @@ -379,6 +392,7 @@ if ($result || empty($id)) if ($graphfiles == 'proposals_suppliers' && !$user->rights->supplier_proposal->lire) continue; if ($graphfiles == 'invoices_suppliers' && !$user->rights->fournisseur->facture->lire) continue; if ($graphfiles == 'orders_suppliers' && !$user->rights->fournisseur->commande->lire) continue; + if ($graphfiles == 'mrp' && empty($user->rights->mrp->mo->read)) continue; if ($i % 2 == 0) @@ -407,7 +421,7 @@ if ($result || empty($id)) // Label print ''; print $graphfiles[$key]['label']; - print ' ('.$graphfiles[$key]['total'].')'; + print ' ('.$graphfiles[$key]['total'].')'; print ''.$linktoregenerate.''; print ''; // Image diff --git a/htdocs/product/stats/commande.php b/htdocs/product/stats/commande.php index 4299a1db53b..71c1b0f1ef7 100644 --- a/htdocs/product/stats/commande.php +++ b/htdocs/product/stats/commande.php @@ -37,11 +37,11 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); -$socid=''; -if (! empty($user->socid)) $socid=$user->socid; -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +$socid = ''; +if (!empty($user->socid)) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('productstatsorder')); @@ -49,62 +49,62 @@ $hookmanager->initHooks(array('productstatsorder')); $mesg = ''; // Load variable for pagination -$limit = GETPOST('limit', 'int')?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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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="c.date_commande"; -$search_month = GETPOST('search_month', 'aplha'); +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "c.date_commande"; +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { - $search_month=''; - $search_year=''; + $search_month = ''; + $search_year = ''; } /* * View */ -$orderstatic=new Commande($db); -$societestatic=new Societe($db); +$orderstatic = new Commande($db); +$societestatic = new Societe($db); $form = new Form($db); -$formother= new FormOther($db); +$formother = new FormOther($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); $object = $product; - $parameters=array('id'=>$id); - $reshook=$hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('id'=>$id); + $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); llxHeader("", "", $langs->trans("CardProduct".$product->type)); if ($result > 0) { - $head=product_prepare_head($product); - $titre=$langs->trans("CardProduct".$product->type); - $picto=($product->type==Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($product); + $titre = $langs->trans("CardProduct".$product->type); + $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'referers', $titre, -1, $picto); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; - if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -126,28 +126,28 @@ if ($id > 0 || ! empty($ref)) if ($user->rights->commande->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client, c.rowid, d.total_ht as total_ht, c.ref,"; - $sql.= " c.ref_client,"; - $sql.= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", sc.fk_soc, sc.fk_user "; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."commande as c"; - $sql.= ", ".MAIN_DB_PREFIX."commandedet as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE c.fk_soc = s.rowid"; - $sql.= " AND c.entity IN (".getEntity('commande').")"; - $sql.= " AND d.fk_commande = c.rowid"; - $sql.= " AND d.fk_product =".$product->id; - if (! empty($search_month)) - $sql.= ' AND MONTH(c.date_commande) IN (' . $search_month . ')'; - if (! empty($search_year)) - $sql.= ' AND YEAR(c.date_commande) IN (' . $search_year . ')'; - if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($socid) $sql.= " AND c.fk_soc = ".$socid; - $sql.= $db->order($sortfield, $sortorder); + $sql .= " c.ref_client,"; + $sql .= " c.date_commande, c.fk_statut as statut, c.facture, c.rowid as commandeid, d.rowid, d.qty"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."commande as c"; + $sql .= ", ".MAIN_DB_PREFIX."commandedet as d"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE c.fk_soc = s.rowid"; + $sql .= " AND c.entity IN (".getEntity('commande').")"; + $sql .= " AND d.fk_commande = c.rowid"; + $sql .= " AND d.fk_product =".$product->id; + if (!empty($search_month)) + $sql .= ' AND MONTH(c.date_commande) IN ('.$search_month.')'; + if (!empty($search_year)) + $sql .= ' AND YEAR(c.date_commande) IN ('.$search_year.')'; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) $sql .= " AND c.fk_soc = ".$socid; + $sql .= $db->order($sortfield, $sortorder); //Calcul total qty and amount for global if full scan list - $total_ht=0; - $total_qty=0; + $total_ht = 0; + $total_qty = 0; // Count total nb of records $totalofrecords = ''; @@ -164,30 +164,30 @@ if ($id > 0 || ! empty($ref)) { $num = $db->num_rows($result); - if (! empty($id)) + if (!empty($id)) $option .= '&id='.$product->id; - if (! empty($search_month)) + if (!empty($search_month)) $option .= '&search_month='.$search_month; - if (! empty($search_year)) + if (!empty($search_year)) $option .= '&search_year='.$search_year; - if ($limit > 0 && $limit != $conf->liste_limit) $option.='&limit='.urlencode($limit); + if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - print '
    ' . "\n"; - if (! empty($sortfield)) - print ''; - if (! empty($sortorder)) - print ''; - if (! empty($page)) { - print ''; - $option .= '&page=' . $page; + print ''."\n"; + if (!empty($sortfield)) + print ''; + if (!empty($sortorder)) + print ''; + if (!empty($page)) { + print ''; + $option .= '&page='.$page; } print_barre_liste($langs->trans("CustomersOrders"), $page, $_SERVER["PHP_SELF"], "&id=".$product->id, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit); print '
    '; print '
    '; - print $langs->trans('Period').' ('.$langs->trans("OrderDate") .') - '; - print $langs->trans('Month') . ': '; - print $langs->trans('Year') . ':' . $formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5); + print $langs->trans('Period').' ('.$langs->trans("OrderDate").') - '; + print $langs->trans('Month').': '; + print $langs->trans('Year').':'.$formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5); print '
    '; print ''; print ''; @@ -214,12 +214,12 @@ if ($id > 0 || ! empty($ref)) { $objp = $db->fetch_object($result); - $total_ht+=$objp->total_ht; - $total_qty+=$objp->qty; + $total_ht += $objp->total_ht; + $total_qty += $objp->qty; - $orderstatic->id=$objp->commandeid; - $orderstatic->ref=$objp->ref; - $orderstatic->ref_client=$objp->ref_client; + $orderstatic->id = $objp->commandeid; + $orderstatic->ref = $objp->ref; + $orderstatic->ref_client = $objp->ref_client; $societestatic->fetch($objp->socid); print ''; diff --git a/htdocs/product/stats/commande_fournisseur.php b/htdocs/product/stats/commande_fournisseur.php index df6abec3d22..7a5b88000e1 100644 --- a/htdocs/product/stats/commande_fournisseur.php +++ b/htdocs/product/stats/commande_fournisseur.php @@ -54,7 +54,7 @@ $mesg = ''; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -63,7 +63,7 @@ if (!$sortorder) $sortorder = "DESC"; if (!$sortfield) $sortfield = "c.date_commande"; -$search_month = GETPOST('search_month', 'aplha'); +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { diff --git a/htdocs/product/stats/contrat.php b/htdocs/product/stats/contrat.php index a478a542f0f..8e61446a834 100644 --- a/htdocs/product/stats/contrat.php +++ b/htdocs/product/stats/contrat.php @@ -49,7 +49,7 @@ $mesg = ''; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -183,9 +183,9 @@ if ($id > 0 || !empty($ref)) print_liste_field_titre("CustomerCode", $_SERVER["PHP_SELF"], "s.code_client", "", "&id=".$product->id, '', $sortfield, $sortorder); print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "c.date_contrat", "", "&id=".$product->id, 'align="center"', $sortfield, $sortorder); //print_liste_field_titre("AmountHT"),$_SERVER["PHP_SELF"],"c.amount","","&id=".$product->id,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($staticcontratligne->LibStatut(0, 3), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); - print_liste_field_titre($staticcontratligne->LibStatut(4, 3), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); - print_liste_field_titre($staticcontratligne->LibStatut(5, 3), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); + print_liste_field_titre($staticcontratligne->LibStatut($staticcontratligne::STATUS_INITIAL, 3, -1, 'class="nochangebackground"'), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); + print_liste_field_titre($staticcontratligne->LibStatut($staticcontratligne::STATUS_OPEN, 3, -1, 'class="nochangebackground"'), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); + print_liste_field_titre($staticcontratligne->LibStatut($staticcontratligne::STATUS_CLOSED, 3, -1, 'class="nochangebackground"'), $_SERVER["PHP_SELF"], "", '', '', 'align="center" width="16"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; $contracttmp = new Contrat($db); diff --git a/htdocs/product/stats/facture.php b/htdocs/product/stats/facture.php index 7bb784f5031..e42afd9f28c 100644 --- a/htdocs/product/stats/facture.php +++ b/htdocs/product/stats/facture.php @@ -38,35 +38,35 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : '')); -$fieldtype = (! empty($ref) ? 'ref' : 'rowid'); -$socid=''; -if (! empty($user->socid)) $socid=$user->socid; -$result=restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +$socid = ''; +if (!empty($user->socid)) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('productstatsinvoice')); -$showmessage=GETPOST('showmessage'); +$showmessage = GETPOST('showmessage'); // Load variable for pagination -$limit = GETPOST('limit', 'int')?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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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="f.datef"; +if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "f.datef"; -$search_month = GETPOST('search_month', 'aplha'); +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { - $search_month=''; - $search_year=''; + $search_month = ''; + $search_year = ''; } @@ -75,21 +75,21 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', * View */ -$invoicestatic=new Facture($db); -$societestatic=new Societe($db); +$invoicestatic = new Facture($db); +$societestatic = new Societe($db); $form = new Form($db); -$formother= new FormOther($db); +$formother = new FormOther($db); -if ($id > 0 || ! empty($ref)) +if ($id > 0 || !empty($ref)) { $product = new Product($db); $result = $product->fetch($id, $ref); $object = $product; - $parameters=array('id'=>$id); - $reshook=$hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks + $parameters = array('id'=>$id); + $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); $title = $langs->trans('ProductServiceCard'); @@ -97,32 +97,32 @@ if ($id > 0 || ! empty($ref)) $shortlabel = dol_trunc($object->label, 16); if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Referers'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + $title = $langs->trans('Product')." ".$shortlabel." - ".$langs->trans('Referers'); + $helpurl = 'EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Referers'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + $title = $langs->trans('Service')." ".$shortlabel." - ".$langs->trans('Referers'); + $helpurl = 'EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } llxHeader('', $title, $helpurl); if ($result > 0) { - $head=product_prepare_head($product); - $titre=$langs->trans("CardProduct".$product->type); - $picto=($product->type==Product::TYPE_SERVICE?'service':'product'); + $head = product_prepare_head($product); + $titre = $langs->trans("CardProduct".$product->type); + $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); dol_fiche_head($head, 'referers', $titre, -1, $picto); - $reshook=$hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); $linkback = ''.$langs->trans("BackToList").''; $shownav = 1; - if ($user->socid && ! in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav=0; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); @@ -147,28 +147,28 @@ if ($id > 0 || ! empty($ref)) elseif ($user->rights->facture->lire) { $sql = "SELECT DISTINCT s.nom as name, s.rowid as socid, s.code_client,"; - $sql.= " f.ref, f.datef, f.paye, f.type, f.fk_statut as statut, f.rowid as facid,"; - $sql.= " d.rowid, d.total_ht as total_ht, d.qty"; // We must keep the d.rowid here to not loose record because of the distinct used to ignore duplicate line when link on societe_commerciaux is used - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", sc.fk_soc, sc.fk_user "; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."facture as f"; - $sql.= ", ".MAIN_DB_PREFIX."facturedet as d"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql.= " WHERE f.fk_soc = s.rowid"; - $sql.= " AND f.entity IN (".getEntity('invoice').")"; - $sql.= " AND d.fk_facture = f.rowid"; - $sql.= " AND d.fk_product =".$product->id; - if (! empty($search_month)) - $sql.= ' AND MONTH(f.datef) IN (' . $search_month . ')'; - if (! empty($search_year)) - $sql.= ' AND YEAR(f.datef) IN (' . $search_year . ')'; - if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if ($socid) $sql.= " AND f.fk_soc = ".$socid; - $sql.= $db->order($sortfield, $sortorder); + $sql .= " f.ref, f.datef, f.paye, f.type, f.fk_statut as statut, f.rowid as facid,"; + $sql .= " d.rowid, d.total_ht as total_ht, d.qty"; // We must keep the d.rowid here to not loose record because of the distinct used to ignore duplicate line when link on societe_commerciaux is used + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."facture as f"; + $sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; + if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= " WHERE f.fk_soc = s.rowid"; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; + $sql .= " AND d.fk_facture = f.rowid"; + $sql .= " AND d.fk_product =".$product->id; + if (!empty($search_month)) + $sql .= ' AND MONTH(f.datef) IN ('.$search_month.')'; + if (!empty($search_year)) + $sql .= ' AND YEAR(f.datef) IN ('.$search_year.')'; + if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) $sql .= " AND f.fk_soc = ".$socid; + $sql .= $db->order($sortfield, $sortorder); // Calcul total qty and amount for global if full scan list - $total_ht=0; - $total_qty=0; + $total_ht = 0; + $total_qty = 0; // Count total nb of records $totalofrecords = ''; @@ -178,37 +178,37 @@ if ($id > 0 || ! empty($ref)) $totalofrecords = $db->num_rows($result); } - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - if (! empty($id)) + if (!empty($id)) $option .= '&id='.$product->id; - if (! empty($search_month)) + if (!empty($search_month)) $option .= '&search_month='.$search_month; - if (! empty($search_year)) + if (!empty($search_year)) $option .= '&search_year='.$search_year; - if ($limit > 0 && $limit != $conf->liste_limit) $option.='&limit='.urlencode($limit); + if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); - print '' . "\n"; - if (! empty($sortfield)) - print ''; - if (! empty($sortorder)) - print ''; - if (! empty($page)) { - print ''; - $option .= '&page=' . $page; + print ''."\n"; + if (!empty($sortfield)) + print ''; + if (!empty($sortorder)) + print ''; + if (!empty($page)) { + print ''; + $option .= '&page='.$page; } print_barre_liste($langs->trans("CustomersInvoices"), $page, $_SERVER["PHP_SELF"], "&id=".$product->id, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit); print '
    '; print '
    '; - print $langs->trans('Period').' ('.$langs->trans("DateInvoice") .') - '; - print $langs->trans('Month') . ': '; - print $langs->trans('Year') . ':' . $formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5); + print $langs->trans('Period').' ('.$langs->trans("DateInvoice").') - '; + print $langs->trans('Month').': '; + print $langs->trans('Year').':'.$formother->selectyear($search_year ? $search_year : - 1, 'search_year', 1, 20, 5); print '
    '; print ''; print ''; @@ -235,13 +235,13 @@ if ($id > 0 || ! empty($ref)) { $objp = $db->fetch_object($result); - if ($objp->type == Facture::TYPE_CREDIT_NOTE) $objp->qty=-($objp->qty); + if ($objp->type == Facture::TYPE_CREDIT_NOTE) $objp->qty = -($objp->qty); - $total_ht+=$objp->total_ht; - $total_qty+=$objp->qty; + $total_ht += $objp->total_ht; + $total_qty += $objp->qty; - $invoicestatic->id=$objp->facid; - $invoicestatic->ref=$objp->ref; + $invoicestatic->id = $objp->facid; + $invoicestatic->ref = $objp->ref; $societestatic->fetch($objp->socid); $paiement = $invoicestatic->getSommePaiement(); diff --git a/htdocs/product/stats/facture_fournisseur.php b/htdocs/product/stats/facture_fournisseur.php index 34247393106..29774709e5e 100644 --- a/htdocs/product/stats/facture_fournisseur.php +++ b/htdocs/product/stats/facture_fournisseur.php @@ -53,14 +53,14 @@ $mesg = ''; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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 = "f.datef"; -$search_month = GETPOST('search_month', 'aplha'); +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { diff --git a/htdocs/product/stats/mo.php b/htdocs/product/stats/mo.php new file mode 100644 index 00000000000..0a148ad2c8a --- /dev/null +++ b/htdocs/product/stats/mo.php @@ -0,0 +1,235 @@ + + * Copyright (C) 2004-2009 Laurent Destailleur + * 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/product/stats/mo.php + * \ingroup product mo + * \brief Page of MO referring product + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('mrp', 'products', 'companies')); + +$id = GETPOST('id', 'int'); +$ref = GETPOST('ref', 'alpha'); + +// Security check +$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : '')); +$fieldtype = (!empty($ref) ? 'ref' : 'rowid'); +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype); + +// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context +$hookmanager->initHooks(array('productstatscontract')); + +$mesg = ''; + +// Load variable for pagination +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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 = "c.date_valid"; + + +/* + * View + */ + +$staticmo = new Mo($db); +$staticmoligne = new MoLine($db); + +$form = new Form($db); + +if ($id > 0 || !empty($ref)) +{ + $product = new Product($db); + $result = $product->fetch($id, $ref); + + $object = $product; + + $parameters = array('id'=>$id); + $reshook = $hookmanager->executeHooks('doActions', $parameters, $product, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + llxHeader("", "", $langs->trans("CardProduct".$product->type)); + + if ($result > 0) + { + $head = product_prepare_head($product); + $titre = $langs->trans("CardProduct".$product->type); + $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); + dol_fiche_head($head, 'referers', $titre, -1, $picto); + + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $linkback = ''.$langs->trans("BackToList").''; + + $shownav = 1; + if ($user->socid && !in_array('product', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + + dol_banner_tab($object, 'ref', $linkback, $shownav, 'ref'); + + print '
    '; + + print '
    '; + print ''; + + $nboflines = show_stats_for_company($product, $socid); + + print "
    "; + + print '
    '; + print '
    '; + + dol_fiche_end(); + + + $now = dol_now(); + + $sql = "SELECT"; + $sql .= ' sum('.$db->ifsql("cd.role='toconsume'", "cd.qty", 0).') as nb_toconsume,'; + $sql .= ' sum('.$db->ifsql("cd.role='consumed'", "cd.qty", 0).') as nb_consumed,'; + $sql .= ' sum('.$db->ifsql("cd.role='toproduce'", "cd.qty", 0).') as nb_toproduce,'; + $sql .= ' sum('.$db->ifsql("cd.role='produced'", "cd.qty", 0).') as nb_produced,'; + $sql .= " c.rowid as rowid, c.ref, c.date_valid, c.status"; + //$sql .= " s.nom as name, s.rowid as socid, s.code_client"; + $sql .= " FROM ".MAIN_DB_PREFIX."mrp_mo as c"; + $sql .= ", ".MAIN_DB_PREFIX."mrp_production as cd"; + $sql .= " WHERE c.rowid = cd.fk_mo"; + $sql .= " AND c.entity IN (".getEntity('mo').")"; + $sql .= " AND cd.fk_product =".$product->id; + if ($socid) $sql .= " AND s.rowid = ".$socid; + $sql .= " GROUP BY c.rowid, c.ref, c.date_valid, c.status"; + //$sql .= ", s.nom, s.rowid, s.code_client"; + $sql .= $db->order($sortfield, $sortorder); + + //Calcul total qty and amount for global if full scan list + $total_ht = 0; + $total_qty = 0; + + // Count total nb of records + $totalofrecords = ''; + if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) + { + $result = $db->query($sql); + $totalofrecords = $db->num_rows($result); + } + + $sql .= $db->plimit($limit + 1, $offset); + + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + if (!empty($id)) + $option .= '&id='.$product->id; + if (!empty($search_month)) + $option .= '&search_month='.urlencode($search_month); + if (!empty($search_year)) + $option .= '&search_year='.urlencode($search_year); + if ($limit > 0 && $limit != $conf->liste_limit) $option .= '&limit='.urlencode($limit); + + print ''."\n"; + if (!empty($sortfield)) + print ''; + if (!empty($sortorder)) + print ''; + if (!empty($page)) { + print ''; + $option .= '&page='.$page; + } + + print_barre_liste($langs->trans("Mos"), $page, $_SERVER["PHP_SELF"], "&id=".$product->id, $sortfield, $sortorder, '', $num, $totalofrecords, '', 0, '', '', $limit); + + $i = 0; + print '
    '; + print ''; + + print ''; + print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "c.rowid", "", "&id=".$product->id, '', $sortfield, $sortorder); + //print_liste_field_titre("Company", $_SERVER["PHP_SELF"], "s.nom", "", "&id=".$product->id, '', $sortfield, $sortorder); + print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "c.date_valid", "", "&id=".$product->id, 'align="center"', $sortfield, $sortorder); + //print_liste_field_titre("AmountHT"),$_SERVER["PHP_SELF"],"c.amount","","&id=".$product->id,'align="right"',$sortfield,$sortorder); + print_liste_field_titre("ToConsume", $_SERVER["PHP_SELF"], "", "", "&id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("QtyAlreadyConsumed", $_SERVER["PHP_SELF"], "", "", "&id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("QtyToProduce", $_SERVER["PHP_SELF"], "", "", "&id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("QtyAlreadyProduced", $_SERVER["PHP_SELF"], "", "", "&id=".$product->id, '', $sortfield, $sortorder, 'center '); + print "\n"; + + $motmp = new Mo($db); + + if ($num > 0) + { + while ($i < min($num, $limit)) + { + $objp = $db->fetch_object($result); + + $motmp->id = $objp->rowid; + $motmp->ref = $objp->ref; + + print ''; + print '\n"; + print ""; + //print "\n"; + //print ''; + print ''; + print ''; + print ''; + //$mostatic->LibStatut($objp->statut,5).''; + print "\n"; + $i++; + } + } + + print '
    '; + print $motmp->getNomUrl(1, 'production'); + print ""; + print dol_print_date($db->jdate($objp->date_valid), 'dayhour')."".price($objp->total_ht)."'; + print ''.($objp->nb_toconsume > 0 ? $objp->nb_toconsume : '').''.($objp->nb_consumed > 0 ? $objp->nb_consumed : '').''.($objp->nb_toproduce > 0 ? $objp->nb_toproduce : '').''.($objp->nb_produced > 0 ? $objp->nb_produced : '').'
    '; + print '
    '; + print ''; + } + else + { + dol_print_error($db); + } + $db->free($result); + } +} +else +{ + dol_print_error(); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/product/stats/propal.php b/htdocs/product/stats/propal.php index 17e9c37158c..d65b88ccabc 100644 --- a/htdocs/product/stats/propal.php +++ b/htdocs/product/stats/propal.php @@ -52,7 +52,7 @@ $mesg = ''; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -60,7 +60,7 @@ $pagenext = $page + 1; if (!$sortorder) $sortorder = "DESC"; if (!$sortfield) $sortfield = "p.datep"; -$search_month = GETPOST('search_month', 'aplha'); +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { diff --git a/htdocs/product/stats/supplier_proposal.php b/htdocs/product/stats/supplier_proposal.php index c344170e674..a7fede51aa1 100644 --- a/htdocs/product/stats/supplier_proposal.php +++ b/htdocs/product/stats/supplier_proposal.php @@ -52,7 +52,7 @@ $mesg = ''; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -60,7 +60,7 @@ $pagenext = $page + 1; if (!$sortorder) $sortorder = "DESC"; if (!$sortfield) $sortfield = "p.date_valid"; -$search_month = GETPOST('search_month', 'aplha'); +$search_month = GETPOST('search_month', 'alpha'); $search_year = GETPOST('search_year', 'int'); if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { diff --git a/htdocs/product/stock/card.php b/htdocs/product/stock/card.php index d0a1fc5db76..c025f0d08aa 100644 --- a/htdocs/product/stock/card.php +++ b/htdocs/product/stock/card.php @@ -105,6 +105,8 @@ if (empty($reshook)) $object->zip = GETPOST("zipcode"); $object->town = GETPOST("town"); $object->country_id = GETPOST("country_id"); + $object->phone = GETPOST("phone"); + $object->fax = GETPOST("fax"); if (!empty($object->libelle)) { @@ -174,6 +176,8 @@ if (empty($reshook)) $object->zip = GETPOST("zipcode"); $object->town = GETPOST("town"); $object->country_id = GETPOST("country_id"); + $object->phone = GETPOST("phone"); + $object->fax = GETPOST("fax"); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -292,6 +296,11 @@ if ($action == 'create') print $form->select_country((!empty($object->country_id) ? $object->country_id : $mysoc->country_code), 'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); print ''; + + // Phone / Fax + print ''.img_picto('', 'object_phoning').' '.$form->editfieldkey('Phone', 'phone', '', $object, 0).''; + print ''.img_picto('', 'object_phoning_fax').' '.$form->editfieldkey('Fax', 'fax', '', $object, 0).''; + // Status print ''.$langs->trans("Status").''; print ''; + print ''.img_picto('', 'object_phoning_fax').' '.$form->editfieldkey('Fax', 'fax', '', $object, 0).''; + // Status print ''.$langs->trans("Status").''; print ''; $moreforfilter.= '
    ';*/ @@ -337,17 +375,54 @@ print ''; -print ''; - -print ''; - -print ''; -print ''; -print ''; +if (!empty($arrayfields['e.ref']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.lieu']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.description']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.address']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.zip']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.town']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.phone']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['e.fax']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['stockqty']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['estimatedvalue']['checked'])) +{ + print ''; +} +if (!empty($arrayfields['sellvalue']['checked'])) +{ + print ''; +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -357,9 +432,12 @@ $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $obje print $hookmanager->resPrint; // Status -print ''; +if (!empty($arrayfields['e.statut']['checked'])) +{ + print ''; +} // Action column print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("LocationSummary", $_SERVER["PHP_SELF"], "e.lieu", "", $param, "", $sortfield, $sortorder); -print_liste_field_titre("PhysicalStock", $_SERVER["PHP_SELF"], "stockqty", '', $param, '', $sortfield, $sortorder, 'right '); -print_liste_field_titre("EstimatedStockValue", $_SERVER["PHP_SELF"], "estimatedvalue", '', $param, '', $sortfield, $sortorder, 'right '); -print_liste_field_titre("EstimatedStockValueSell", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'right '); + +if (!empty($arrayfields['e.ref']['checked'])) +{ + print_liste_field_titre($arrayfields['e.ref']['label'], $_SERVER["PHP_SELF"], "e.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.lieu']['checked'])) +{ + print_liste_field_titre($arrayfields['e.lieu']['label'], $_SERVER["PHP_SELF"], "e.lieu", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.description']['checked'])) +{ + print_liste_field_titre($arrayfields['e.description']['label'], $_SERVER["PHP_SELF"], "e.description", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.address']['checked'])) +{ + print_liste_field_titre($arrayfields['e.address']['label'], $_SERVER["PHP_SELF"], "e.address", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.zip']['checked'])) +{ + print_liste_field_titre($arrayfields['e.zip']['label'], $_SERVER["PHP_SELF"], "e.zip", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.town']['checked'])) +{ + print_liste_field_titre($arrayfields['e.town']['label'], $_SERVER["PHP_SELF"], "e.town", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.phone']['checked'])) +{ + print_liste_field_titre($arrayfields['e.phone']['label'], $_SERVER["PHP_SELF"], "e.phone", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['e.fax']['checked'])) +{ + print_liste_field_titre($arrayfields['e.fax']['label'], $_SERVER["PHP_SELF"], "e.fax", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['stockqty']['checked'])) +{ + print_liste_field_titre($arrayfields['stockqty']['label'], $_SERVER["PHP_SELF"], "stockqty", '', $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['estimatedvalue']['checked'])) +{ + print_liste_field_titre($arrayfields['estimatedvalue']['label'], $_SERVER["PHP_SELF"], "estimatedvalue", '', $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['sellvalue']['checked'])) +{ + print_liste_field_titre($arrayfields['sellvalue']['label'], $_SERVER["PHP_SELF"], "sellvalue", '', $param, '', $sortfield, $sortorder, 'right '); +} + // 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_liste_field_titre("Status", $_SERVER["PHP_SELF"], "e.statut", '', $param, '', $sortfield, $sortorder, 'right '); + +if (!empty($arrayfields['e.statut']['checked'])) +{ + print_liste_field_titre($arrayfields['e.statut']['label'], $_SERVER["PHP_SELF"], "e.statut", '', $param, '', $sortfield, $sortorder, 'right '); +} + // Action column print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print ''."\n"; @@ -410,33 +535,96 @@ if ($num) // Show here line of result print ''; - print ''; - if (!$i) $totalarray['nbfield']++; + + //print_r($arrayfields[]); + + // Label (ref) + if (!empty($arrayfields['e.ref']['checked'])) + { + print ''; + } + // Location - print ''; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['e.lieu']['checked'])) + { + print ''; + } + + // Description + if (!empty($arrayfields['e.description']['checked'])) + { + print ''; + } + + // Address + if (!empty($arrayfields['e.address']['checked'])) + { + print ''; + } + + // Zip + if (!empty($arrayfields['e.zip']['checked'])) + { + print ''; + } + + if (!empty($arrayfields['e.town']['checked'])) + { + print ''; + } + + // Phone + if (!empty($arrayfields['e.phone']['checked'])) + { + print ''; + } + + //Fax + if (!empty($arrayfields['e.fax']['checked'])) + { + print ''; + } // Stock qty - print ''; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['stockqty']['checked'])) + { + print ''; + } // PMP value - print ''; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['estimatedvalue']['checked'])) + { + print ''; + } // Selling value - print ''; } - print ''; - if (!$i) $totalarray['nbfield']++; // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; @@ -446,8 +634,10 @@ if ($num) print $hookmanager->resPrint; // Status - print ''; - if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['e.statut']['checked'])) + { + print ''; + } // Action column print ''; - print ''; - print ''; - print ''; - print ''; - print ''; + if (!empty($arrayfields['e.lieu']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.description']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.address']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.zip']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.town']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.phone']['checked'])) + { + $emptyColumn++; + } + if (!empty($arrayfields['e.fax']['checked'])) + { + $emptyColumn++; + } + + for ($i=0; $i < $emptyColumn; $i++) + { + print ''; + } + + print ''; + + if (!empty($arrayfields['stockqty']['checked'])) + { + print ''; + } + if (!empty($arrayfields['estimatedvalue']['checked'])) + { + print ''; + } + + if (!empty($arrayfields['sellvalue']['checked'])) + { + print ''; + } + + if (empty($extrafieldsobjectkey) && is_object($object)) $extrafieldsobjectkey = $object->table_element; + if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) + { + if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; + + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) + { + if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) + { + print ''; + } + } + } + + if (!empty($arrayfields['e.statut']['checked'])) + { + print ''; + } + print ''; print "\n"; } diff --git a/htdocs/product/stock/massstockmove.php b/htdocs/product/stock/massstockmove.php index 8d98f028d23..36db491629f 100644 --- a/htdocs/product/stock/massstockmove.php +++ b/htdocs/product/stock/massstockmove.php @@ -52,7 +52,7 @@ $idline = GETPOST('idline'); $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 if (!$sortfield) { diff --git a/htdocs/product/stock/movement_card.php b/htdocs/product/stock/movement_card.php index d1cb6a8dbde..c8567108d2d 100644 --- a/htdocs/product/stock/movement_card.php +++ b/htdocs/product/stock/movement_card.php @@ -72,7 +72,7 @@ $search_qty = trim(GETPOST("search_qty", 'alpha')); $search_type_mouvement = GETPOST('search_type_mouvement', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 @@ -99,7 +99,7 @@ $arrayfields = array( 'p.ref'=>array('label'=>$langs->trans("ProductRef"), 'checked'=>1, 'css'=>'maxwidth100'), 'p.label'=>array('label'=>$langs->trans("ProductLabel"), 'checked'=>1), 'm.batch'=>array('label'=>$langs->trans("BatchNumberShort"), 'checked'=>1, 'enabled'=>(!empty($conf->productbatch->enabled))), - 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'enabled'=>(!empty($conf->productbatch->enabled))), + 'pl.eatby'=>array('label'=>$langs->trans("EatByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), 'pl.sellby'=>array('label'=>$langs->trans("SellByDate"), 'checked'=>0, 'position'=>10, 'enabled'=>(!empty($conf->productbatch->enabled))), 'e.ref'=>array('label'=>$langs->trans("Warehouse"), 'checked'=>1, 'enabled'=>(!$id > 0)), // If we are on specific warehouse, we hide it 'm.fk_user_author'=>array('label'=>$langs->trans("Author"), 'checked'=>0), @@ -113,16 +113,16 @@ $arrayfields = array( //'m.tms'=>array('label'=>$langs->trans("DateModificationShort"), 'checked'=>0, 'position'=>500) ); +$usercanread = (($user->rights->stock->mouvement->lire)); +$usercancreate = (($user->rights->stock->mouvement->creer)); +$usercandelete = (($user->rights->stock->mouvement->supprimer)); + /* * Actions */ -$usercanread = (($user->rights->stock->mouvement->lire)); -$usercancreate = (($user->rights->stock->mouvement->creer)); -$usercandelete = (($user->rights->stock->mouvement->supprimer)); - if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } @@ -702,8 +702,6 @@ if ($resql) if ($search_product) $param .= '&search_product='.urlencode($search_product); if ($search_batch) $param .= '&search_batch='.urlencode($search_batch); if ($search_warehouse > 0) $param .= '&search_warehouse='.urlencode($search_warehouse); - if (!empty($sref)) $param .= '&sref='.urlencode($sref); // FIXME $sref is not defined - if (!empty($snom)) $param .= '&snom='.urlencode($snom); // FIXME $snom is not defined if ($search_user) $param .= '&search_user='.urlencode($search_user); if ($idproduct > 0) $param .= '&idproduct='.urlencode($idproduct); // Add $param from extra fields @@ -726,7 +724,6 @@ if ($resql) print ''; print ''; print ''; - print ''; print ''; if ($id > 0) print ''; @@ -956,7 +953,7 @@ if ($resql) $arrayofuniqueproduct = array(); - while ($i < min($num, $limit)) { + while ($i < ($limit ? min($num, $limit) : $num)) { $objp = $db->fetch_object($resql); $userstatic->id = $objp->fk_user_author; diff --git a/htdocs/product/stock/movement_list.php b/htdocs/product/stock/movement_list.php index dea7580aeb7..f89788167b9 100644 --- a/htdocs/product/stock/movement_list.php +++ b/htdocs/product/stock/movement_list.php @@ -54,8 +54,11 @@ $ref = GETPOST('ref', 'alpha'); $msid = GETPOST('msid', 'int'); $product_id = GETPOST("product_id", 'int'); $action = GETPOST('action', 'aZ09'); +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation $cancel = GETPOST('cancel', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'movementlist'; +$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list // Security check //$result=restrictedArea($user, 'stock', $id, 'entrepot&stock'); @@ -76,7 +79,7 @@ $search_qty = trim(GETPOST("search_qty")); $search_type_mouvement = GETPOST('search_type_mouvement', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 @@ -123,15 +126,19 @@ if (!$user->rights->stock->mouvement->lire) { accessforbidden(); } +$permissiontoread = $user->rights->stock->mouvement->lire; +$permissiontoadd = $user->rights->stock->mouvement->creer; +$permissiontodelete = $user->rights->stock->mouvement->creer; // There is no deletion permission for stock movement as we shoul dnever delete + +$usercanread = $user->rights->stock->mouvement->lire; +$usercancreate = $user->rights->stock->mouvement->creer; +$usercandelete = $user->rights->stock->mouvement->creer; + /* * Actions */ -$usercanread = (($user->rights->stock->mouvement->lire)); -$usercancreate = (($user->rights->stock->mouvement->creer)); -$usercandelete = (($user->rights->stock->mouvement->supprimer)); - if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } @@ -139,26 +146,35 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - -// Do we click on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers +if (empty($reshook)) { - $year = ''; - $month = ''; - $search_ref = ''; - $search_movement = ""; - $search_type_mouvement = ""; - $search_inventorycode = ""; - $search_product_ref = ""; - $search_product = ""; - $search_warehouse = ""; - $search_user = ""; - $search_batch = ""; - $search_qty = ''; - $sall = ""; - $toselect = ''; - $search_array_options = array(); + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Do we click on purge search criteria ? + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers + { + $year = ''; + $month = ''; + $search_ref = ''; + $search_movement = ""; + $search_type_mouvement = ""; + $search_inventorycode = ""; + $search_product_ref = ""; + $search_product = ""; + $search_warehouse = ""; + $search_user = ""; + $search_batch = ""; + $search_qty = ''; + $sall = ""; + $toselect = ''; + $search_array_options = array(); + } + + // Mass actions + $objectclass = 'MouvementStock'; + $objectlabel = 'MouvementStock'; + $uploaddir = $conf->stock->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } // Correct stock @@ -600,8 +616,8 @@ if ($resql) $resqlbis = $db->query($sql); if ($resqlbis) { - $obj = $db->fetch_object($resqlbis); - $lastmovementdate = $db->jdate($obj->datem); + $objbis = $db->fetch_object($resqlbis); + $lastmovementdate = $db->jdate($objbis->datem); } else { @@ -694,8 +710,9 @@ if ($resql) // 'presend'=>$langs->trans("SendByMail"), // 'builddoc'=>$langs->trans("PDFMerge"), ); - //if ($user->rights->stock->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + // By default, we should never accept deletion of stock movement. + if (! empty($conf->global->STOCK_ALLOW_DELETE_OF_MOVEMENT) && $permissiontodelete) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); + if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; @@ -713,6 +730,13 @@ if ($resql) if ($id > 0) print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); else print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'generic', 0, '', '', $limit); + // Add code for pre mass action (confirmation or email presend form) + $topicmail = "SendStockMovement"; + $modelmail = "movementstock"; + $objecttmp = new MouvementStock($db); + $trackid = 'mov'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + if ($sall) { foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); @@ -961,6 +985,8 @@ if ($resql) $arrayofuniqueproduct = array(); + $i = 0; + $totalarray = array(); while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); @@ -1126,8 +1152,8 @@ if ($resql) 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 ''; + if (in_array($objp->mid, $arrayofselected)) $selected = 1; + print ''; } print ''; if (!$i) $totalarray['nbfield']++; diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index c3eb7523e7d..17004a39a71 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php'; // Load translation files required by the page -$langs->loadLangs(array('stock', 'other', 'productbatch')); +$langs->loadLangs(array('stocks', 'other', 'productbatch')); // Get parameters $id = GETPOST('id', 'int'); diff --git a/htdocs/product/stock/productlot_document.php b/htdocs/product/stock/productlot_document.php index 5fb9cc23bca..95bf0b7f5c4 100644 --- a/htdocs/product/stock/productlot_document.php +++ b/htdocs/product/stock/productlot_document.php @@ -57,7 +57,7 @@ $hookmanager->initHooks(array('productlotdocuments')); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index 4b36fda5ccb..5eedc40f40c 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -57,7 +57,7 @@ $optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/product/stock/replenish.php b/htdocs/product/stock/replenish.php index 5164b72fa4a..d860640be81 100644 --- a/htdocs/product/stock/replenish.php +++ b/htdocs/product/stock/replenish.php @@ -66,7 +66,7 @@ $texte = ''; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; @@ -160,7 +160,7 @@ if ($action == 'order' && isset($_POST['valid'])) $desc = $productsupplier->description; } $line->desc = $desc; - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { // TODO Get desc in language of thirdparty } @@ -195,6 +195,7 @@ if ($action == 'order' && isset($_POST['valid'])) //we now know how many orders we need and what lines they have $i = 0; + $fail = 0; $orders = array(); $suppliersid = array_keys($suppliers); foreach ($suppliers as $supplier) @@ -311,6 +312,7 @@ if (!empty($conf->global->STOCK_ALLOW_ADD_LIMIT_STOCK_BY_WAREHOUSE) && $fk_entre $sql .= ' pse.desiredstock as desiredstockpse, pse.seuil_stock_alerte as seuil_stock_alertepse,'; } $sql .= ' '.$sqldesiredtock.' as desiredstockcombined, '.$sqlalertstock.' as seuil_stock_alertecombined,'; +$sql .= ' s.fk_product,'; $sql .= ' SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").') as stock_physique'; // Add fields from hooks @@ -319,8 +321,8 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= $hookmanager->resPrint; $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p'; -$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s'; -$sql .= ' ON (p.rowid = s.fk_product AND s.fk_entrepot IN (SELECT ent.rowid FROM '.MAIN_DB_PREFIX.'entrepot AS ent WHERE ent.entity IN('.getEntity('stock').')))'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as s ON p.rowid = s.fk_product'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'entrepot AS ent ON s.fk_entrepot = ent.rowid AND ent.entity IN('.getEntity('stock').')'; if ($fk_supplier > 0) { $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_fournisseur_price pfp ON (pfp.fk_product = p.rowid AND pfp.fk_soc = '.$fk_supplier.')'; } @@ -360,46 +362,84 @@ $sql .= ', s.fk_product'; if ($usevirtualstock) { - $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd.qty) IS NULL", "0", "SUM(cd.qty)")." as qty"; - $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd"; - $sqlCommandesCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; - $sqlCommandesCli .= " WHERE c.entity IN (".getEntity('commande').")"; - $sqlCommandesCli .= " AND cd.fk_product = p.rowid"; - $sqlCommandesCli .= " AND c.fk_statut IN (1,2))"; + if (!empty($conf->commande->enabled)) { + $sqlCommandesCli = "(SELECT ".$db->ifsql("SUM(cd1.qty) IS NULL", "0", "SUM(cd1.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlCommandesCli .= " FROM ".MAIN_DB_PREFIX."commandedet as cd1, ".MAIN_DB_PREFIX."commande as c1"; + $sqlCommandesCli .= " WHERE c1.rowid = cd1.fk_commande AND c1.entity IN (".getEntity('commande').")"; + $sqlCommandesCli .= " AND cd1.fk_product = p.rowid"; + $sqlCommandesCli .= " AND c1.fk_statut IN (1,2))"; + } else { + $sqlCommandesCli = '0'; + } - $sqlExpeditionsCli = "(SELECT ".$db->ifsql("SUM(ed.qty) IS NULL", "0", "SUM(ed.qty)")." as qty"; - $sqlExpeditionsCli .= " FROM ".MAIN_DB_PREFIX."expedition as e"; - $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."expeditiondet as ed ON (ed.fk_expedition = e.rowid)"; - $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commandedet as cd ON (cd.rowid = ed.fk_origin_line)"; - $sqlExpeditionsCli .= " LEFT JOIN ".MAIN_DB_PREFIX."commande as c ON (c.rowid = cd.fk_commande)"; - $sqlExpeditionsCli .= " WHERE e.entity IN (".getEntity('expedition').")"; - $sqlExpeditionsCli .= " AND cd.fk_product = p.rowid"; - $sqlExpeditionsCli .= " AND e.fk_statut IN (1,2))"; + if (!empty($conf->expedition->enabled)) { + $sqlExpeditionsCli = "(SELECT ".$db->ifsql("SUM(ed2.qty) IS NULL", "0", "SUM(ed2.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlExpeditionsCli .= " FROM ".MAIN_DB_PREFIX."expedition as e2,"; + $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."expeditiondet as ed2,"; + $sqlExpeditionsCli .= " ".MAIN_DB_PREFIX."commandedet as cd2"; + $sqlExpeditionsCli .= " WHERE ed2.fk_expedition = e2.rowid AND cd2.rowid = ed2.fk_origin_line AND e2.entity IN (".getEntity('expedition').")"; + $sqlExpeditionsCli .= " AND cd2.fk_product = p.rowid"; + $sqlExpeditionsCli .= " AND e2.fk_statut IN (1,2))"; + } else { + $sqlExpeditionsCli = '0'; + } - $sqlCommandesFourn = "(SELECT ".$db->ifsql("SUM(cd.qty) IS NULL", "0", "SUM(cd.qty)")." as qty"; - $sqlCommandesFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; - $sqlCommandesFourn .= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; - $sqlCommandesFourn .= " WHERE c.rowid = cd.fk_commande"; - $sqlCommandesFourn .= " AND c.entity IN (".getEntity('supplier_order').")"; - $sqlCommandesFourn .= " AND cd.fk_product = p.rowid"; - $sqlCommandesFourn .= " AND c.fk_statut IN (3,4))"; + if (!empty($conf->fournisseur->enabled)) { + $sqlCommandesFourn = "(SELECT ".$db->ifsql("SUM(cd3.qty) IS NULL", "0", "SUM(cd3.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlCommandesFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as cd3,"; + $sqlCommandesFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur as c3"; + $sqlCommandesFourn .= " WHERE c3.rowid = cd3.fk_commande"; + $sqlCommandesFourn .= " AND c3.entity IN (".getEntity('supplier_order').")"; + $sqlCommandesFourn .= " AND cd3.fk_product = p.rowid"; + $sqlCommandesFourn .= " AND c3.fk_statut IN (3,4))"; - $sqlReceptionFourn = "(SELECT ".$db->ifsql("SUM(fd.qty) IS NULL", "0", "SUM(fd.qty)")." as qty"; - $sqlReceptionFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; - $sqlReceptionFourn .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd ON (fd.fk_commande = cf.rowid)"; - $sqlReceptionFourn .= " WHERE cf.entity IN (".getEntity('supplier_order').")"; - $sqlReceptionFourn .= " AND fd.fk_product = p.rowid"; - $sqlReceptionFourn .= " AND cf.fk_statut IN (3,4))"; + $sqlReceptionFourn = "(SELECT ".$db->ifsql("SUM(fd4.qty) IS NULL", "0", "SUM(fd4.qty)")." as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlReceptionFourn .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf4,"; + $sqlReceptionFourn .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as fd4"; + $sqlReceptionFourn .= " WHERE fd4.fk_commande = cf4.rowid AND cf4.entity IN (".getEntity('supplier_order').")"; + $sqlReceptionFourn .= " AND fd4.fk_product = p.rowid"; + $sqlReceptionFourn .= " AND cf4.fk_statut IN (3,4))"; + } else { + $sqlCommandesFourn = '0'; + $sqlReceptionFourn = '0'; + } - $sql .= ' HAVING (('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; - $sql .= ' OR ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.'))))'; + if (!empty($conf->mrp->enabled)) { + $sqlProductionToConsume = "(SELECT GREATEST(0, ".$db->ifsql("SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').") IS NULL", "0", "SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').")").") as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlProductionToConsume .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,"; + $sqlProductionToConsume .= " ".MAIN_DB_PREFIX."mrp_production as mp5"; + $sqlProductionToConsume .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity('mo').")"; + $sqlProductionToConsume .= " AND mp5.fk_product = p.rowid"; + $sqlProductionToConsume .= " AND mp5.role IN ('toconsume', 'consummed')"; + $sqlProductionToConsume .= " AND mm5.status IN (1,2))"; + + $sqlProductionToProduce = "(SELECT GREATEST(0, ".$db->ifsql("SUM(".$db->ifsql("mp5.role = 'toproduce'", 'mp5.qty', '- mp5.qty').") IS NULL", "0", "SUM(".$db->ifsql("mp5.role = 'toconsume'", 'mp5.qty', '- mp5.qty').")").") as qty"; // We need the ifsql because if result is 0 for product p.rowid, we must return 0 and not NULL + $sqlProductionToProduce .= " FROM ".MAIN_DB_PREFIX."mrp_mo as mm5,"; + $sqlProductionToProduce .= " ".MAIN_DB_PREFIX."mrp_production as mp5"; + $sqlProductionToProduce .= " WHERE mm5.rowid = mp5.fk_mo AND mm5.entity IN (".getEntity('mo').")"; + $sqlProductionToProduce .= " AND mp5.fk_product = p.rowid"; + $sqlProductionToProduce .= " AND mp5.role IN ('toproduce', 'produced')"; + $sqlProductionToProduce .= " AND mm5.status IN (1,2))"; + } else + { + $sqlProductionToConsume = '0'; + $sqlProductionToProduce = '0'; + } + + $sql .= ' HAVING ('; + $sql .= ' ('.$sqldesiredtock.' >= 0 AND ('.$sqldesiredtock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.')))'; + $sql .= ' OR '; + $sql .= ' ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.')))'; + $sql .= ')'; if ($salert == 'on') // Option to see when stock is lower than alert { - $sql .= ' AND ('.$sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; - $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.')))'; + $sql .= ' AND ('; + $sql .= $sqlalertstock.' >= 0 AND ('.$sqlalertstock.' > SUM('.$db->ifsql("s.reel IS NULL", "0", "s.reel").')'; + $sql .= ' - ('.$sqlCommandesCli.' - '.$sqlExpeditionsCli.') + ('.$sqlCommandesFourn.' - '.$sqlReceptionFourn.') + ('.$sqlProductionToProduce.' - '.$sqlProductionToConsume.'))'; + $sql .= ')'; $alertchecked = 'checked'; } } else { diff --git a/htdocs/product/stock/replenishorders.php b/htdocs/product/stock/replenishorders.php index 5ca7debbef6..c1e1e157f79 100644 --- a/htdocs/product/stock/replenishorders.php +++ b/htdocs/product/stock/replenishorders.php @@ -46,7 +46,7 @@ $sref = GETPOST('search_ref', 'alpha'); $snom = GETPOST('search_nom', 'alpha'); $suser = GETPOST('search_user', 'alpha'); $sttc = GETPOST('search_ttc', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sproduct = GETPOST('sproduct', 'int'); $search_dateyear = GETPOST('search_dateyear', 'int'); $search_datemonth = GETPOST('search_datemonth', 'int'); diff --git a/htdocs/projet/card.php b/htdocs/projet/card.php index 77e83dfae96..a16b77b6667 100644 --- a/htdocs/projet/card.php +++ b/htdocs/projet/card.php @@ -263,12 +263,12 @@ if (empty($reshook)) $object->socid = GETPOST('socid', 'int'); $object->description = GETPOST('description', 'none'); // Do not use 'alpha' here, we want field as it is $object->public = GETPOST('public', 'alpha'); - $object->date_start = empty($_POST["projectstart"]) ? '' : $date_start; - $object->date_end = empty($_POST["projectend"]) ? '' : $date_end; - if (isset($_POST['opp_amount'])) $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); - if (isset($_POST['budget_amount'])) $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); - if (isset($_POST['opp_status'])) $object->opp_status = $opp_status; - if (isset($_POST['opp_percent'])) $object->opp_percent = $opp_percent; + $object->date_start = (!GETPOST('projectstart')) ? '' : $date_start; + $object->date_end = (!GETPOST('projectend')) ? '' : $date_end; + if (GETPOSTISSET('opp_amount')) $object->opp_amount = price2num(GETPOST('opp_amount', 'alpha')); + if (GETPOSTISSET('budget_amount')) $object->budget_amount = price2num(GETPOST('budget_amount', 'alpha')); + if (GETPOSTISSET('opp_status')) $object->opp_status = $opp_status; + if (GETPOSTISSET('opp_percent')) $object->opp_percent = $opp_percent; $object->usage_opportunity = (GETPOST('usage_opportunity', 'alpha') == 'on' ? 1 : 0); $object->usage_task = (GETPOST('usage_task', 'alpha') == 'on' ? 1 : 0); $object->usage_bill_time = (GETPOST('usage_bill_time', 'alpha') == 'on' ? 1 : 0); @@ -546,7 +546,7 @@ if ($action == 'create' && $user->rights->projet->creer) print ''; // Label - print ''; + print ''; // Usage (opp, task, bill time, ...) print ''; + + // Opportunity Weighted Amount + print ''; } // Date start - end diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 10e091e1244..54075318246 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -493,7 +493,7 @@ class Project extends CommonObject if (empty($id) && empty($ref)) return -1; $sql = "SELECT rowid, ref, title, description, public, datec, opp_amount, budget_amount,"; - $sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut, fk_opp_status, opp_percent,"; + $sql .= " tms, dateo, datee, date_close, fk_soc, fk_user_creat, fk_user_modif, fk_user_close, fk_statut as status, fk_opp_status, opp_percent,"; $sql .= " note_private, note_public, model_pdf, usage_opportunity, usage_task, usage_bill_time, usage_organize_event, entity"; $sql .= " FROM ".MAIN_DB_PREFIX."projet"; if (!empty($id)) @@ -534,7 +534,8 @@ class Project extends CommonObject $this->user_modification_id = $obj->fk_user_modif; $this->user_close_id = $obj->fk_user_close; $this->public = $obj->public; - $this->statut = $obj->fk_statut; + $this->statut = $obj->status; // deprecated + $this->status = $obj->status; $this->opp_status = $obj->fk_opp_status; $this->opp_amount = $obj->opp_amount; $this->opp_percent = $obj->opp_percent; @@ -700,7 +701,7 @@ class Project extends CommonObject 'propal'=>'fk_projet', 'commande'=>'fk_projet', 'facture'=>'fk_projet', 'supplier_proposal'=>'fk_projet', 'commande_fournisseur'=>'fk_projet', 'facture_fourn'=>'fk_projet', 'expensereport_det'=>'fk_projet', 'contrat'=>'fk_projet', 'fichinter'=>'fk_projet', 'don'=>'fk_projet', - 'actioncomm'=>'fk_project' + 'actioncomm'=>'fk_project', 'mo'=>'fk_project' ); foreach ($listoftables as $key => $value) { @@ -994,7 +995,7 @@ class Project extends CommonObject */ public function getLibStatut($mode = 0) { - return $this->LibStatut($this->statut, $mode); + return $this->LibStatut(isset($this->statut)?$this->statut:$this->status, $mode); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1055,6 +1056,9 @@ class Project extends CommonObject if (!empty($this->datee)) $label .= ($label ? '
    ' : '').''.$langs->trans('DateEnd').': '.dol_print_date($this->datee, 'day'); // The space must be after the : to not being explode when showing the title in img_picto if ($moreinpopup) $label .= '
    '.$moreinpopup; + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } $url = ''; if ($option != 'nolink') diff --git a/htdocs/projet/class/projectstats.class.php b/htdocs/projet/class/projectstats.class.php index 6f551d7ae2b..d7e5c86ffa6 100644 --- a/htdocs/projet/class/projectstats.class.php +++ b/htdocs/projet/class/projectstats.class.php @@ -76,7 +76,6 @@ class ProjectStats extends Stats $sql .= " GROUP BY t.fk_opp_status, cls.code, cls.label"; $result = array (); - $res = array (); dol_syslog(get_class($this) . '::' . __METHOD__ . "", LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/projet/contact.php b/htdocs/projet/contact.php index 42226f93208..6e4f19b2818 100644 --- a/htdocs/projet/contact.php +++ b/htdocs/projet/contact.php @@ -19,7 +19,7 @@ /** * \file htdocs/projet/contact.php * \ingroup project - * \brief Onglet de gestion des contacts du projet + * \brief List of all contacts of a project */ require '../main.inc.php'; @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +if ($conf->categorie->enabled) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; } // Load translation files required by the page $langs->loadLangs(array('projects', 'companies')); diff --git a/htdocs/projet/document.php b/htdocs/projet/document.php index f77419f2e75..1895270d758 100644 --- a/htdocs/projet/document.php +++ b/htdocs/projet/document.php @@ -57,7 +57,7 @@ if ($id > 0 || ! empty($ref)) { // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/projet/element.php b/htdocs/projet/element.php index b3e0303c7f4..f95c0b147b4 100644 --- a/htdocs/projet/element.php +++ b/htdocs/projet/element.php @@ -34,27 +34,28 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; -if (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -if (! empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; -if (! empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; -if (! empty($conf->supplier_proposal->enabled)) require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; -if (! empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; -if (! empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; -if (! empty($conf->ficheinter->enabled)) require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -if (! empty($conf->expedition->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; -if (! empty($conf->deplacement->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; -if (! empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; -if (! empty($conf->agenda->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; -if (! empty($conf->don->enabled)) require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; -if (! empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; -if (! empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; -if (! empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; -if (! empty($conf->tax->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; -if (! empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; -if (! empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; -if (! empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +if (!empty($conf->facture->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; +if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->supplier_proposal->enabled)) require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; +if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +if (!empty($conf->fournisseur->enabled)) require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; +if (!empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +if (!empty($conf->ficheinter->enabled)) require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; +if (!empty($conf->expedition->enabled)) require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; +if (!empty($conf->deplacement->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php'; +if (!empty($conf->expensereport->enabled)) require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; +if (!empty($conf->agenda->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +if (!empty($conf->don->enabled)) require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; +if (!empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php'; +if (!empty($conf->loan->enabled)) require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php'; +if (!empty($conf->stock->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; +if (!empty($conf->tax->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php'; +if (!empty($conf->salaries->enabled)) require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +if (!empty($conf->mrp->enabled)) require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php'; // Load translation files required by the page $langs->loadLangs(array('projects', 'companies', 'suppliers', 'compta')); @@ -67,6 +68,7 @@ if (!empty($conf->expensereport->enabled)) $langs->load("trips"); if (!empty($conf->don->enabled)) $langs->load("donations"); if (!empty($conf->loan->enabled)) $langs->load("loan"); if (!empty($conf->salaries->enabled)) $langs->load("salaries"); +if (!empty($conf->mrp->enabled)) $langs->load("mrp"); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -384,6 +386,18 @@ $listofreferent = array( 'buttonnew'=>'CreateShipment', 'testnew'=>0, 'test'=>$conf->expedition->enabled && $user->rights->expedition->lire), +'mrp'=>array( + 'name'=>"MO", + 'title'=>"ListMOAssociatedProject", + 'class'=>'Mo', + 'table'=>'mrp_mo', + 'datefieldname'=>'date_valid', + 'urlnew'=>DOL_URL_ROOT.'/mrp/mo_card.php?action=create&origin=project&originid='.$id.'&socid='.$socid, + 'lang'=>'mrp', + 'buttonnew'=>'CreateMO', + 'testnew'=>'$user->rights->mrp->write', + 'project_field'=>'fk_project', + 'test'=>$conf->mrp->enabled && $user->rights->mrp->read), 'trip'=>array( 'name'=>"TripsAndExpenses", 'title'=>"ListExpenseReportsAssociatedProject", @@ -606,7 +620,7 @@ foreach ($listofreferent as $key => $value) $elementarray = $object->get_element_list($key, $tablename, $datefieldname, $dates, $datee, !empty($project_field) ? $project_field : 'fk_projet'); - if (count($elementarray) > 0 && is_array($elementarray)) + if (is_array($elementarray) && count($elementarray) > 0) { $total_ht = 0; $total_ttc = 0; @@ -652,25 +666,25 @@ foreach ($listofreferent as $key => $value) $total_ht_by_line = price2num($tmp['amount'], 'MT'); } } - elseif ($key == 'loan'){ - if((empty($dates) && empty($datee)) || (intval($dates) <= $element->datestart && intval($datee) >= $element->dateend)){ + elseif ($key == 'loan') { + if ((empty($dates) && empty($datee)) || (intval($dates) <= $element->datestart && intval($datee) >= $element->dateend)) { // Get total loan $total_ht_by_line = -$element->capital; } - else{ + else { // Get loan schedule according to date filter $total_ht_by_line = 0; $loanScheduleStatic = new LoanSchedule($element->db); $loanScheduleStatic->fetchAll($element->id); - if(!empty($loanScheduleStatic->lines)){ - foreach($loanScheduleStatic->lines as $loanSchedule){ + if (!empty($loanScheduleStatic->lines)) { + foreach ($loanScheduleStatic->lines as $loanSchedule) { /** * @var $loanSchedule LoanSchedule */ - if( ($loanSchedule->datep >= $dates && $loanSchedule->datep <= $datee) // dates filter is defined + if (($loanSchedule->datep >= $dates && $loanSchedule->datep <= $datee) // dates filter is defined || !empty($dates) && empty($datee) && $loanSchedule->datep >= $dates && $loanSchedule->datep <= dol_now() || empty($dates) && !empty($datee) && $loanSchedule->datep <= $datee - ){ + ) { $total_ht_by_line = -$loanSchedule->amount_capital; } } @@ -688,7 +702,7 @@ foreach ($listofreferent as $key => $value) $defaultvat = get_default_tva($mysoc, $mysoc); $total_ttc_by_line = price2num($total_ht_by_line * (1 + ($defaultvat / 100)), 'MT'); } - elseif ($key == 'loan'){ + elseif ($key == 'loan') { $total_ttc_by_line = $total_ht_by_line; // For loan there is actually no taxe managed in Dolibarr } else $total_ttc_by_line = $element->total_ttc; @@ -829,7 +843,7 @@ foreach ($listofreferent as $key => $value) $addform .= '
    '; if ($testnew) $addform .= ''.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).''; elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { - $addform .= ''.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).''; + $addform .= ''.($buttonnew ? $langs->trans($buttonnew) : $langs->trans("Create")).''; } $addform .= '
    '; } @@ -968,7 +982,7 @@ foreach ($listofreferent as $key => $value) print $element->getNomUrl(1, 'withproject', 'time'); print ' - '.dol_trunc($element->label, 48); } - elseif ($key == 'loan'){ + elseif ($key == 'loan') { print $element->getNomUrl(1); print ' - '.dol_trunc($element->label, 48); } @@ -1015,13 +1029,16 @@ foreach ($listofreferent as $key => $value) elseif ($tablename == 'fichinter') $date = $element->datev; // There is no other date for this elseif ($tablename == 'projet_task') $date = ''; // We show no date. Showing date of beginning of task make user think it is date of time consumed else - { + { $date = $element->date; // invoice, ... if (empty($date)) $date = $element->date_contrat; if (empty($date)) $date = $element->datev; + if (empty($date) && !empty($datefieldname)) { + $date = $element->$datefieldname; + } } } - elseif ($key == 'loan'){ + elseif ($key == 'loan') { $date = $element->datestart; } diff --git a/htdocs/projet/graph_opportunities.inc.php b/htdocs/projet/graph_opportunities.inc.php index 72394c348fc..e535756ce0c 100644 --- a/htdocs/projet/graph_opportunities.inc.php +++ b/htdocs/projet/graph_opportunities.inc.php @@ -75,16 +75,16 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) } if ($conf->use_javascript_ajax) { - print '
    '; - print ''; } +if (!empty($arrayfields['opp_weighted_amount']['checked'])) +{ + print ''; +} if (!empty($arrayfields['p.budget_amount']['checked'])) { print '\n"; $i = 0; -$totalarray = array(); +$totalarray = array( + 'nbfield' => 0, + 'val' => array(), +); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -761,9 +771,7 @@ while ($i < min($num, $limit)) $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 3) // We print only number { - print ''; print $nbofsalesrepresentative; - print ''; } elseif ($nbofsalesrepresentative > 0) { @@ -837,19 +845,32 @@ while ($i < min($num, $limit)) $totalarray['val']['p.opp_amount'] += $obj->opp_amount; } print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='p.opp_amount'; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.opp_amount'; } // Opp percent - if (! empty($arrayfields['p.opp_percent']['checked'])) + if (!empty($arrayfields['p.opp_percent']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } + // Opp weighted amount + if (!empty($arrayfields['opp_weighted_amount']['checked'])) + { + if (!isset($totalarray['val']['opp_weighted_amount'])) $totalarray['val']['opp_weighted_amount'] = 0; + print ''; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'opp_weighted_amount'; + } // Budget - if (! empty($arrayfields['p.budget_amount']['checked'])) + if (!empty($arrayfields['p.budget_amount']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; - if (! $i) $totalarray['pos'][$totalarray['nbfield']]='p.budget_amount'; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'p.budget_amount'; } // Usage opportunity - if (! empty($arrayfields['p.usage_opportunity']['checked'])) + if (!empty($arrayfields['p.usage_opportunity']['checked'])) { print '
    '; -print ''; -print ''; -print ''; -print ''; + print ''; + print ''; + print ''; + print ''; -print $form->selectarray('search_status', $warehouse->statuts, $search_status, 1, 0, 0, '', 1); -print ''; + print $form->selectarray('search_status', $warehouse->statuts, $search_status, 1, 0, 0, '', 1); + print ''; @@ -371,18 +449,65 @@ print '
    '.$warehouse->getNomUrl(1).''.$warehouse->getNomUrl(1).''.$obj->lieu.''.$obj->lieu.''.$obj->description.''.$obj->address.''.$obj->zip.''.$obj->town.''.$obj->phone.''.$obj->fax.''.price2num($obj->stockqty, 5).''.price2num($obj->stockqty, 5).''; - if (price2num($obj->estimatedvalue, 'MT')) print price(price2num($obj->estimatedvalue, 'MT'), 1); - else print ''; - print ''; + + if (price2num($obj->estimatedvalue, 'MT')) + { + print price(price2num($obj->estimatedvalue, 'MT'), 1); + } + else + { + print ''; + } + + print ''; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($obj->sellvalue, 'MT'), 1); - else + if (!empty($arrayfields['sellvalue']['checked'])) { - $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); - print $form->textwithtooltip($langs->trans("Variable"), $htmltext); + print ''; + + if (empty($conf->global->PRODUIT_MULTIPRICES)) + { + print price(price2num($obj->sellvalue, 'MT'), 1); + } + else + { + $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); + print $form->textwithtooltip($langs->trans("Variable"), $htmltext); + } + + print ''.$warehouse->LibStatut($obj->statut, 5).''.$warehouse->LibStatut($obj->statut, 5).''; @@ -469,18 +659,89 @@ if ($num) if ($totalnboflines - $offset <= $limit) { print '
    '.$langs->trans("Total").''.price2num($totalStock, 5).''.price(price2num($total, 'MT'), 1, $langs, 0, 0, -1, $conf->currency).''; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($totalsell, 'MT'), 1, $langs, 0, 0, -1, $conf->currency); - else + + $emptyColumn = -1; + + if (!empty($arrayfields['e.ref']['checked'])) { - $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); - print $form->textwithtooltip($langs->trans("Variable"), $htmltext); + $emptyColumn++; } - print ''.$langs->trans("Total").''.price2num($totalStock, 5).''.price(price2num($total, 'MT'), 1, $langs, 0, 0, -1, $conf->currency).''; + if (empty($conf->global->PRODUIT_MULTIPRICES)) print price(price2num($totalsell, 'MT'), 1, $langs, 0, 0, -1, $conf->currency); + else + { + $htmltext = $langs->trans("OptionMULTIPRICESIsOn"); + print $form->textwithtooltip($langs->trans("Variable"), $htmltext); + } + print '
    '.$langs->trans("Label").'
    '.$langs->trans("Label").'
    '; @@ -786,7 +786,7 @@ elseif ($object->id > 0) array('type' => 'checkbox', 'name' => 'clone_task_files', 'label' => $langs->trans("CloneTaskFiles"), 'value' => false) ); - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CloneProject"), $langs->trans("ConfirmCloneProject"), "confirm_clone", $formquestion, '', 1, 300, 590); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ToClone"), $langs->trans("ConfirmCloneProject"), "confirm_clone", $formquestion, '', 1, 300, 590); } @@ -1048,6 +1048,11 @@ elseif ($object->id > 0) }*/ if (strcmp($object->opp_amount, '')) print price($object->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); print '
    '.$langs->trans('OpportunityWeightedAmount').''; + if (strcmp($object->opp_amount, '') && strcmp($object->opp_percent, '')) print price($object->opp_amount * $object->opp_percent / 100, 0, $langs, 1, 0, -1, $conf->currency); + print '
    '; + print '
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); - $dolgraph->SetHeight(180); + //$dolgraph->setWidth('100%'); + $dolgraph->SetHeight('200'); $dolgraph->draw('idgraphstatus'); print $dolgraph->show($totaloppnb ? 0 : 1); diff --git a/htdocs/projet/index.php b/htdocs/projet/index.php index 9ab79a3b677..ddb66bc3317 100644 --- a/htdocs/projet/index.php +++ b/htdocs/projet/index.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2016 Laurent Destailleur + * Copyright (C) 2004-2020 Laurent Destailleur * Copyright (C) 2005-2010 Regis Houssin * Copyright (C) 2019 Nicolas ZABOURI * @@ -166,14 +166,14 @@ include DOL_DOCUMENT_ROOT.'/projet/graph_opportunities.inc.php'; // List of draft projects -print_projecttasks_array($db, $form, $socid, $projectsListId, 0, 0, $listofoppstatus, array('projectlabel', 'plannedworkload', 'declaredprogress')); +print_projecttasks_array($db, $form, $socid, $projectsListId, 0, 0, $listofoppstatus, array('projectlabel', 'plannedworkload', 'declaredprogress', 'prospectionstatus', 'projectstatus')); print '
    '; // Latest modified projects -$sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut, p.tms as datem,"; -$sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.canvas"; +$sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut as status, p.tms as datem,"; +$sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.canvas, s.status as thirdpartystatus"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; @@ -200,7 +200,7 @@ if ($resql) $obj = $db->fetch_object($resql); print '
    '; + print ''; $projectstatic->id = $obj->rowid; $projectstatic->ref = $obj->ref; @@ -208,6 +208,7 @@ if ($resql) $projectstatic->dateo = $obj->dateo; $projectstatic->datep = $obj->datep; $projectstatic->thirdparty_name = $obj->name; + $projectstatic->status = $obj->status; $companystatic->id = $obj->socid; $companystatic->name = $obj->name; @@ -217,6 +218,7 @@ if ($resql) $companystatic->code_client = $obj->code_client; $companystatic->code_fournisseur = $obj->code_fournisseur; $companystatic->canvas = $obj->canvas; + $companystatic->status = $obj->thirdpartystatus; print ''; print ''; print ''; - print ''; + print ''; print ''; $i++; } @@ -265,37 +267,49 @@ print_liste_field_titre("NbOfProjects", "", "", "", "", '', $sortfield, $sortord print "\n"; $sql = "SELECT COUNT(p.rowid) as nb, SUM(p.opp_amount)"; -$sql .= ", s.nom as name, s.rowid as socid"; +$sql .= ", s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.canvas, s.status"; $sql .= " FROM ".MAIN_DB_PREFIX."projet as p"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on p.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.fk_statut = 1"; if ($mine || empty($user->rights->projet->all->lire)) $sql .= " AND p.rowid IN (".$projectsListId.")"; // If we have this test true, it also means projectset is not 2 if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; -$sql .= " GROUP BY s.nom, s.rowid"; +$sql .= " GROUP BY s.rowid, s.nom, s.email, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.canvas, s.status"; $sql .= $db->order($sortfield, $sortorder); +//$sql .= $db->plimit($max + 1, 0); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; + $othernb = 0; while ($i < $num) { $obj = $db->fetch_object($resql); + if ($i >= $max) { + $othernb += $obj->nb; + $i++; + continue; + } + print ''; print ''; print ''; + print ''; + print ''; + print "\n"; + } $db->free($resql); } @@ -316,10 +340,10 @@ else print "
    '; @@ -243,7 +245,7 @@ if ($resql) } print ''.dol_print_date($db->jdate($obj->datem), 'day').''.$projectstatic->LibStatut($obj->fk_statut, 3).''.$projectstatic->LibStatut($obj->status, 3).'
    '; if ($obj->socid) { $companystatic->id = $obj->socid; $companystatic->name = $obj->name; + $companystatic->email = $obj->email; + $companystatic->status = $obj->status; + print $companystatic->getNomUrl(1); } else { print $langs->trans("OthersNotLinkedToThirdParty"); + $i--; } print ''; @@ -306,6 +320,16 @@ if ($resql) $i++; } + if ($othernb) { + print '
    '; + print '...'; + print ''; + print $othernb; + print '
    "; print ''; -if (!empty($conf->global->PROJECT_SHOW_PROJECT_LIST_ON_PROJECT_AREA)) +if (empty($conf->global->PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA)) { - // This list can be very long, so we don't show it by default on task area. We prefer to use the list page. - // Add constant PROJECT_SHOW_PROJECT_LIST_ON_PROJECT_AREA to show this list + // This list can be very long, so we allow to hide it to prefer to use the list page. + // Add constant PROJECT_HIDE_PROJECT_LIST_ON_PROJECT_AREA to show this list print '
    '; @@ -329,7 +353,7 @@ if (!empty($conf->global->PROJECT_SHOW_PROJECT_LIST_ON_PROJECT_AREA)) print ''; $parameters = array('user' => $user); -$reshook = $hookmanager->executeHooks('dashboardProjects', $parameters, $object); // Note that $action and $object may have been modified by hook +$reshook = $hookmanager->executeHooks('dashboardProjects', $parameters, $projectstatic); // Note that $action and $object may have been modified by hook // End of page llxFooter(); diff --git a/htdocs/projet/info.php b/htdocs/projet/info.php index ddb7673dece..0058a5a94dd 100644 --- a/htdocs/projet/info.php +++ b/htdocs/projet/info.php @@ -39,7 +39,7 @@ $action = GETPOST('action', 'aZ09'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", "alpha"); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; if (!$sortfield) $sortfield = "a.datep,a.id"; diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index ef09ade1b91..e04875294bf 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -62,7 +62,7 @@ $diroutputmassaction = $conf->projet->dir_output.'/temp/massgeneration/'.$user-> $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", "alpha"); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $page = is_numeric($page) ? $page : 0; $page = $page == -1 ? 0 : $page; if (!$sortfield) $sortfield = "p.ref"; @@ -131,7 +131,8 @@ $arrayfields = array( 'p.opp_amount'=>array('label'=>$langs->trans("OpportunityAmountShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES ? 1 : 0), 'position'=>103), 'p.fk_opp_status'=>array('label'=>$langs->trans("OpportunityStatusShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES ? 1 : 0), 'position'=>104), 'p.opp_percent'=>array('label'=>$langs->trans("OpportunityProbabilityShort"), 'checked'=>1, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES ? 1 : 0), 'position'=>105), - 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), + 'opp_weighted_amount'=>array('label'=>$langs->trans('OpportunityWeightedAmountShort'), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES ? 1 : 0), 'position'=>106), + 'p.budget_amount'=>array('label'=>$langs->trans("Budget"), 'checked'=>0, 'position'=>110), 'p.usage_opportunity'=>array('label'=>$langs->trans("UsageOpportunity"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_USE_OPPORTUNITIES ? 1 : 0), 'position'=>115), 'p.usage_task'=>array('label'=>$langs->trans("UsageTasks"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_HIDE_TASKS ? 0 : 1), 'position'=>116), 'p.usage_bill_time'=>array('label'=>$langs->trans("UsageBillTimeShort"), 'checked'=>0, 'enabled'=>($conf->global->PROJECT_HIDE_TASKS ? 0 : 1), 'position'=>117), @@ -289,7 +290,7 @@ if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0] = '0'; / $distinct = 'DISTINCT'; // We add distinct until we are added a protection to be sure a contact of a project and task is only once. $sql = "SELECT ".$distinct." p.rowid as id, p.ref, p.title, p.fk_statut, p.fk_opp_status, p.public, p.fk_user_creat"; -$sql .= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount, p.usage_opportunity, p.usage_task, p.usage_bill_time"; +$sql .= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, (p.opp_amount*p.opp_percent/100) as opp_weighted_amount, p.tms as date_update, p.budget_amount, p.usage_opportunity, p.usage_task, p.usage_bill_time"; $sql .= ", s.rowid as socid, s.nom as name, s.email"; $sql .= ", cls.code as opp_status_code"; // We'll need these fields in order to filter by categ @@ -604,6 +605,11 @@ if (!empty($arrayfields['p.opp_percent']['checked'])) print ''; print '
    '; + print ''; @@ -676,7 +682,8 @@ if (!empty($arrayfields['p.datee']['checked'])) print_liste_field_titre( if (!empty($arrayfields['p.public']['checked'])) print_liste_field_titre($arrayfields['p.public']['label'], $_SERVER["PHP_SELF"], "p.public", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER['PHP_SELF'], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['opp_weighted_amount']['checked'])) print_liste_field_titre($arrayfields['opp_weighted_amount']['label'], $_SERVER['PHP_SELF'], 'opp_weighted_amount', '', $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['p.usage_opportunity']['checked'])) print_liste_field_titre($arrayfields['p.usage_opportunity']['label'], $_SERVER["PHP_SELF"], 'p.usage_opportunity', "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['p.usage_task']['checked'])) print_liste_field_titre($arrayfields['p.usage_task']['label'], $_SERVER["PHP_SELF"], 'p.usage_task', "", $param, '', $sortfield, $sortorder, 'right '); @@ -694,7 +701,10 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $ print "
    '; if ($obj->opp_percent) print price($obj->opp_percent, 1, $langs, 1, 0).'%'; print ''; + if ($obj->opp_weighted_amount) { + print price($obj->opp_weighted_amount, 1, $langs, 1, -1, -1, ''); + $totalarray['val']['opp_weighted_amount'] += $obj->opp_weighted_amount; + } + print ''; if ($obj->budget_amount != '') @@ -858,11 +879,11 @@ while ($i < min($num, $limit)) $totalarray['val']['p.budget_amount'] += $obj->budget_amount; } print ''; if ($obj->usage_opportunity) diff --git a/htdocs/projet/stats/index.php b/htdocs/projet/stats/index.php index 38fa476fcab..38d12081b4f 100644 --- a/htdocs/projet/stats/index.php +++ b/htdocs/projet/stats/index.php @@ -77,11 +77,12 @@ if (!empty($userid) && $userid != -1) $stats_project->userid = $userid; if (!empty($socid) && $socid != -1) $stats_project->socid = $socid; if (!empty($year)) $stats_project->year = $year; - - +/* if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + // Current stats of project amount per status $data1 = $stats_project->getAllProjectByStatus(); + if (!is_array($data1) && $data1 < 0) { setEventMessages($stats_project->error, null, 'errors'); } @@ -100,43 +101,42 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $i = 0; $tot = count($data1); $legend = array(); while ($i <= $tot) { - $data1[$i][0] = $data1[$i][0]; // Required to avoid error "Could not draw pie with labels contained inside canvas" $legend[] = $data1[$i][0]; $i++; } + $px->SetData($data1); unset($data1); if ($nocolor) - $px->SetDataColor(array( + $px->SetDataColor(array( array( 220, 220, 220 ) )); - $px->SetLegend($legend); - $px->setShowLegend(0); - $px->setShowPointValue($showpointvalue); - $px->setShowPercent(1); - $px->SetMaxValue($px->GetCeilMaxValue()); - $px->SetWidth($WIDTH); - $px->SetHeight($HEIGHT); - $px->SetShading(3); - $px->SetHorizTickIncrement(1); - $px->SetCssPrefix("cssboxes"); - $px->SetType(array( - 'pie' - )); - $px->SetTitle($langs->trans('OpportunitiesStatusForProjects')); - $result = $px->draw($filenamenb, $fileurlnb); + + $px->SetLegend($legend); + $px->setShowLegend(0); + $px->setShowPointValue($showpointvalue); + $px->setShowPercent(1); + $px->SetMaxValue($px->GetCeilMaxValue()); + $px->SetWidth($WIDTH); + $px->SetHeight($HEIGHT); + $px->SetShading(3); + $px->SetHorizTickIncrement(1); + $px->SetCssPrefix("cssboxes"); + $px->SetType(array('pie')); + $px->SetTitle($langs->trans('OpportunitiesStatusForProjects')); + $result = $px->draw($filenamenb, $fileurlnb); if ($result < 0) { setEventMessages($px->error, null, 'errors'); } } else { - setEventMessages(null, $mesgs, 'errors'); + setEventMessages(null, $mesg, 'errors'); } -} +}*/ // Build graphic number of object @@ -186,13 +186,14 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $mesg = $px2->isGraphKo(); if (!$mesg) { - $px2->SetData($data); $i = $startyear; $legend = array(); while ($i <= $endyear) { $legend[] = $i; $i++; } + + $px2->SetData($data); $px2->SetLegend($legend); $px2->SetMaxValue($px2->GetCeilMaxValue()); $px2->SetMinValue(min(0, $px2->GetFloorMinValue())); @@ -201,6 +202,7 @@ if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) $px2->SetYLabel($langs->trans("ProjectOppAmountOfProjectsByMonth")); $px2->SetShading(3); $px2->SetHorizTickIncrement(1); + $px2->SetType(array('bars', 'bars')); $px2->mode = 'depth'; $px2->SetTitle($langs->trans("ProjectOppAmountOfProjectsByMonth")); @@ -272,6 +274,7 @@ dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1, ''); print '
    '; print ''; +print ''; print ''; print ''; @@ -353,8 +356,8 @@ else { $stringtoshow .= "
    \n"; if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { - $stringtoshow .= $px->show(); - $stringtoshow .= "
    \n"; + //$stringtoshow .= $px->show(); + //$stringtoshow .= "
    \n"; $stringtoshow .= $px2->show(); $stringtoshow .= "
    \n"; $stringtoshow .= $px3->show(); diff --git a/htdocs/projet/tasks/document.php b/htdocs/projet/tasks/document.php index 133b3d3d509..4dd06b10cd2 100644 --- a/htdocs/projet/tasks/document.php +++ b/htdocs/projet/tasks/document.php @@ -53,7 +53,7 @@ if (!$user->rights->projet->lire) accessforbidden(); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index 3fd85f4082e..09135733e9e 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -91,7 +91,7 @@ $diroutputmassaction = $conf->projet->dir_output.'/tasks/temp/massgeneration/'.$ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/projet/tasks/stats/index.php b/htdocs/projet/tasks/stats/index.php index dafd5ae0071..c758664d2c6 100644 --- a/htdocs/projet/tasks/stats/index.php +++ b/htdocs/projet/tasks/stats/index.php @@ -139,6 +139,7 @@ dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1, ''); print '
    '; print ''; +print ''; print '
    '.$langs->trans("Filter").'
    '; print ''; diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index 291ab4ab949..637ed3a6644 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -75,7 +75,7 @@ if (!$user->rights->projet->lire) accessforbidden(); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/public/error-401.php b/htdocs/public/error-401.php index d6a6ed548ff..87da7c347e3 100644 --- a/htdocs/public/error-401.php +++ b/htdocs/public/error-401.php @@ -21,7 +21,7 @@ Sorry. You are not allowed to access this resource.
    - +
    diff --git a/htdocs/public/error-404.php b/htdocs/public/error-404.php index 36547d26704..baaa26cd833 100644 --- a/htdocs/public/error-404.php +++ b/htdocs/public/error-404.php @@ -21,7 +21,7 @@ You requested a website or a page that does not exists.
    - +
    diff --git a/htdocs/public/members/public_list.php b/htdocs/public/members/public_list.php index 560d7dbd0a9..1dfe694f154 100644 --- a/htdocs/public/members/public_list.php +++ b/htdocs/public/members/public_list.php @@ -80,7 +80,7 @@ function llxFooterVierge() $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/public/opensurvey/studs.php b/htdocs/public/opensurvey/studs.php index ab011dd219a..c9697e2e1e4 100644 --- a/htdocs/public/opensurvey/studs.php +++ b/htdocs/public/opensurvey/studs.php @@ -250,7 +250,8 @@ $form = new Form($db); $arrayofjs = array(); $arrayofcss = array('/opensurvey/css/style.css'); -llxHeaderSurvey($object->titre, "", 0, 0, $arrayofjs, $arrayofcss); + +llxHeaderSurvey($object->titre, "", 0, 0, $arrayofjs, $arrayofcss, $numsondage); if (empty($object->ref)) // For survey, id is a hex string { @@ -274,6 +275,7 @@ foreach ($toutsujet as $value) $toutsujet = str_replace("°", "'", $toutsujet); + print '
    '.$langs->trans("YouAreInivitedToVote").'
    '; print $langs->trans("OpenSurveyHowTo").'

    '; @@ -301,9 +303,6 @@ if (!$canbemodified) { exit; } -print ''."\n"; -print ''; - print '
    '."\n"; print '

    '."\n"; diff --git a/htdocs/public/payment/newpayment.php b/htdocs/public/payment/newpayment.php index 3810f18dea3..00f19d248cf 100644 --- a/htdocs/public/payment/newpayment.php +++ b/htdocs/public/payment/newpayment.php @@ -195,7 +195,7 @@ if ((empty($paymentmethod) || $paymentmethod == 'paybox') && ! empty($conf->payb } if ((empty($paymentmethod) || $paymentmethod == 'stripe') && ! empty($conf->stripe->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This include also /stripe/lib/stripe.lib.php, /includes/stripe/init.php, ... + require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This include also /stripe/lib/stripe.lib.php, /includes/stripe/stripe-php/init.php, ... } // Initialize $validpaymentmethod @@ -665,9 +665,9 @@ if ($action == 'charge' && !empty($conf->stripe->enabled)) if ($paymentintent->status != 'succeeded') { $error++; - $errormessage = "StatusOfRetreivedIntent is not succeeded: ".$e->getMessage(); + $errormessage = "StatusOfRetreivedIntent is not succeeded: ".$paymentintent->status; dol_syslog($errormessage, LOG_WARNING, 0, '_stripe'); - setEventMessages($e->getMessage(), null, 'errors'); + setEventMessages($paymentintent->status, null, 'errors'); $action = ''; } else @@ -1719,7 +1719,6 @@ if ($action != 'dopayment') if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { - // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of paybox print '
    '; print '
    '; print ''.$langs->trans("CreditOrDebitCard").''; @@ -1740,7 +1739,6 @@ if ($action != 'dopayment') if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { - // If STRIPE_PICTO_FOR_PAYMENT is 'cb' we show a picto of a crdit card instead of stripe print '
    '; print ''; print '
    '; diff --git a/htdocs/public/payment/paymentko.php b/htdocs/public/payment/paymentko.php index 2c8b23396c7..eac2fdf9f47 100644 --- a/htdocs/public/payment/paymentko.php +++ b/htdocs/public/payment/paymentko.php @@ -68,6 +68,7 @@ $suffix = GETPOST("suffix", 'aZ09'); // Detect $paymentmethod $paymentmethod = ''; +$reg = array(); if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) { $paymentmethod = $reg[1]; @@ -203,14 +204,14 @@ if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head = 'dol_hide_leftmenu) ? '
    ' : '').'
    '; +llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea); // Show ko message print ''."\n"; print '
    '."\n"; - // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) $width = 0; // Define logo and logosmall @@ -222,25 +223,39 @@ elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global-> //print ''."\n"; // Define urllogo $urllogo = ''; +$urllogofull = ''; if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { - $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('logos/thumbs/'.$logosmall); + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); $width = 150; } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { - $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('logos/'.$logo); + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); $width = 150; } + // Output html code for logo if ($urllogo) { - print '
    '; + print '
    '; + print '
    '; - print '
    '; + print '>'; + print '
    '; + if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { + print ''; + } + print '
    '; } + +print '

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

    "; $key = 'ONLINE_PAYMENT_MESSAGE_KO'; diff --git a/htdocs/public/payment/paymentok.php b/htdocs/public/payment/paymentok.php index 4661067b78e..28060a6d71e 100644 --- a/htdocs/public/payment/paymentok.php +++ b/htdocs/public/payment/paymentok.php @@ -78,6 +78,7 @@ $suffix=GETPOST("suffix", 'aZ09'); // Detect $paymentmethod $paymentmethod=''; +$reg = array(); if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) { $paymentmethod=$reg[1]; @@ -136,45 +137,59 @@ if (! empty($conf->global->ONLINE_PAYMENT_CSS_URL)) $head='dol_hide_leftmenu) ? '
    ' : '').'
    '; +llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea); // Show message print ''."\n"; -print '
    '."\n"; +print '
    '."\n"; // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo) -$width=0; +$width = 0; // Define logo and logosmall -$logosmall=$mysoc->logo_small; -$logo=$mysoc->logo; -$paramlogo='ONLINE_PAYMENT_LOGO_'.$suffix; -if (! empty($conf->global->$paramlogo)) $logosmall=$conf->global->$paramlogo; -elseif (! empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall=$conf->global->ONLINE_PAYMENT_LOGO; +$logosmall = $mysoc->logo_small; +$logo = $mysoc->logo; +$paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix; +if (!empty($conf->global->$paramlogo)) $logosmall = $conf->global->$paramlogo; +elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) $logosmall = $conf->global->ONLINE_PAYMENT_LOGO; //print ''."\n"; // Define urllogo -$urllogo=''; -if (! empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) +$urllogo = ''; +$urllogofull = ''; +if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('logos/thumbs/'.$logosmall); - $width=150; + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall); + $width = 150; } -elseif (! empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) +elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) { - $urllogo=DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&file='.urlencode('logos/'.$logo); - $width=150; + $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo); + $width = 150; } + // Output html code for logo if ($urllogo) { - print '
    '; + print '
    '; + print '
    '; - print '
    '; + print '>'; + print '
    '; + if (empty($conf->global->MAIN_HIDE_POWERED_BY)) { + print ''; + } + print '
    '; } +print '

    '; + + if (! empty($conf->paypal->enabled)) { if ($paymentmethod == 'paypal') // We call this page only if payment is ok on payment system @@ -643,6 +658,7 @@ if ($ispaymentok) } $paiement->paiementid = $paymentTypeId; $paiement->num_paiement = ''; + $paiement->num_payment = ''; $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress; $paiement->ext_payment_id = $TRANSACTIONID; $paiement->ext_payment_site = $service; diff --git a/htdocs/public/stripe/confirm_payment.php b/htdocs/public/stripe/confirm_payment.php index 51c2a1bf9a5..7e7dd12fcff 100644 --- a/htdocs/public/stripe/confirm_payment.php +++ b/htdocs/public/stripe/confirm_payment.php @@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; if (empty($conf->stripe->enabled)) accessforbidden('', 0, 0, 1); diff --git a/htdocs/public/stripe/ipn.php b/htdocs/public/stripe/ipn.php index f634d49ebac..219ad7e487d 100644 --- a/htdocs/public/stripe/ipn.php +++ b/htdocs/public/stripe/ipn.php @@ -33,7 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; -require_once DOL_DOCUMENT_ROOT.'/includes/stripe/init.php'; +require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php'; require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; diff --git a/htdocs/public/ticket/create_ticket.php b/htdocs/public/ticket/create_ticket.php index b3e94d5ceb2..16978e06ee2 100644 --- a/htdocs/public/ticket/create_ticket.php +++ b/htdocs/public/ticket/create_ticket.php @@ -68,11 +68,12 @@ if (GETPOST('addfile', 'alpha') && !GETPOST('add', 'alpha')) { // Set tmp directory TODO Use a dedicated directory for temp mails files $vardir = $conf->ticket->dir_output; - $upload_dir_tmp = $vardir.'/temp'; + $upload_dir_tmp = $vardir.'/temp/'.session_id(); if (!dol_is_dir($upload_dir_tmp)) { dol_mkdir($upload_dir_tmp); } - dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile'); + + dol_add_file_process($upload_dir_tmp, 0, 0, 'addedfile', '', null, '', 0); $action = 'create_ticket'; ////} } @@ -83,7 +84,7 @@ if (GETPOST('removedfile', 'alpha') && !GETPOST('add', 'alpha')) { // Set tmp directory $vardir = $conf->ticket->dir_output.'/'; - $upload_dir_tmp = $vardir.'/temp'; + $upload_dir_tmp = $vardir.'/temp/'.session_id(); // TODO Delete only files that was uploaded from email form dol_remove_file_process($_POST['removedfile'], 0, 0); @@ -170,7 +171,7 @@ if ($action == 'create_ticket' && GETPOST('add', 'alpha')) { if (!$error && $id > 0) { if ($usertoassign > 0) { - $object->add_contact($usertoassign, "SUPPORTCLI", 'external', $notrigger = 0); + $object->add_contact($usertoassign, "SUPPORTCLI", 'external', 0); } } @@ -205,7 +206,7 @@ if ($action == 'create_ticket' && GETPOST('add', 'alpha')) { // Send email to customer - $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubject', $object->ref); + $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubject', $object->ref, $object->track_id); $message .= ($conf->global->TICKET_MESSAGE_MAIL_NEW ? $conf->global->TICKET_MESSAGE_MAIL_NEW : $langs->transnoentities('TicketNewEmailBody'))."\n\n"; $message .= $langs->transnoentities('TicketNewEmailBodyInfosTicket')."\n"; @@ -247,7 +248,7 @@ if ($action == 'create_ticket' && GETPOST('add', 'alpha')) { if ($sendto) { - $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubjectAdmin', $object->ref); + $subject = '['.$conf->global->MAIN_INFO_SOCIETE_NOM.'] '.$langs->transnoentities('TicketNewEmailSubjectAdmin', $object->ref, $object->track_id); $message_admin = $langs->transnoentities('TicketNewEmailBodyAdmin', $object->track_id)."\n\n"; $message_admin .= '
    • '.$langs->trans('Title').' : '.$object->subject.'
    • '; $message_admin .= '
    • '.$langs->trans('Type').' : '.$object->type_label.'
    • '; @@ -304,7 +305,7 @@ if ($action == 'create_ticket' && GETPOST('add', 'alpha')) { } // Copy files into ticket directory - $destdir = $conf->ticket->dir_output.'/'.$object->track_id; + $destdir = $conf->ticket->dir_output.'/'.$object->ref; if (!dol_is_dir($destdir)) { dol_mkdir($destdir); } diff --git a/htdocs/public/ticket/list.php b/htdocs/public/ticket/list.php index edb89257e3e..4b3d181517d 100644 --- a/htdocs/public/ticket/list.php +++ b/htdocs/public/ticket/list.php @@ -292,7 +292,7 @@ if ($action == "view_ticketlist") $limit = $conf->liste_limit; - $page = GETPOST("page", 'int'); + $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/public/ticket/view.php b/htdocs/public/ticket/view.php index 8f6d84059a5..04331f30f80 100644 --- a/htdocs/public/ticket/view.php +++ b/htdocs/public/ticket/view.php @@ -234,9 +234,9 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a print $form->formconfirm($_SERVER["PHP_SELF"]."?track_id=".$track_id, $langs->trans("CloseATicket"), $langs->trans("ConfirmCloseAticket"), "confirm_public_close", '', '', 1); } - print '
      '; + print '
      '; - print '
    '.$langs->trans("Filter").'
    '; + print '
    '; // Ref print ''.$line->product_label.''; } } + if ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { + $invoice->fetch($placeid); //Reload object before send to printer + $ret = $printer->sendToPrinter($invoice, $conf->global->{'TAKEPOS_TEMPLATE_TO_USE_FOR_ORDERS'.$_SESSION["takeposterminal"]}, $conf->global->{'TAKEPOS_PRINTER_TO_USE'.$_SESSION["takeposterminal"]}); // PRINT TO PRINTER 1 + } + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='1' and fk_facture=".$invoice->id; // Set as printed + $db->query($sql); + $invoice->fetch($placeid); //Reload object after set lines as printed foreach ($invoice->lines as $line) { @@ -476,15 +542,20 @@ if ($action == "order" and $placeid != 0) $result = array_intersect($catsprinter2, $existing); $count = count($result); if ($count > 0) { - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where rowid=".$line->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='2' where rowid=".$line->id; //Set to print on printer 2 $db->query($sql); $order_receipt_printer2 .= ''.$line->product_label.''; } } - - $invoice->fetch($placeid); + if ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { + $invoice->fetch($placeid); //Reload object before send to printer + $ret = $printer->sendToPrinter($invoice, $conf->global->{'TAKEPOS_TEMPLATE_TO_USE_FOR_ORDERS'.$_SESSION["takeposterminal"]}, $conf->global->{'TAKEPOS_PRINTER_TO_USE'.$_SESSION["takeposterminal"]}); // PRINT TO PRINTER 2 + } + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where special_code='2' and fk_facture=".$invoice->id; // Set as printed + $db->query($sql); + $invoice->fetch($placeid); //Reload object after set lines as printed } $sectionwithinvoicelink = ''; @@ -504,9 +575,9 @@ if ($action == "valid" || $action == "history") else $sectionwithinvoicelink .= $langs->trans('BillShortStatusValidated'); } $sectionwithinvoicelink .= ''; - if ($conf->global->TAKEPOSCONNECTOR) { + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { $sectionwithinvoicelink .= ' '; - } elseif ($conf->global->TAKEPOS_DOLIBARR_PRINTER) { + } elseif ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { $sectionwithinvoicelink .= ' '; } else { $sectionwithinvoicelink .= ' '; @@ -516,7 +587,7 @@ if ($action == "valid" || $action == "history") $sectionwithinvoicelink .= ' '; } - if ($conf->global->TAKEPOS_AUTO_PRINT_TICKETS) $sectionwithinvoicelink .= ''; + if ($remaintopay <= 0 && $conf->global->TAKEPOS_AUTO_PRINT_TICKETS) $sectionwithinvoicelink .= ''; } /* @@ -630,10 +701,81 @@ function DolibarrTakeposPrinting(id) { url: "" + id, }); } + + +$( document ).ready(function() { + console.log("Set customer info in header"); + + trans("Customer"); + if ($invoice->socid != $conf->global->$constforcompanyid) { + $s = $soc->name; + } + ?> + + $("a#customer").html(''); + + stock->enabled) && $conf->global->$constantforkey != "1") + { + $s = ''; + $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; + $warehouse = new Entrepot($db); + $warehouse->fetch($conf->global->$constantforkey); + $s .= $langs->trans("Warehouse").'
    '.$warehouse->ref; + $s .= '
    '; + } + ?> + + $("#infowarehouse").html(''); + + adherent->enabled) && $invoice->socid != $conf->global->$constforcompanyid) + { + $s = ''; + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + $langs->load("members"); + $s .= $langs->trans("Member").': '; + $adh = new Adherent($db); + $result = $adh->fetch('', '', $invoice->socid); + if ($result > 0) + { + $adh->ref = $adh->getFullName($langs); + $s.= $adh->getFullName($langs); + $s.= ' - '.$adh->type; + if ($adh->datefin) + { + $s.= '
    '.$langs->trans("SubscriptionEndDate").': '.dol_print_date($adh->datefin, 'day'); + if ($adh->hasDelay()) { + $s.= " ".img_warning($langs->trans("Late")); + } + } + else + { + $s.= '
    '.$langs->trans("SubscriptionNotReceived"); + if ($adh->statut > 0) $s.= " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated + } + } + else + { + $s.= '
    '.$langs->trans("ThirdpartyNotLinkedToMember"); + } + $s.= '
    '; + } + ?> + $("#moreinfo").html(''); + +}); + use_javascript_ajax)) { @@ -641,7 +783,7 @@ if (!empty($conf->use_javascript_ajax)) print ''."\n"; } - +print ''."\n"; print '
    '; print '
    '.$langs->trans("Ref").''; @@ -378,7 +378,7 @@ if ($action == "view_ticket" || $action == "presend" || $action == "close" || $a print ''; } } else { - print '

    '.$langs->trans("TicketPublicMsgViewLogIn").'

    '; + print '
    '.$langs->trans("TicketPublicMsgViewLogIn").'
    '; print '
    '; print ''; diff --git a/htdocs/public/website/index.php b/htdocs/public/website/index.php index f96ab2b0778..b624a847dc5 100644 --- a/htdocs/public/website/index.php +++ b/htdocs/public/website/index.php @@ -13,6 +13,15 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . + * + * Note about $_SERVER: + * REQUEST_URI: /test/before_rewrite/script.php/path/info?q=helloword + * PHP_SELF: /test/after_rewrite/script.php/path/info + * QUERY_STRING: q=helloword + * SCRIPT_NAME: /test/after_rewrite/script.php + * PATH_INFO: /path/info + * SCRIPT_FILENAME: /var/www/test/php/script.php + * __FILE__ : /var/www/test/php/script_included.php */ /** @@ -52,7 +61,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; $websitekey=GETPOST('website', 'alpha'); $pageid=GETPOST('page', 'alpha')?GETPOST('page', 'alpha'):GETPOST('pageid', 'alpha'); -$pageref=GETPOST('pageref', 'aZ09')?GETPOST('pageref', 'aZ09'):''; +$pageref=GETPOST('pageref', 'alphanohtml')?GETPOST('pageref', 'alphanohtml'):''; $accessallowed = 1; $type=''; @@ -110,7 +119,7 @@ if (empty($pageid)) if (empty($pageid)) { - $array=$objectpage->fetchAll($object->id); + $array=$objectpage->fetchAll($object->id); // TODO Can filter on container of type pages only ? if (is_array($array) && count($array) > 0) { $firstrep=reset($array); diff --git a/htdocs/reception/class/reception.class.php b/htdocs/reception/class/reception.class.php index 260a3744e2e..595100b771c 100644 --- a/htdocs/reception/class/reception.class.php +++ b/htdocs/reception/class/reception.class.php @@ -56,7 +56,13 @@ class Reception extends CommonObject public $socid; public $ref_supplier; + + /** + * @var int Ref int + * @deprecated + */ public $ref_int; + public $brouillon; public $entrepot_id; public $lines = array(); @@ -372,15 +378,15 @@ class Reception extends CommonObject * @param int $id Id of object to load * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param string $ref_int Internal reference of other object + * @param string $notused Internal reference of other object * @return int >0 if OK, 0 if not found, <0 if KO */ - public function fetch($id, $ref = '', $ref_ext = '', $ref_int = '') + public function fetch($id, $ref = '', $ref_ext = '', $notused = '') { global $conf; // Check parameters - if (empty($id) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1; + if (empty($id) && empty($ref) && empty($ref_ext)) return -1; $sql = "SELECT e.rowid, e.ref, e.fk_soc as socid, e.date_creation, e.ref_supplier, e.ref_ext, e.ref_int, e.fk_user_author, e.fk_statut"; $sql .= ", e.weight, e.weight_units, e.size, e.size_units, e.width, e.height"; @@ -397,7 +403,7 @@ class Reception extends CommonObject if ($id) $sql .= " AND e.rowid=".$id; if ($ref) $sql .= " AND e.ref='".$this->db->escape($ref)."'"; if ($ref_ext) $sql .= " AND e.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($ref_int) $sql .= " AND e.ref_int='".$this->db->escape($ref_int)."'"; + if ($notused) $sql .= " AND e.ref_int='".$this->db->escape($notused)."'"; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); @@ -546,7 +552,7 @@ class Reception extends CommonObject $numref = $this->ref; } - $this->newref = $numref; + $this->newref = dol_sanitizeFileName($numref); $now = dol_now(); diff --git a/htdocs/reception/list.php b/htdocs/reception/list.php index abdfd46ce67..de558a6bee4 100644 --- a/htdocs/reception/list.php +++ b/htdocs/reception/list.php @@ -63,7 +63,7 @@ $optioncss = GETPOST('optioncss', 'alpha'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (!$sortfield) $sortfield = "e.ref"; if (!$sortorder) $sortorder = "DESC"; if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 diff --git a/htdocs/resource/agenda.php b/htdocs/resource/agenda.php index 803190ec699..8e45cd9c015 100644 --- a/htdocs/resource/agenda.php +++ b/htdocs/resource/agenda.php @@ -58,7 +58,7 @@ $search_agenda_label=GETPOST('search_agenda_label'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/resource/document.php b/htdocs/resource/document.php index e023134b9f5..174b1503dbe 100644 --- a/htdocs/resource/document.php +++ b/htdocs/resource/document.php @@ -51,7 +51,7 @@ $result = restrictedArea($user, 'resource', $id, 'resource'); // Get parameters $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/resource/list.php b/htdocs/resource/list.php index 2053e19dc72..54cc8963b75 100644 --- a/htdocs/resource/list.php +++ b/htdocs/resource/list.php @@ -93,7 +93,7 @@ if (empty($sortfield)) $sortfield = "t.ref"; if (empty($arch)) $arch = 0; $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/salaries/document.php b/htdocs/salaries/document.php index 7bd9a14a718..57cc3c7b8a1 100644 --- a/htdocs/salaries/document.php +++ b/htdocs/salaries/document.php @@ -52,7 +52,7 @@ $result = restrictedArea($user, 'salaries', '', '', ''); // Get parameters $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/salaries/list.php b/htdocs/salaries/list.php index 74354539043..259547ae8ff 100644 --- a/htdocs/salaries/list.php +++ b/htdocs/salaries/list.php @@ -47,7 +47,7 @@ $search_account = GETPOST('search_account', 'int'); $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/salaries/stats/index.php b/htdocs/salaries/stats/index.php index e96b6776664..25c5be2c79d 100644 --- a/htdocs/salaries/stats/index.php +++ b/htdocs/salaries/stats/index.php @@ -193,6 +193,8 @@ print '
    '; // Show filter box print ''; +print ''; + print ''; print ''; // User diff --git a/htdocs/societe/agenda.php b/htdocs/societe/agenda.php index 7b2e6ead2cc..1ba29e5e190 100644 --- a/htdocs/societe/agenda.php +++ b/htdocs/societe/agenda.php @@ -53,7 +53,7 @@ $result = restrictedArea($user, 'societe', $socid, '&societe'); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/societe/canvas/actions_card_common.class.php b/htdocs/societe/canvas/actions_card_common.class.php index a76e9aa34cb..e369341dd1b 100644 --- a/htdocs/societe/canvas/actions_card_common.class.php +++ b/htdocs/societe/canvas/actions_card_common.class.php @@ -45,7 +45,7 @@ abstract class ActionsCardCommon /** * @var string Error code (or message) */ - public $error=''; + public $error = ''; /** @@ -66,7 +66,7 @@ abstract class ActionsCardCommon //$ret = $this->getInstanceDao(); $object = new Societe($this->db); - if (! empty($id) || ! empty($ref)) $object->fetch($id, $ref); + if (!empty($id) || !empty($ref)) $object->fetch($id, $ref); $this->object = $object; } @@ -87,13 +87,13 @@ abstract class ActionsCardCommon if ($action == 'add' || $action == 'update') $this->assign_post($action); - if ($_GET["type"]=='f') { $this->object->fournisseur=1; } - if ($_GET["type"]=='c') { $this->object->client=1; } - if ($_GET["type"]=='p') { $this->object->client=2; } - if ($_GET["type"]=='cp') { $this->object->client=3; } - if ($_REQUEST["private"]==1) { $this->object->particulier=1; } + if ($_GET["type"] == 'f') { $this->object->fournisseur = 1; } + if ($_GET["type"] == 'c') { $this->object->client = 1; } + if ($_GET["type"] == 'p') { $this->object->client = 2; } + if ($_GET["type"] == 'cp') { $this->object->client = 3; } + if ($_REQUEST["private"] == 1) { $this->object->particulier = 1; } - foreach($this->object as $key => $value) + foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; } @@ -140,15 +140,15 @@ abstract class ActionsCardCommon } // Load object modCodeClient - $module=(! empty($conf->global->SOCIETE_CODECLIENT_ADDON)?$conf->global->SOCIETE_CODECLIENT_ADDON:'mod_codeclient_leopard'); + $module = (!empty($conf->global->SOCIETE_CODECLIENT_ADDON) ? $conf->global->SOCIETE_CODECLIENT_ADDON : 'mod_codeclient_leopard'); if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $modCodeClient = new $module($db); @@ -168,23 +168,23 @@ abstract class ActionsCardCommon $this->tpl['customercode'] = $this->object->code_client; if ((!$this->object->code_client || $this->object->code_client == -1) && $modCodeClient->code_auto) $this->tpl['customercode'] = $modCodeClient->getNextValue($this->object, 0); $this->tpl['ismodifiable_customercode'] = $this->object->codeclient_modifiable(); - $s=$modCodeClient->getToolTip($langs, $this->object, 0); + $s = $modCodeClient->getToolTip($langs, $this->object, 0); $this->tpl['help_customercode'] = $form->textwithpicto('', $s, 1); - if (! empty($conf->fournisseur->enabled)) + if (!empty($conf->fournisseur->enabled)) { $this->tpl['supplier_enabled'] = 1; // Load object modCodeFournisseur - $module=$conf->global->SOCIETE_CODECLIENT_ADDON; + $module = $conf->global->SOCIETE_CODECLIENT_ADDON; if (substr($module, 0, 15) == 'mod_codeclient_' && substr($module, -3) == 'php') { - $module = substr($module, 0, dol_strlen($module)-4); + $module = substr($module, 0, dol_strlen($module) - 4); } - $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); + $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']); foreach ($dirsociete as $dirroot) { - $res=dol_include_once($dirroot.$module.'.php'); + $res = dol_include_once($dirroot.$module.'.php'); if ($res) break; } $modCodeFournisseur = new $module; @@ -197,7 +197,7 @@ abstract class ActionsCardCommon $this->tpl['suppliercode'] = $this->object->code_fournisseur; if ((!$this->object->code_fournisseur || $this->object->code_fournisseur == -1) && $modCodeFournisseur->code_auto) $this->tpl['suppliercode'] = $modCodeFournisseur->getNextValue($this->object, 1); $this->tpl['ismodifiable_suppliercode'] = $this->object->codefournisseur_modifiable(); - $s=$modCodeFournisseur->getToolTip($langs, $this->object, 1); + $s = $modCodeFournisseur->getToolTip($langs, $this->object, 1); $this->tpl['help_suppliercode'] = $form->textwithpicto('', $s, 1); $this->object->LoadSupplierCateg(); @@ -205,10 +205,10 @@ abstract class ActionsCardCommon } // Zip - $this->tpl['select_zip'] = $formcompany->select_ziptown($this->object->zip, 'zipcode', array('town','selectcountry_id','state_id'), 6); + $this->tpl['select_zip'] = $formcompany->select_ziptown($this->object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 6); // Town - $this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode','selectcountry_id','state_id')); + $this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); // Country $this->object->country_id = ($this->object->country_id ? $this->object->country_id : $mysoc->country_id); @@ -223,39 +223,39 @@ abstract class ActionsCardCommon else $this->tpl['select_state'] = $countrynotdefined; // Language - if (! empty($conf->global->MAIN_MULTILANGS)) $this->tpl['select_lang'] = $formadmin->select_language(($this->object->default_lang?$this->object->default_lang:$conf->global->MAIN_LANG_DEFAULT), 'default_lang', 0, 0, 1); + if (!empty($conf->global->MAIN_MULTILANGS)) $this->tpl['select_lang'] = $formadmin->select_language(($this->object->default_lang ? $this->object->default_lang : $conf->global->MAIN_LANG_DEFAULT), 'default_lang', 0, 0, 1); // VAT - $this->tpl['yn_assujtva'] = $form->selectyesno('assujtva_value', $this->tpl['tva_assuj'], 1); // Assujeti par defaut en creation + $this->tpl['yn_assujtva'] = $form->selectyesno('assujtva_value', $this->tpl['tva_assuj'], 1); // Assujeti par defaut en creation // Select users $this->tpl['select_users'] = $form->select_dolusers($this->object->commercial_id, 'commercial_id', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); // Local Tax // TODO mettre dans une classe propre au pays - if($mysoc->country_code=='ES') + if ($mysoc->country_code == 'ES') { $this->tpl['localtax'] = ''; - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; } - elseif($mysoc->localtax1_assuj=="1") + elseif ($mysoc->localtax1_assuj == "1") { - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; } - elseif($mysoc->localtax2_assuj=="1") + elseif ($mysoc->localtax2_assuj == "1") { - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; } } } @@ -263,78 +263,76 @@ abstract class ActionsCardCommon { $head = societe_prepare_head($this->object); - $this->tpl['showhead']=dol_get_fiche_head($head, 'card', '', 0, 'company'); - $this->tpl['showend']=dol_get_fiche_end(); + $this->tpl['showhead'] = dol_get_fiche_head($head, 'card', '', 0, 'company'); + $this->tpl['showend'] = dol_get_fiche_end(); - $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'socid', '', ($user->socid?0:1), 'rowid', 'nom'); + $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom'); $this->tpl['checkcustomercode'] = $this->object->check_codeclient(); $this->tpl['checksuppliercode'] = $this->object->check_codefournisseur(); - $this->tpl['address'] = dol_nl2br($this->object->address); + $this->tpl['address'] = dol_nl2br($this->object->address); - $img=picto_from_langcode($this->object->country_code); - if ($this->object->isInEEC()) $this->tpl['country'] = $form->textwithpicto(($img?$img.' ':'').$this->object->country, $langs->trans("CountryIsInEEC"), 1, 0); - $this->tpl['country'] = ($img?$img.' ':'').$this->object->country; + $img = picto_from_langcode($this->object->country_code); + if ($this->object->isInEEC()) $this->tpl['country'] = $form->textwithpicto(($img ? $img.' ' : '').$this->object->country, $langs->trans("CountryIsInEEC"), 1, 0); + $this->tpl['country'] = ($img ? $img.' ' : '').$this->object->country; $this->tpl['phone'] = dol_print_phone($this->object->phone, $this->object->country_code, 0, $this->object->id, 'AC_TEL'); $this->tpl['fax'] = dol_print_phone($this->object->fax, $this->object->country_code, 0, $this->object->id, 'AC_FAX'); $this->tpl['email'] = dol_print_email($this->object->email, 0, $this->object->id, 'AC_EMAIL'); $this->tpl['url'] = dol_print_url($this->object->url); - $this->tpl['tva_assuj'] = yn($this->object->tva_assuj); + $this->tpl['tva_assuj'] = yn($this->object->tva_assuj); // Third party type $arr = $formcompany->typent_array(1); $this->tpl['typent'] = $arr[$this->object->typent_code]; - if (! empty($conf->global->MAIN_MULTILANGS)) + if (!empty($conf->global->MAIN_MULTILANGS)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; //$s=picto_from_langcode($this->default_lang); //print ($s?$s.' ':''); $langs->load("languages"); - $this->tpl['default_lang'] = ($this->default_lang?$langs->trans('Language_'.$this->object->default_lang):''); + $this->tpl['default_lang'] = ($this->default_lang ? $langs->trans('Language_'.$this->object->default_lang) : ''); } - $this->tpl['image_edit'] = img_edit(); + $this->tpl['image_edit'] = img_edit(); - $this->tpl['display_rib'] = $this->object->display_rib(); + $this->tpl['display_rib'] = $this->object->display_rib(); // Sales representatives $this->tpl['sales_representatives'] = ''; - $listsalesrepresentatives=$this->object->getSalesRepresentatives($user); - $nbofsalesrepresentative=count($listsalesrepresentatives); + $listsalesrepresentatives = $this->object->getSalesRepresentatives($user); + $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 3) // We print only number { - $this->tpl['sales_representatives'].= ''; - $this->tpl['sales_representatives'].= $nbofsalesrepresentative; - $this->tpl['sales_representatives'].= ''; + $this->tpl['sales_representatives'] .= $nbofsalesrepresentative; } elseif ($nbofsalesrepresentative > 0) { - $userstatic=new User($this->db); - $i=0; - foreach($listsalesrepresentatives as $val) + $userstatic = new User($this->db); + $i = 0; + foreach ($listsalesrepresentatives as $val) { - $userstatic->id=$val['id']; - $userstatic->lastname=$val['name']; - $userstatic->firstname=$val['firstname']; - $this->tpl['sales_representatives'].= $userstatic->getNomUrl(1); + $userstatic->id = $val['id']; + $userstatic->lastname = $val['name']; + $userstatic->firstname = $val['firstname']; + $this->tpl['sales_representatives'] .= $userstatic->getNomUrl(1); $i++; - if ($i < $nbofsalesrepresentative) $this->tpl['sales_representatives'].= ', '; + if ($i < $nbofsalesrepresentative) $this->tpl['sales_representatives'] .= ', '; } } - else $this->tpl['sales_representatives'].= $langs->trans("NoSalesRepresentativeAffected"); + else $this->tpl['sales_representatives'] .= $langs->trans("NoSalesRepresentativeAffected"); // Linked member - if (! empty($conf->adherent->enabled)) + if (!empty($conf->adherent->enabled)) { $langs->load("members"); - $adh=new Adherent($this->db); - $result=$adh->fetch('', '', $this->object->id); + $adh = new Adherent($this->db); + $result = $adh->fetch('', '', $this->object->id); if ($result > 0) { - $adh->ref=$adh->getFullName($langs); + $adh->ref = $adh->getFullName($langs); $this->tpl['linked_member'] = $adh->getNomUrl(1); } else @@ -345,26 +343,26 @@ abstract class ActionsCardCommon // Local Tax // TODO mettre dans une classe propre au pays - if($mysoc->country_code=='ES') + if ($mysoc->country_code == 'ES') { $this->tpl['localtax'] = ''; - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") { - $this->tpl['localtax'].= ''; - $this->tpl['localtax'].= ''; - $this->tpl['localtax'].= ''; - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; + $this->tpl['localtax'] .= ''; + $this->tpl['localtax'] .= ''; + $this->tpl['localtax'] .= ''; } - elseif($mysoc->localtax1_assuj=="1") + elseif ($mysoc->localtax1_assuj == "1") { - $this->tpl['localtax'].= ''; - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; + $this->tpl['localtax'] .= ''; } - elseif($mysoc->localtax2_assuj=="1") + elseif ($mysoc->localtax2_assuj == "1") { - $this->tpl['localtax'].= ''; - $this->tpl['localtax'].= ''; + $this->tpl['localtax'] .= ''; + $this->tpl['localtax'] .= ''; } } } @@ -382,47 +380,47 @@ abstract class ActionsCardCommon // phpcs:enable global $langs, $mysoc; - $this->object->id = $_POST["socid"]; - $this->object->name = $_POST["nom"]; - $this->object->prefix_comm = $_POST["prefix_comm"]; - $this->object->client = $_POST["client"]; - $this->object->code_client = $_POST["code_client"]; - $this->object->fournisseur = $_POST["fournisseur"]; - $this->object->code_fournisseur = $_POST["code_fournisseur"]; - $this->object->address = $_POST["adresse"]; - $this->object->zip = $_POST["zipcode"]; - $this->object->town = $_POST["town"]; - $this->object->country_id = $_POST["country_id"]?$_POST["country_id"]:$mysoc->country_id; - $this->object->state_id = $_POST["state_id"]; - $this->object->phone = $_POST["tel"]; - $this->object->fax = $_POST["fax"]; - $this->object->email = $_POST["email"]; - $this->object->url = $_POST["url"]; - $this->object->capital = $_POST["capital"]; - $this->object->idprof1 = $_POST["idprof1"]; - $this->object->idprof2 = $_POST["idprof2"]; - $this->object->idprof3 = $_POST["idprof3"]; - $this->object->idprof4 = $_POST["idprof4"]; - $this->object->typent_id = $_POST["typent_id"]; - $this->object->effectif_id = $_POST["effectif_id"]; - $this->object->barcode = $_POST["barcode"]; - $this->object->forme_juridique_code = $_POST["forme_juridique_code"]; - $this->object->default_lang = $_POST["default_lang"]; - $this->object->commercial_id = $_POST["commercial_id"]; + $this->object->id = $_POST["socid"]; + $this->object->name = $_POST["nom"]; + $this->object->prefix_comm = $_POST["prefix_comm"]; + $this->object->client = $_POST["client"]; + $this->object->code_client = $_POST["code_client"]; + $this->object->fournisseur = $_POST["fournisseur"]; + $this->object->code_fournisseur = $_POST["code_fournisseur"]; + $this->object->address = $_POST["adresse"]; + $this->object->zip = $_POST["zipcode"]; + $this->object->town = $_POST["town"]; + $this->object->country_id = $_POST["country_id"] ? $_POST["country_id"] : $mysoc->country_id; + $this->object->state_id = $_POST["state_id"]; + $this->object->phone = $_POST["tel"]; + $this->object->fax = $_POST["fax"]; + $this->object->email = $_POST["email"]; + $this->object->url = $_POST["url"]; + $this->object->capital = $_POST["capital"]; + $this->object->idprof1 = $_POST["idprof1"]; + $this->object->idprof2 = $_POST["idprof2"]; + $this->object->idprof3 = $_POST["idprof3"]; + $this->object->idprof4 = $_POST["idprof4"]; + $this->object->typent_id = $_POST["typent_id"]; + $this->object->effectif_id = $_POST["effectif_id"]; + $this->object->barcode = $_POST["barcode"]; + $this->object->forme_juridique_code = $_POST["forme_juridique_code"]; + $this->object->default_lang = $_POST["default_lang"]; + $this->object->commercial_id = $_POST["commercial_id"]; - $this->object->tva_assuj = $_POST["assujtva_value"]?$_POST["assujtva_value"]:1; - $this->object->tva_intra = $_POST["tva_intra"]; + $this->object->tva_assuj = $_POST["assujtva_value"] ? $_POST["assujtva_value"] : 1; + $this->object->tva_intra = $_POST["tva_intra"]; //Local Taxes - $this->object->localtax1_assuj = $_POST["localtax1assuj_value"]; - $this->object->localtax2_assuj = $_POST["localtax2assuj_value"]; + $this->object->localtax1_assuj = $_POST["localtax1assuj_value"]; + $this->object->localtax2_assuj = $_POST["localtax2assuj_value"]; // We set country_id, and country_code label of the chosen country if ($this->object->country_id) { - $tmparray=getCountry($this->object->country_id, 'all', $this->db, $langs, 0); - $this->object->country_code = $tmparray['code']; - $this->object->country_label= $tmparray['label']; + $tmparray = getCountry($this->object->country_id, 'all', $this->db, $langs, 0); + $this->object->country_code = $tmparray['code']; + $this->object->country_label = $tmparray['label']; } } } diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index b7bdda5d6ba..edc00088c39 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -1557,14 +1557,9 @@ else print ''; } - // Other attributes - $parameters = array('colspan' => ' colspan="3"', 'cols' => '3'); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook)) - { - print $object->showOptionals($extrafields, 'edit', $parameters); - } + // Other attributes + $parameters = array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; // Assign a sale representative print ''; @@ -2218,14 +2213,9 @@ else print ''; } - // Other attributes - $parameters = array('colspan' => ' colspan="3"', 'cols' => '3'); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook)) - { - print $object->showOptionals($extrafields, 'edit', $parameters); - } + // Other attributes + $parameters = array('socid'=>$socid, 'colspan' => ' colspan="3"', 'colspanvalue' => '3'); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; // Webservices url/key if (!empty($conf->syncsupplierwebservices->enabled)) { diff --git a/htdocs/societe/class/api_contacts.class.php b/htdocs/societe/class/api_contacts.class.php index cfddddb7b96..d8efc00f85e 100644 --- a/htdocs/societe/class/api_contacts.class.php +++ b/htdocs/societe/class/api_contacts.class.php @@ -74,7 +74,7 @@ class Contacts extends DolibarrApi { throw new RestException(401, 'No permission to read contacts'); } - if ($id ==0) { + if ($id == 0) { $result = $this->contact->initAsSpecimen(); } else { $result = $this->contact->fetch($id); @@ -87,7 +87,7 @@ class Contacts extends DolibarrApi if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { - throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } if ($includecount) @@ -134,37 +134,37 @@ class Contacts extends DolibarrApi $search_sale = DolibarrApiAccess::$user->id; $sql = "SELECT t.rowid"; - $sql.= " FROM " . MAIN_DB_PREFIX . "socpeople as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX . "socpeople_extrafields as te ON te.fk_object = t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as t"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople_extrafields as te ON te.fk_object = t.rowid"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { // We need this table joined to the select in order to filter by sale - $sql.= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; } - $sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON t.fk_soc = s.rowid"; - $sql.= ' WHERE t.entity IN (' . getEntity('socpeople') . ')'; - if ($socids) $sql.= " AND t.fk_soc IN (" . $socids . ")"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON t.fk_soc = s.rowid"; + $sql .= ' WHERE t.entity IN ('.getEntity('socpeople').')'; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) - $sql.= " AND t.fk_soc = sc.fk_soc"; + $sql .= " AND t.fk_soc = sc.fk_soc"; if ($search_sale > 0) - $sql.= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + $sql .= " AND s.rowid = sc.fk_soc"; // Join for the needed table to filter by sale // Insert sale filter if ($search_sale > 0) { - $sql .= " AND sc.fk_user = " . $search_sale; + $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters if ($sqlfilters) { - if (! DolibarrApi::_checkFilters($sqlfilters)) + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } - $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; } - $sql.= $db->order($sortfield, $sortorder); + $sql .= $db->order($sortfield, $sortorder); if ($limit) { @@ -174,7 +174,7 @@ class Contacts extends DolibarrApi } $offset = $limit * $page; - $sql.= $db->plimit($limit + 1, $offset); + $sql .= $db->plimit($limit + 1, $offset); } $result = $db->query($sql); if ($result) @@ -199,7 +199,7 @@ class Contacts extends DolibarrApi } } else { - throw new RestException(503, 'Error when retrieve contacts : ' . $sql); + throw new RestException(503, 'Error when retrieve contacts : '.$sql); } if (!count($obj_ret)) { @@ -255,7 +255,7 @@ class Contacts extends DolibarrApi if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { - throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) @@ -290,10 +290,10 @@ class Contacts extends DolibarrApi if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe')) { - throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } $this->contact->oldcopy = clone $this->contact; - return $this->contact->delete($id); + return $this->contact->delete(); } /** @@ -330,7 +330,7 @@ class Contacts extends DolibarrApi } if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) { - throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } // Check mandatory fields @@ -362,7 +362,7 @@ class Contacts extends DolibarrApi */ public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { - if (! DolibarrApiAccess::$user->rights->categorie->lire) { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { throw new RestException(401); } @@ -391,31 +391,29 @@ class Contacts extends DolibarrApi * * @return mixed * - * @throws 401 RestException Insufficient rights - * @throws 401 RestException Access not allowed for login - * @throws 404 RestException Category not found - * @throws 404 RestException Contact not found + * @throws RestException 401 Insufficient rights + * @throws RestException 404 Category or contact not found */ public function addCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->contact->creer) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { throw new RestException(401, 'Insufficient rights'); } $result = $this->contact->fetch($id); - if (! $result) { + if (!$result) { throw new RestException(404, 'Contact not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if (! $result) { + if (!$result) { throw new RestException(404, 'category not found'); } - if (! DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -433,31 +431,29 @@ class Contacts extends DolibarrApi * @param int $category_id Id of category * @return mixed * - * @throws 401 RestException Insufficient rights - * @throws 401 RestException Access not allowed for login - * @throws 404 RestException Category not found - * @throws 404 RestException Contact not found + * @throws RestException 401 Insufficient rights + * @throws RestException 404 Category or contact not found */ public function deleteCategory($id, $category_id) { - if(! DolibarrApiAccess::$user->rights->societe->contact->creer) { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { throw new RestException(401, 'Insufficient rights'); } $result = $this->contact->fetch($id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'Contact not found'); } $category = new Categorie($this->db); $result = $category->fetch($category_id); - if( ! $result ) { + if (!$result) { throw new RestException(404, 'category not found'); } - if( ! DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) { + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index 07dd2ba6031..5f031137c1f 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -731,9 +731,9 @@ class Thirdparties extends DolibarrApi * * @return array List of outstandings proposals of thirdparty * - * @throws 400 - * @throws 401 - * @throws 404 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 */ public function getOutStandingProposals($id, $mode = 'customer') { @@ -775,9 +775,9 @@ class Thirdparties extends DolibarrApi * * @return array List of outstandings orders of thirdparty * - * @throws 400 - * @throws 401 - * @throws 404 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 */ public function getOutStandingOrder($id, $mode = 'customer') { @@ -818,9 +818,9 @@ class Thirdparties extends DolibarrApi * * @return array List of outstandings invoices of thirdparty * - * @throws 400 - * @throws 401 - * @throws 404 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 */ public function getOutStandingInvoices($id, $mode = 'customer') { @@ -861,9 +861,9 @@ class Thirdparties extends DolibarrApi * * @return array List of representatives of thirdparty * - * @throws 400 - * @throws 401 - * @throws 404 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 */ public function getSalesRepresentatives($id, $mode = 0) { @@ -903,10 +903,10 @@ class Thirdparties extends DolibarrApi * * @return array List of fixed discount of thirdparty * - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 503 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 503 */ public function getFixedAmountDiscounts($id, $filter = "none", $sortfield = "f.type", $sortorder = 'ASC') { @@ -961,10 +961,10 @@ class Thirdparties extends DolibarrApi * @url GET {id}/getinvoicesqualifiedforreplacement * * @return array - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function getInvoicesQualifiedForReplacement($id) { @@ -1003,10 +1003,11 @@ class Thirdparties extends DolibarrApi * @url GET {id}/getinvoicesqualifiedforcreditnote * * @return array - * @throws 400 - * @throws 401 - * @throws 404 - * @throws 405 + * + * @throws RestException 400 + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 405 */ public function getInvoicesQualifiedForCreditNote($id) { @@ -1313,8 +1314,8 @@ class Thirdparties extends DolibarrApi * @param string $site Site key * * @return SocieteAccount[] - * @throws 401 Unauthorized: User does not have permission to read thirdparties - * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty + * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties + * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty * * @url GET {id}/gateways/ */ @@ -1387,11 +1388,11 @@ class Thirdparties extends DolibarrApi * @param array $request_data Request data * * @return SocieteAccount - * @throws 401 Unauthorized: User does not have permission to read thirdparties - * @throws 409 Conflict: A SocieteAccount entity (gateway) already exists for this company and site. - * @throws 422 Unprocessable Entity: You must pass the site attribute in your request data ! - * @throws 500 Internal Server Error: Error creating SocieteAccount account - * @status 201 + * + * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties + * @throws RestException 409 Conflict: A SocieteAccount entity (gateway) already exists for this company and site. + * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data ! + * @throws RestException 500 Internal Server Error: Error creating SocieteAccount account * * @url POST {id}/gateways */ @@ -1447,11 +1448,11 @@ class Thirdparties extends DolibarrApi * @param array $request_data Request data * * @return SocieteAccount - * @throws 401 Unauthorized: User does not have permission to read thirdparties - * @throws 422 Unprocessable Entity: You must pass the site attribute in your request data ! - * @throws 500 Internal Server Error: Error updating SocieteAccount entity * - * @throws RestException + * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties + * @throws RestException 422 Unprocessable Entity: You must pass the site attribute in your request data ! + * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity + * * @url PUT {id}/gateways/{site} */ public function putSocieteAccount($id, $site, $request_data = null) @@ -1529,10 +1530,11 @@ class Thirdparties extends DolibarrApi * @param array $request_data Request data * * @return SocieteAccount - * @throws 401 Unauthorized: User does not have permission to read thirdparties - * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty - * @throws 409 Conflict: Another SocieteAccount entity already exists for this thirdparty with this site key. - * @throws 500 Internal Server Error: Error updating SocieteAccount entity + * + * @throws RestException 401 Unauthorized: User does not have permission to read thirdparties + * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty + * @throws RestException 409 Conflict: Another SocieteAccount entity already exists for this thirdparty with this site key. + * @throws RestException 500 Internal Server Error: Error updating SocieteAccount entity * * @url PATCH {id}/gateways/{site} */ @@ -1583,9 +1585,9 @@ class Thirdparties extends DolibarrApi * @param int $site Site key * * @return void - * @throws 401 Unauthorized: User does not have permission to delete thirdparties gateways - * @throws 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty - * @throws 500 Internal Server Error: Error deleting SocieteAccount entity + * @throws RestException 401 Unauthorized: User does not have permission to delete thirdparties gateways + * @throws RestException 404 Not Found: Specified thirdparty ID does not belongs to an existing thirdparty + * @throws RestException 500 Internal Server Error: Error deleting SocieteAccount entity * * @url DELETE {id}/gateways/{site} */ diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 08416ed8842..ad5c66a50b8 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -125,16 +125,16 @@ class Societe extends CommonObject /** * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ - public $fields=array( + public $fields = array( 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), 'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20), 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25), 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30), - 'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35), - 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36), + 'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1), + 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>1), 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1), 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>45), - 'ref_int' =>array('type'=>'varchar(60)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>-1, 'position'=>50), + 'ref_int' =>array('type'=>'varchar(60)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>50), // deprecated 'code_client' =>array('type'=>'varchar(24)', 'label'=>'Code client', 'enabled'=>1, 'visible'=>-1, 'position'=>55), 'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'Code fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>60), 'code_compta' =>array('type'=>'varchar(24)', 'label'=>'Code compta', 'enabled'=>1, 'visible'=>-1, 'position'=>65), @@ -625,13 +625,13 @@ class Societe extends CommonObject /** * @var string Internal ref + * @deprecated */ public $ref_int; /** * External user reference. - * This is to allow external systems to store their id and make self-developed synchronizing functions easier to - * build. + * This is to allow external systems to store their id and make self-developed synchronizing functions easier to build. * @var string */ public $ref_ext; @@ -877,7 +877,7 @@ class Societe extends CommonObject $contact->firstname = $this->firstname; $contact->civility_id = $this->civility_id; $contact->socid = $this->id; // fk_soc - $contact->statut = 1; // deprecated + $contact->statut = 1; // deprecated $contact->status = 1; $contact->priv = 0; $contact->country_id = $this->country_id; @@ -1454,7 +1454,7 @@ class Societe extends CommonObject * @param int $rowid Id of third party to load * @param string $ref Reference of third party, name (Warning, this can return several records) * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr) - * @param string $ref_int Internal reference of third party (not used by dolibarr) + * @param string $notused Not used * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records) * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records) * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records) @@ -1465,12 +1465,12 @@ class Societe extends CommonObject * @param string $ref_alias Name_alias of third party (Warning, this can return several records) * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found. */ - public function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '') + public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '') { global $langs; global $conf; - if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1; + if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1; $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm'; $sql .= ', s.status'; @@ -1515,7 +1515,7 @@ class Societe extends CommonObject if ($ref) $sql .= " AND s.nom = '".$this->db->escape($ref)."'"; if ($ref_alias) $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'"; if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'"; - if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'"; + if ($notused) $sql .= " AND s.ref_int = '".$this->db->escape($notused)."'"; if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'"; if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'"; if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'"; @@ -2111,7 +2111,7 @@ class Societe extends CommonObject $reparray[$i]['email'] = $obj->email; $reparray[$i]['phone'] = $obj->office_phone; $reparray[$i]['job'] = $obj->job; - $reparray[$i]['statut'] = $obj->status; // deprecated + $reparray[$i]['statut'] = $obj->status; // deprecated $reparray[$i]['status'] = $obj->status; $reparray[$i]['entity'] = $obj->entity; $reparray[$i]['login'] = $obj->login; @@ -2330,7 +2330,7 @@ class Societe extends CommonObject if (!empty($this->logo) && class_exists('Form')) { $label .= '
    '; - $label .= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip. + $label .= Form::showphoto('societe', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip. $label .= '
    '; } elseif (!empty($this->logo_squarred) && class_exists('Form')) @@ -2417,7 +2417,9 @@ class Societe extends CommonObject $label .= '
    '.$langs->trans('CustomerAccountancyCode').': '.($this->code_compta ? $this->code_compta : $this->code_compta_client); if (!empty($conf->accounting->enabled) && $this->fournisseur) $label .= '
    '.$langs->trans('SupplierAccountancyCode').': '.$this->code_compta_fournisseur; - + if (isset($this->status)) { + $label .= '
    '.$langs->trans("Status").": ".$this->getLibStatut(5); + } $label .= ''; // Add type of canvas diff --git a/htdocs/societe/consumption.php b/htdocs/societe/consumption.php index cd82533fc88..3664d8fd848 100644 --- a/htdocs/societe/consumption.php +++ b/htdocs/societe/consumption.php @@ -42,7 +42,7 @@ if ($socid > 0) $object->fetch($socid); $limit = GETPOST('limit', 'int')?GETPOST('limit', 'int'):$conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/societe/document.php b/htdocs/societe/document.php index f907bd210f6..992892e96db 100644 --- a/htdocs/societe/document.php +++ b/htdocs/societe/document.php @@ -50,7 +50,7 @@ $result = restrictedArea($user, 'societe', $id, '&societe'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/societe/index.php b/htdocs/societe/index.php index f0206175d0d..5b89c086c1f 100644 --- a/htdocs/societe/index.php +++ b/htdocs/societe/index.php @@ -112,10 +112,10 @@ if (!empty($conf->use_javascript_ajax) && ((round($third['prospect']) ? 1 : 0) + include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphthirdparties'); print $dolgraph->show(); print ''."\n"; @@ -200,10 +200,10 @@ if (!empty($conf->categorie->enabled) && !empty($conf->global->CATEGORY_GRAPHSTA include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); - $dolgraph->setShowLegend(1); + $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); $dolgraph->SetType(array('pie')); - $dolgraph->setWidth('100%'); + $dolgraph->setHeight('200'); $dolgraph->draw('idgraphcateg'); print $dolgraph->show(); } @@ -238,7 +238,10 @@ $max = 15; $sql = "SELECT s.rowid, s.nom as name, s.email, s.client, s.fournisseur"; $sql .= ", s.code_client"; $sql .= ", s.code_fournisseur"; +$sql .= ", s.code_compta_fournisseur"; +$sql .= ", s.code_compta"; $sql .= ", s.logo"; +$sql .= ", s.entity"; $sql .= ", s.canvas, s.tms as date_modification, s.status as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -285,6 +288,9 @@ if ($result) $thirdparty_static->code_fournisseur = $objp->code_fournisseur; $thirdparty_static->canvas = $objp->canvas; $thirdparty_static->email = $objp->email; + $thirdparty_static->entity = $objp->entity; + $thirdparty_static->code_compta_fournisseur = $objp->code_compta_fournisseur; + $thirdparty_static->code_compta = $objp->code_compta; print ''; // Name diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 47a116c7fdf..04ad577bff9 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -10,6 +10,7 @@ * Copyright (C) 2017 Rui Strecht * Copyright (C) 2017 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 @@ -96,8 +97,6 @@ $search_type = GETPOST('search_type', 'alpha'); $search_level = GETPOST("search_level", "array"); $search_stcomm = GETPOST('search_stcomm', 'int'); $search_import_key = GETPOST("search_import_key", "alpha"); -$search_btn = GETPOST('button_search', 'alpha'); -$search_remove_btn = GETPOST('button_removefilter', 'alpha'); $search_parent_name = GETPOST('search_parent_name', 'alpha'); $type = GETPOST('type', 'alpha'); @@ -109,10 +108,10 @@ $diroutputmassaction = $conf->societe->dir_output.'/temp/massgeneration/'.$user- $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (!$sortorder) $sortorder = "ASC"; if (!$sortfield) $sortfield = "s.nom"; -if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -235,17 +234,17 @@ if ($action == "change") // Change customer for TakePOS $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' AND entity IN (".getEntity('invoice').")"; $result = $db->query($sql); $num_lines = $db->num_rows($result); - if ($num_lines==0) + if ($num_lines == 0) { - require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php'; + require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $invoice = new Facture($db); $constforthirdpartyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; $invoice->socid = $conf->global->$constforthirdpartyid; $invoice->date = dol_now(); $invoice->module_source = 'takepos'; $invoice->pos_source = $_SESSION["takeposterminal"]; - $placeid =$invoice->create($user); - $sql="UPDATE ".MAIN_DB_PREFIX."facture set ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' where rowid=".$placeid; + $placeid = $invoice->create($user); + $sql = "UPDATE ".MAIN_DB_PREFIX."facture set ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")' where rowid=".$placeid; $db->query($sql); } @@ -253,6 +252,7 @@ if ($action == "change") // Change customer for TakePOS $resql = $db->query($sql); ?> @@ -72,6 +111,21 @@ if ($action == "addnote") echo ' +load_cache_vatrates("'" . $mysoc->country_code . "'"); + if ($num > 0) { + print '

    '; + print $langs->trans('VAT') . ' : '; + foreach ($form->cache_vatrates as $rate) { + print ''; + } + } +} +?> diff --git a/htdocs/takepos/takepos.php b/htdocs/takepos/index.php similarity index 83% rename from htdocs/takepos/takepos.php rename to htdocs/takepos/index.php index 75145154c22..9615f90d539 100644 --- a/htdocs/takepos/takepos.php +++ b/htdocs/takepos/index.php @@ -17,7 +17,7 @@ */ /** - * \file htdocs/takepos/takepos.php + * \file htdocs/takepos/index.php * \ingroup takepos * \brief Main TakePOS screen */ @@ -48,7 +48,7 @@ if ($setterminal > 0) $_SESSION["takeposterminal"] = $setterminal; } -$_SESSION["urlfrom"] = '/takepos/takepos.php'; +$_SESSION["urlfrom"] = '/takepos/index.php'; $langs->loadLangs(array("bills", "orders", "commercial", "cashdesk", "receiptprinter")); @@ -137,8 +137,8 @@ foreach ($categories as $key => $categorycursor) } } -sort($maincategories); -sort($subcategories); +$maincategories = dol_sort_array($maincategories, 'label'); +$subcategories = dol_sort_array($subcategories, 'label'); ?> var categories = ; @@ -179,7 +179,7 @@ function ClearSearch() { // Set the focus on search field but only on desktop. On tablet or smartphone, we don't to avoid to have the keyboard open automatically function setFocusOnSearchField() { - console.log("Call setFocusOnSearchField in page takepos.php"); + console.log("Call setFocusOnSearchField in page index.php"); browser->layout == 'classic') { ?> console.log("has keyboard from localStorage, so we can force focus on search field"); $("#search").focus(); @@ -263,6 +263,8 @@ function LoadProducts(position, issubcat) { if (currentcat==val.fk_parent) { $("#prodivdesc"+ishow).show(); $("#prodesc"+ishow).text(val.label); + $("#proprice"+ishow).attr("class", "hidden"); + $("#proprice"+ishow).html(""); $("#proimg"+ishow).attr("src","genimg/index.php?query=cat&id="+val.rowid); $("#prodiv"+ishow).data("rowid",val.rowid); $("#prodiv"+ishow).data("iscat",1); @@ -281,6 +283,8 @@ function LoadProducts(position, issubcat) { if (typeof (data[idata]) == "undefined") { $("#prodivdesc"+ishow).hide(); $("#prodesc"+ishow).text(""); + $("#proprice"+ishow).attr("class", "hidden"); + $("#proprice"+ishow).html(""); $("#proimg"+ishow).attr("title",""); $("#proimg"+ishow).attr("src","genimg/empty.png"); $("#prodiv"+ishow).data("rowid",""); @@ -289,9 +293,17 @@ function LoadProducts(position, issubcat) { ishow++; //Next product to show after print data product } else if ((data[idata]['status']) == "1") { // Only show products with status=1 (for sell) - var titlestring = 'transnoentities('Ref').': '); ?>'+data[idata]['ref']; + transnoentities('Ref').': ')."' + data[idata]['ref']"; + $titlestring .= " + ' - ".dol_escape_js($langs->trans("Barcode").': ')."' + data[idata]['barcode']"; + ?> + var titlestring = ; $("#prodivdesc"+ishow).show(); $("#prodesc"+ishow).text(data[parseInt(idata)]['label']); + if (data[parseInt(idata)]['price_formated']) { + $("#proprice"+ishow).attr("class", "productprice"); + $("#proprice"+ishow).html(data[parseInt(idata)]['price_formated']); + } $("#proimg"+ishow).attr("title", titlestring); $("#proimg"+ishow).attr("src", "genimg/index.php?query=pro&id="+data[idata]['id']); $("#prodiv"+ishow).data("rowid", data[idata]['id']); @@ -337,6 +349,8 @@ function MoreProducts(moreorless) { if (typeof (data[idata]) == "undefined") { $("#prodivdesc"+ishow).hide(); $("#prodesc"+ishow).text(""); + $("#proprice"+ishow).attr("class", ""); + $("#proprice"+ishow).html(""); $("#proimg"+ishow).attr("src","genimg/empty.png"); $("#prodiv"+ishow).data("rowid",""); ishow++; //Next product to show after print data product @@ -345,6 +359,10 @@ function MoreProducts(moreorless) { //Only show products with status=1 (for sell) $("#prodivdesc"+ishow).show(); $("#prodesc"+ishow).text(data[parseInt(idata)]['label']); + if (data[parseInt(idata)]['price_formated']) { + $("#proprice"+ishow).attr("class", "productprice"); + $("#proprice"+ishow).html(data[parseInt(idata)]['price_formated']); + } $("#proimg"+ishow).attr("src","genimg/index.php?query=pro&id="+data[idata]['id']); $("#prodiv"+ishow).data("rowid",data[idata]['id']); $("#prodiv"+ishow).data("iscat",0); @@ -398,6 +416,12 @@ function History() $.colorbox({href:"../compta/facture/list.php?contextpage=poslist", width:"90%", height:"80%", transition:"none", iframe:"true", title:"trans("History"); ?>"}); } +function Reduction() { + invoiceid = $("#invoiceid").val(); + console.log("Open popup to enter reduction on invoiceid="+invoiceid); + $.colorbox({href:"reduction.php?place="+place+"&invoiceid="+invoiceid, width:"80%", height:"90%", transition:"none", iframe:"true", title:""}); +} + function CloseBill() { invoiceid = $("#invoiceid").val(); console.log("Open popup to enter payment on invoiceid="+invoiceid); @@ -429,39 +453,81 @@ function Refresh() { function New() { // If we go here,it means $conf->global->TAKEPOS_BAR_RESTAURANT is not defined console.log("New with place = , js place="+place); - var r = confirm(' 0 ? $langs->transnoentitiesnoconv("ConfirmDeletionOfThisPOSSale") : $langs->transnoentitiesnoconv("ConfirmDiscardOfThisPOSSale")); ?>'); - if (r == true) { - $("#poslines").load("invoice.php?action=delete&place="+place, function() { - //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); - }); - ClearSearch(); - } + + invoiceid = $("#invoiceid").val(); + $.getJSON('/takepos/ajax/ajax.php?action=getInvoice&id='+invoiceid, function(data) { + var r; + + if (parseInt(data['paye']) === 1) { + r = true; + } else { + r = confirm(' 0 ? $langs->transnoentitiesnoconv("ConfirmDeletionOfThisPOSSale") : $langs->transnoentitiesnoconv("ConfirmDiscardOfThisPOSSale")); ?>'); + } + + if (r == true) { + $("#poslines").load("invoice.php?action=delete&place=" + place, function () { + //$('#poslines').scrollTop($('#poslines')[0].scrollHeight); + }); + ClearSearch(); + } + }); } -function Search2() { - console.log("Search2 Call ajax search to replace products"); - if(window.event.keyCode == 13) var key=13; - pageproducts=0; - jQuery(".wrapper2 .catwatermark").hide(); - $.getJSON('/takepos/ajax/ajax.php?action=search&term='+$('#search').val(), function(data) { - for (i = 0; i < ; i++) { - if (typeof (data[i]) == "undefined"){ - $("#prodesc"+i).text(""); - $("#proimg"+i).attr("src","genimg/empty.png"); - $("#prodiv"+i).data("rowid",""); - continue; +/** + * Search products + * + * @param {int} keyCodeForEnter Key code for "enter" + * return {void} + */ +function Search2(keyCodeForEnter) { + console.log("Search2 Call ajax search to replace products keyCodeForEnter="+keyCodeForEnter); + + var search = false; + var eventKeyCode = window.event.keyCode; + if (typeof keyCodeForEnter === 'undefined' || eventKeyCode == keyCodeForEnter) { + search = true; + } + + if (search === true) { + pageproducts = 0; + jQuery(".wrapper2 .catwatermark").hide(); + $.getJSON('/takepos/ajax/ajax.php?action=search&term=' + $('#search').val(), function (data) { + for (i = 0; i < ; i++) { + if (typeof (data[i]) == "undefined") { + $("#prodesc" + i).text(""); + $("#proprice" + i).attr("class", "hidden"); + $("#proprice" + i).html(""); + $("#proimg" + i).attr("src", "genimg/empty.png"); + $("#prodiv" + i).data("rowid", ""); + continue; + } + transnoentities('Ref').': ')."' + data[i]['ref']"; + $titlestring .= " + ' - ".dol_escape_js($langs->trans("Barcode").': ')."' + data[i]['barcode']"; + ?> + var titlestring = ; + $("#prodesc" + i).text(data[i]['label']); + $("#prodivdesc" + i).show(); + if (data[i]['price_formated']) { + $("#proprice" + i).attr("class", "productprice"); + $("#proprice" + i).html(data[i]['price_formated']); + } + $("#proimg" + i).attr("title", titlestring); + $("#proimg" + i).attr("src", "genimg/index.php?query=pro&id=" + data[i]['rowid']); + $("#prodiv" + i).data("rowid", data[i]['rowid']); + $("#prodiv" + i).data("iscat", 0); } - var titlestring = 'transnoentities('Ref').': '); ?>'+data[i]['ref']; - $("#prodesc"+i).text(data[i]['label']); - $("#prodivdesc"+i).show(); - $("#proimg"+i).attr("title", titlestring); - $("#proimg"+i).attr("src", "genimg/?query=pro&id="+data[i]['rowid']); - $("#prodiv"+i).data("rowid", data[i]['rowid']); - $("#prodiv"+i).data("iscat", 0); - } - }).always(function() { - if(key==13) ClickProduct(0); - }); + }).always(function (data) { + // If there is only 1 answer + if ($('#search').val().length > 0 && data.length == 1) { + console.log($('#search').val()+' - '+data[0]['barcode']); + if ($('#search').val() == data[0]['barcode']) { + console.log("There is only 1 answer with barcode matching the search, so we add the product in basket"); + ClickProduct(0); + } + } + }); + } } function Edit(number) { @@ -605,14 +671,14 @@ function TerminalsDialog() modal: true, buttons: { 'trans("Terminal")) ?> 1': function() { - location.href='takepos.php?setterminal=1'; + location.href='index.php?setterminal=1'; } global->TAKEPOS_NUM_TERMINALS; $i++) { print ", '".dol_escape_js($langs->trans("Terminal"))." ".$i."': function() { - location.href='takepos.php?setterminal=".$i."'; + location.href='index.php?setterminal=".$i."'; } "; } @@ -648,7 +714,8 @@ $( document ).ready(function() { global->TAKEPOS_NUM_TERMINALS != "1" && $_SESSION["takeposterminal"] == "") print '
    '.$langs->trans('TerminalSelect').'
    '; +print ''; +$keyCodeForEnter = $conf->global->{'CASHDESK_READER_KEYCODE_FOR_ENTER'.$_SESSION['takeposterminal']} > 0 ? $conf->global->{'CASHDESK_READER_KEYCODE_FOR_ENTER'.$_SESSION['takeposterminal']} : ''; ?>
    @@ -658,20 +725,29 @@ if (empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { @@ -752,6 +828,7 @@ if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { } $menus[$r++] = array('title'=>'
    '.$langs->trans("History").'
    ', 'action'=>'History();'); $menus[$r++] = array('title'=>'
    '.$langs->trans("FreeZone").'
    ', 'action'=>'FreeZone();'); +$menus[$r++] = array('title'=>'
    '.$langs->trans("Reduction").'
    ', 'action'=>'Reduction();'); $menus[$r++] = array('title'=>'
    '.$langs->trans("Payment").'
    ', 'action'=>'CloseBill();'); if ($conf->global->TAKEPOS_DIRECT_PAYMENT) { @@ -768,13 +845,13 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) //add temp ticket button if ($conf->global->TAKEPOS_BAR_RESTAURANT) { - if ($conf->global->TAKEPOSCONNECTOR) { + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { $menus[$r++] = array('title'=>'
    '.$langs->trans("Receipt").'
    ', 'action'=>'TakeposPrinting(placeid);'); } else { $menus[$r++] = array('title'=>'
    '.$langs->trans("Receipt").'
    ', 'action'=>'Print(placeid);'); } } - if ($conf->global->TAKEPOSCONNECTOR && $conf->global->TAKEPOS_ORDER_NOTES == 1) + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector" && $conf->global->TAKEPOS_ORDER_NOTES == 1) { $menus[$r++] = array('title'=>'
    '.$langs->trans("OrderNotes").'
    ', 'action'=>'TakeposOrderNotes();'); } @@ -784,10 +861,10 @@ if ($conf->global->TAKEPOS_BAR_RESTAURANT) } } -if ($conf->global->TAKEPOSCONNECTOR) { +if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { $menus[$r++] = array('title'=>'
    '.$langs->trans("DOL_OPEN_DRAWER").'
    ', 'action'=>'OpenDrawer();'); } -if ($conf->global->TAKEPOS_DOLIBARR_PRINTER) { +if ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { $menus[$r++] = array( 'title' => '
    '.$langs->trans("DOL_OPEN_DRAWER").'
    ', 'action' => 'DolibarrOpenDrawer();', @@ -802,8 +879,6 @@ if (!empty($reshook)) { if ($r % 3 == 2) $menus[$r++] = array('title'=>'', 'style'=>'visibility: hidden;'); -$menus[$r++] = array('title'=>'
    '.$langs->trans("BackOffice").'
    ', 'action'=>'window.open(\''.(DOL_URL_ROOT ? DOL_URL_ROOT : '/').'\', \'_backoffice\');'); - if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { $menus[$r++] = array('title'=>'
    '.$langs->trans("Logout").'
    ', 'action'=>'window.location.href=\''.DOL_URL_ROOT.'/user/logout.php\';'); } @@ -828,7 +903,7 @@ if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { print ''."\n"; print '
    '; - print ' '; + print ' '; print ''.img_picto('', 'searchclear').''; print '
    '; } @@ -884,15 +959,16 @@ if (!empty($conf->global->TAKEPOS_HIDE_HEAD_BAR)) { '; - echo ''; + print ''; } elseif ($count == ($MAXPRODUCT - 1)) { //echo ''; - echo ''; + print ''; } else { - echo ''; + print '
    '; + print ''; } ?> diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index 77c59b090ca..683b74edc4b 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -37,6 +37,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; +global $mysoc; + $langs->loadLangs(array("companies", "commercial", "bills", "cashdesk", "stocks")); $id = GETPOST('id', 'int'); @@ -45,6 +47,12 @@ $idproduct = GETPOST('idproduct', 'int'); $place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Bar or Restaurant $placeid = 0; // $placeid is ID of invoice +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + + + if ($conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1 && $conf->browser->layout == 'phone') { // DIRECT LINK TO THIS PAGE FROM MOBILE AND NO TERMINAL SELECTED @@ -53,7 +61,7 @@ if ($conf->global->TAKEPOS_PHONE_BASIC_LAYOUT == 1 && $conf->browser->layout == if ($conf->global->TAKEPOS_NUM_TERMINALS == "1") $_SESSION["takeposterminal"] = 1; else { - header("Location: takepos.php"); + header("Location: ".DOL_URL_ROOT."/takepos/index.php"); exit; } } @@ -168,9 +176,15 @@ if ($action == 'valid' && $user->rights->facture->creer) $invoice->update($user); } + //$sav_FACTURE_ADDON = ''; + //if (!empty($conf->global->TAKEPOS_ADDON)) { + // $sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON; + // if ($conf->global->TAKEPOS_ADDON == "terminal") $conf->global->FACTURE_ADDON = $conf->global->{'TAKEPOS_ADDON'.$_SESSION["takeposterminal"]}; + // else $conf->global->FACTURE_ADDON = $conf->global->TAKEPOS_ADDON; + //} + $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.$_SESSION["takeposterminal"]; - if ($invoice->statut != Facture::STATUS_DRAFT) - { + if ($invoice->statut != Facture::STATUS_DRAFT) { //If invoice is validated but it is not fully paid is not error and make the payment if ($invoice->getRemainToPay() > 0) $res = 1; else { @@ -190,7 +204,12 @@ if ($action == 'valid' && $user->rights->facture->creer) $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; dol_syslog("Validate invoice with stock change into warehouse defined into constant ".$constantforkey." = ".$conf->global->$constantforkey); - $res = $invoice->validate($user, '', $conf->global->$constantforkey); + $batch_rule = 0; + if (!empty($conf->productbatch->enabled) && !empty($conf->global->CASHDESK_FORCE_DECREASE_STOCK)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; + $batch_rule = Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST; + } + $res = $invoice->validate($user, '', $conf->global->$constantforkey, 0, $batch_rule); $conf->global->STOCK_CALCULATE_ON_BILL = $savconst; } @@ -199,6 +218,12 @@ if ($action == 'valid' && $user->rights->facture->creer) $res = $invoice->validate($user); } + // Restore save values + //if (!empty($sav_FACTURE_ADDON)) + //{ + // $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON; + //} + $remaintopay = $invoice->getRemainToPay(); // Add the payment @@ -209,7 +234,8 @@ if ($action == 'valid' && $user->rights->facture->creer) $payment->amounts[$invoice->id] = $amountofpayment; // If user has not used change control, add total invoice payment - if ($amountofpayment == 0) $payment->amounts[$invoice->id] = $remaintopay; + // Or if user has used change control and the amount of payment is higher than remain to pay, add the remain to pay + if ($amountofpayment == 0 || $amountofpayment > $remaintopay) $payment->amounts[$invoice->id] = $remaintopay; $payment->paiementid = $paiementid; $payment->num_payment = $invoice->ref; @@ -222,6 +248,8 @@ if ($action == 'valid' && $user->rights->facture->creer) dol_syslog("Invoice is paid, so we set it to status Paid"); $result = $invoice->set_paid($user); if ($result > 0) $invoice->paye = 1; + // set payment method + $invoice->setPaymentMethods($paiementid); } else { dol_syslog("Invoice is not paid, remain to pay = ".$remaintopay); } @@ -282,7 +310,7 @@ if ($action == "addline") $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $customer, $mysoc, $tva_npr); - if (! empty($conf->global->TAKEPOS_SUPPLEMENTS)) + if (!empty($conf->global->TAKEPOS_SUPPLEMENTS)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $cat = new Categorie($db); @@ -293,12 +321,28 @@ if ($action == "addline") $sql = "SELECT fk_parent_line FROM ".MAIN_DB_PREFIX."facturedet where rowid=$selectedline"; $resql = $db->query($sql); $row = $db->fetch_array($resql); - if ($row[0]==null) $parent_line=$selectedline; - else $parent_line=$row[0]; //If the parent line is already a supplement, add the supplement to the main product + if ($row[0] == null) $parent_line = $selectedline; + else $parent_line = $row[0]; //If the parent line is already a supplement, add the supplement to the main product } } - $idoflineadded = $invoice->addline($prod->description, $price, 1, $tva_tx, $localtax1_tx, $localtax2_tx, $idproduct, $customer->remise_percent, '', 0, 0, 0, '', $price_base_type, $price_ttc, $prod->type, -1, 0, '', 0, $parent_line, null, 0, '', 0, 100, '', null, 0); + $idoflineadded = 0; + if (!empty($conf->global->TAKEPOS_GROUP_SAME_PRODUCT)) { + foreach ($invoice->lines as $line) { + if ($line->product_ref == $prod->ref) { + $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty+1, $line->remise_percent, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + if ($result < 0) { + dol_htmloutput_errors($invoice->error, $invoice->errors, 1); + } else { + $idoflineadded = $line->id; + } + break; + } + } + } + if ($idoflineadded <= 0) { + $idoflineadded = $invoice->addline($prod->description, $price, 1, $tva_tx, $localtax1_tx, $localtax2_tx, $idproduct, $customer->remise_percent, '', 0, 0, 0, '', $price_base_type, $price_ttc, $prod->type, -1, 0, '', 0, $parent_line, null, 0, '', 0, 100, '', null, 0); + } $invoice->fetch($placeid); } @@ -307,7 +351,12 @@ if ($action == "freezone") { $customer = new Societe($db); $customer->fetch($invoice->socid); - $tva_tx = get_default_tva($mysoc, $customer); + $tva_tx = GETPOST('tva_tx', 'alpha'); + if ($tva_tx != '') { + $tva_tx = price2num($tva_tx); + } else { + $tva_tx = get_default_tva($mysoc, $customer); + } // Local Taxes $localtax1_tx = get_localtax($tva_tx, 1, $customer, $mysoc, $tva_npr); @@ -435,12 +484,22 @@ if ($action == "updatereduction") else $result = $invoice->updateline($line->id, $line->desc, $line->multicurrency_subprice, $line->qty, $number, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); } } + $invoice->fetch($placeid); +} elseif ($action == 'update_reduction_global') { + foreach ($invoice->lines as $line) { + $result = $invoice->updateline($line->id, $line->desc, $line->subprice, $line->qty, $number, $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit); + } + $invoice->fetch($placeid); } if ($action == "order" and $placeid != 0) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + if ($conf->global->TAKEPOS_PRINT_METHOD == "receiptprinter") { + require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php'; + $printer = new dolReceiptPrinter($db); + } $headerorder = '
    '.$langs->trans('Place').' '.$place.'
    '.$langs->trans("Filter").'
    '.$langs->trans("LocalTax1IsUsedES").''; - $this->tpl['localtax'].= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); - $this->tpl['localtax'].= ''.$langs->trans("LocalTax2IsUsedES").''; - $this->tpl['localtax'].= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); - $this->tpl['localtax'].= '
    '.$langs->trans("LocalTax1IsUsedES").''; + $this->tpl['localtax'] .= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); + $this->tpl['localtax'] .= ''.$langs->trans("LocalTax2IsUsedES").''; + $this->tpl['localtax'] .= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); + $this->tpl['localtax'] .= '
    '.$langs->trans("LocalTax1IsUsedES").''; - $this->tpl['localtax'].= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); - $this->tpl['localtax'].= '
    '.$langs->trans("LocalTax1IsUsedES").''; + $this->tpl['localtax'] .= $form->selectyesno('localtax1assuj_value', $this->object->localtax1_assuj, 1); + $this->tpl['localtax'] .= '
    '.$langs->trans("LocalTax2IsUsedES").''; - $this->tpl['localtax'].= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); - $this->tpl['localtax'].= '
    '.$langs->trans("LocalTax2IsUsedES").''; + $this->tpl['localtax'] .= $form->selectyesno('localtax2assuj_value', $this->object->localtax1_assuj, 1); + $this->tpl['localtax'] .= '
    '.$langs->trans("LocalTax1IsUsedES").''.yn($this->object->localtax1_assuj).''.$langs->trans("LocalTax2IsUsedES").''.yn($this->object->localtax2_assuj).'
    '.$langs->trans("LocalTax1IsUsedES").''.yn($this->object->localtax1_assuj).''.$langs->trans("LocalTax2IsUsedES").''.yn($this->object->localtax2_assuj).'
    '.$langs->trans("LocalTax1IsUsedES").''.yn($this->object->localtax1_assuj).'
    '.$langs->trans("LocalTax1IsUsedES").''.yn($this->object->localtax1_assuj).'
    '.$langs->trans("LocalTax2IsUsedES").''.yn($this->object->localtax2_assuj).'
    '.$langs->trans("LocalTax2IsUsedES").''.yn($this->object->localtax2_assuj).'
    '; $footerorder = '
    '.$langs->trans("Label").''.$langs->trans("Qty").'
    '.dol_print_date(dol_now(), 'dayhour').'
    '; @@ -458,13 +517,20 @@ if ($action == "order" and $placeid != 0) $result = array_intersect($catsprinter1, $existing); $count = count($result); if ($count > 0) { - $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='4' where rowid=".$line->id; + $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet set special_code='1' where rowid=".$line->id; //Set to print on printer 1 $db->query($sql); $order_receipt_printer1 .= '
    '.$line->qty; if (!empty($line->array_options['options_order_notes'])) $order_receipt_printer1 .= "
    (".$line->array_options['options_order_notes'].")"; $order_receipt_printer1 .= '
    '.$line->qty; if (!empty($line->array_options['options_order_notes'])) $order_receipt_printer2 .= "
    (".$line->array_options['options_order_notes'].")"; $order_receipt_printer2 .= '
    '; print ''; @@ -750,13 +892,13 @@ if ($placeid > 0) $tmplines = array_reverse($invoice->lines); foreach ($tmplines as $line) { - if ($line->fk_parent_line!=false) + if ($line->fk_parent_line != false) { - $htmlsupplements[$line->fk_parent_line].='fk_parent_line].=' order'; - $htmlsupplements[$line->fk_parent_line].= '" id="'.$line->id.'">'; - $htmlsupplements[$line->fk_parent_line].= 'fk_parent_line] .= ' order'; + $htmlsupplements[$line->fk_parent_line] .= '" id="'.$line->id.'">'; + $htmlsupplements[$line->fk_parent_line] .= '
    '; - $htmlsupplements[$line->fk_parent_line].= img_picto('', 'rightarrow'); + $htmlsupplements[$line->fk_parent_line] .= '
    '; + $htmlsupplements[$line->fk_parent_line] .= img_picto('', 'rightarrow'); if ($line->product_label) $htmlsupplements[$line->fk_parent_line] .= $line->product_label; if ($line->product_label && $line->desc) $htmlsupplements[$line->fk_parent_line] .= '
    '; if ($line->product_label != $line->desc) @@ -795,19 +937,29 @@ if ($placeid > 0) if (empty($line->product_type)) $htmlforlines .= img_object('', 'product').' '; else $htmlforlines .= img_object('', 'service').' '; } - if ($line->product_label) $htmlforlines .= $line->product_label; - if ($line->product_label && $line->desc) $htmlforlines .= '
    '; - if ($line->product_label != $line->desc) - { - $firstline = dolGetFirstLineOfText($line->desc); - if ($firstline != $line->desc) - { - $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); - } - else - { - $htmlforlines .= $line->desc; - } + if (empty($conf->global->TAKEPOS_SHOW_N_FIRST_LINES)) { + $tooltiptext = ''.$langs->trans("Ref").' : '.$line->product_ref.'
    '; + $tooltiptext .= ''.$langs->trans("Label").' : '.$line->product_label.'
    '; + if ($line->product_label != $line->desc) { + if ($line->desc) $tooltiptext .= '
    '; + $tooltiptext .= $line->desc; + } + $htmlforlines .= $form->textwithpicto($line->product_label ? $line->product_label : ($line->product_ref ? $line->product_ref : dolGetFirstLineOfText($line->desc, 1)), $tooltiptext); + } else { + if ($line->product_label) $htmlforlines .= $line->product_label; + if ($line->product_label != $line->desc) + { + if ($line->product_label && $line->desc) $htmlforlines .= '
    '; + $firstline = dolGetFirstLineOfText($line->desc, $conf->global->TAKEPOS_SHOW_N_FIRST_LINES); + if ($firstline != $line->desc) + { + $htmlforlines .= $form->textwithpicto(dolGetFirstLineOfText($line->desc), $line->desc); + } + else + { + $htmlforlines .= $line->desc; + } + } } if (!empty($line->array_options['options_order_notes'])) $htmlforlines .= "
    (".$line->array_options['options_order_notes'].")"; if ($_SESSION["basiclayout"] != 1) @@ -845,55 +997,6 @@ else { // No invoice generated yet print '
    '; -if ($invoice->socid != $conf->global->$constforcompanyid) -{ - print ''; - print '

    '; - print $langs->trans("Customer").': '.$soc->name; - - $constantforkey = 'CASHDESK_NO_DECREASE_STOCK'.$_SESSION["takeposterminal"]; - if (!empty($conf->stock->enabled) && $conf->global->$constantforkey != "1") - { - $constantforkey = 'CASHDESK_ID_WAREHOUSE'.$_SESSION["takeposterminal"]; - $warehouse = new Entrepot($db); - $warehouse->fetch($conf->global->$constantforkey); - print '
    '.$langs->trans("Warehouse").': '.$warehouse->ref; - } - - // Module Adherent - if (!empty($conf->adherent->enabled)) - { - require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - $langs->load("members"); - print '
    '.$langs->trans("Member").': '; - $adh = new Adherent($db); - $result = $adh->fetch('', '', $invoice->socid); - if ($result > 0) - { - $adh->ref = $adh->getFullName($langs); - print $adh->getFullName($langs); - print '
    '.$langs->trans("Type").': '.$adh->type; - if ($adh->datefin) - { - print '
    '.$langs->trans("SubscriptionEndDate").': '.dol_print_date($adh->datefin, 'day'); - if ($adh->hasDelay()) { - print " ".img_warning($langs->trans("Late")); - } - } - else - { - print '
    '.$langs->trans("SubscriptionNotReceived"); - if ($adh->statut > 0) print " ".img_warning($langs->trans("Late")); // displays delay Pictogram only if not a draft and not terminated - } - } - else - { - print ''.$langs->trans("ThirdpartyNotLinkedToMember").''; - } - } - print '

    '; -} - if ($action == "search") { print '
    diff --git a/htdocs/takepos/pay.php b/htdocs/takepos/pay.php index ec619015496..f79e310f36b 100644 --- a/htdocs/takepos/pay.php +++ b/htdocs/takepos/pay.php @@ -38,6 +38,10 @@ $place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place $invoiceid = GETPOST('invoiceid', 'int'); +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + /* * View @@ -214,7 +218,7 @@ else print "var received=0;"; } -
    +
    trans('TotalTTC'); ?>: total_ttc, 1, '', 1, -1, -1) ?>
    @@ -233,7 +237,7 @@ else print "var received=0;";
    -
    +
    "parent.$.colorbox.close();", - "span" => "id='printtext'", - "text" => $langs->trans("Cancel"), + "span" => "id='printtext' style='font-weight: bold; font-size: 18pt;'", + "text" => "X", "class" => "poscolordelete" ), ); $numpad = $conf->global->TAKEPOS_NUMPAD; + +print ''; +print ''; +print ''; ?> - - - 0) { $paycode = $paiements[0]->code; - if ($paycode == 'LIQ') $paycode = 'cash'; - if ($paycode == 'CB') $paycode = 'card'; - if ($paycode == 'CHQ') $paycode = 'cheque'; - ?> - - - - - - - + $payIcon = ''; + if ($paycode == 'LIQ') { + $paycode = 'cash'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + } elseif ($paycode == 'CB') { + $paycode = 'card'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + } elseif ($paycode == 'CHQ') { + $paycode = 'cheque'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + } + + print ''; +} else { + print ''; +} + +print ''; +print ''; +print ''; +?> 1) { $paycode = $paiements[1]->code; - if ($paycode == 'LIQ') $paycode = 'cash'; - if ($paycode == 'CB') $paycode = 'card'; - if ($paycode == 'CHQ') $paycode = 'cheque'; - ?> - - - - - - - + $payIcon = ''; + if ($paycode == 'LIQ') { + $paycode = 'cash'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + } elseif ($paycode == 'CB') { + $paycode = 'card'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + } elseif ($paycode == 'CHQ') { + $paycode = 'cheque'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + } + + print ''; +} else { + $button = array_pop($action_buttons); + print ''; +} + +print ''; +print ''; +print ''; +?> 2) { $paycode = $paiements[2]->code; - if ($paycode == 'LIQ') $paycode = 'cash'; - if ($paycode == 'CB') $paycode = 'card'; - if ($paycode == 'CHQ') $paycode = 'cheque'; - ?> - -global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'coins'; + } elseif ($paycode == 'CB') { + $paycode = 'card'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'credit-card'; + } elseif ($paycode == 'CHQ') { + $paycode = 'cheque'; + if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) $payIcon = 'money-check'; + } + + print ''; +} else { $button = array_pop($action_buttons); - ?> - - - - - -'.$button["text"].''; +} + +print ''; +print ''; +print ''; + $i = 3; while ($i < count($paiements)) { - ?> - - trans($paiements[$i]->code).'\');">'.$langs->trans("PaymentTypeShort".$paiements[$i]->code).''; $i = $i + 1; } @@ -320,9 +350,7 @@ if ($conf->global->TAKEPOS_ENABLE_SUMUP) { $class = ($i == 3) ? "calcbutton3" : "calcbutton2"; foreach ($action_buttons as $button) { $newclass = $class.($button["class"] ? " ".$button["class"] : ""); - ?> - - '.$button["text"].''; } ?>
    diff --git a/htdocs/takepos/phone.php b/htdocs/takepos/phone.php index 5d0346a495c..c32561d3f52 100644 --- a/htdocs/takepos/phone.php +++ b/htdocs/takepos/phone.php @@ -48,6 +48,11 @@ if ($setterminal > 0) $langs->loadLangs(array("bills", "orders", "commercial", "cashdesk", "receiptprinter")); +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + + /* * View */ diff --git a/htdocs/takepos/receipt.php b/htdocs/takepos/receipt.php index 1df223716fb..31390c347bd 100644 --- a/htdocs/takepos/receipt.php +++ b/htdocs/takepos/receipt.php @@ -34,6 +34,10 @@ $place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place $facid = GETPOST('facid', 'int'); +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + /* * View @@ -85,31 +89,27 @@ if (!empty($hookmanager->resPrint)) {

    global->TAKEPOS_CUSTOM_RECEIPT) +if (!empty($conf->global->TAKEPOS_HEADER)) { $substitutionarray = getCommonSubstitutionArray($langs); if (!empty($conf->global->TAKEPOS_HEADER)) - { - $newfreetext = make_substitutions($conf->global->TAKEPOS_HEADER, $substitutionarray); - echo $newfreetext; - } + $newfreetext = make_substitutions($conf->global->TAKEPOS_HEADER, $substitutionarray); + echo $newfreetext; } ?>

    trans('Date')." ".dol_print_date($object->date, 'day').'
    '; -if ($conf->global->TAKEPOS_CUSTOM_RECEIPT) print $conf->global->TAKEPOS_RECEIPT_NAME." "; +if (!empty($conf->global->TAKEPOS_RECEIPT_NAME)) print $conf->global->TAKEPOS_RECEIPT_NAME." "; if ($object->statut == Facture::STATUS_DRAFT) print str_replace(")", "", str_replace("-", " ".$langs->trans('Place')." ", str_replace("(PROV-POS", $langs->trans("Terminal")." ", $object->ref))); else print $object->ref; -if ($conf->global->TAKEPOS_CUSTOM_RECEIPT && $conf->global->TAKEPOS_SHOW_CUSTOMER) +if ($conf->global->TAKEPOS_SHOW_CUSTOMER) { - $soc = new Societe($db); - $soc->fetch($invoice->socid); - if ($invoice->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}) + if ($object->socid != $conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}) { $soc = new Societe($db); - if ($invoice->socid > 0) $soc->fetch($invoice->socid); + if ($object->socid > 0) $soc->fetch($object->socid); else $soc->fetch($conf->global->{'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]}); print "
    ".$langs->trans("Customer").': '.$soc->name; } @@ -183,13 +183,11 @@ if ($conf->global->TAKEPOS_CUSTOM_RECEIPT && $conf->global->TAKEPOS_SHOW_CUSTOME

    global->TAKEPOS_CUSTOM_RECEIPT) +if (!empty($conf->global->TAKEPOS_FOOTER)) { $substitutionarray = getCommonSubstitutionArray($langs); - if (!empty($conf->global->TAKEPOS_FOOTER)) { - $newfreetext = make_substitutions($conf->global->TAKEPOS_FOOTER, $substitutionarray); - echo $newfreetext; - } + $newfreetext = make_substitutions($conf->global->TAKEPOS_FOOTER, $substitutionarray); + echo $newfreetext; } ?> diff --git a/htdocs/takepos/reduction.php b/htdocs/takepos/reduction.php new file mode 100644 index 00000000000..7ad3e88d2b5 --- /dev/null +++ b/htdocs/takepos/reduction.php @@ -0,0 +1,234 @@ + + * + * 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/takepos/reduction.php + * \ingroup takepos + * \brief Page with the content of the popup to enter reductions + */ + +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Not disabled cause need to load personalized language +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Not disabled cause need to load personalized language +//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'); + +require '../main.inc.php'; // Load $user and permissions +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + +$place = (GETPOST('place', 'int') > 0 ? GETPOST('place', 'int') : 0); // $place is id of table for Ba or Restaurant + +$invoiceid = GETPOST('invoiceid', 'int'); + +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + + +/* + * View + */ + +$invoice = new Facture($db); +if ($invoiceid > 0) +{ + $invoice->fetch($invoiceid); +} +else +{ + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."facture where ref='(PROV-POS".$_SESSION["takeposterminal"]."-".$place.")'"; + $resql = $db->query($sql); + $obj = $db->fetch_object($resql); + if ($obj) + { + $invoiceid = $obj->rowid; + } + if (!$invoiceid) + { + $invoiceid = 0; // Invoice does not exist yet + } + else + { + $invoice->fetch($invoiceid); + } +} + +$arrayofcss = array('/takepos/css/pos.css.php'); +$arrayofjs = array(); + +top_htmlhead($head, '', 0, 0, $arrayofjs, $arrayofcss); + +$langs->loadLangs(array('main', 'bills', 'cashdesk')); + +if (!empty($conf->global->TAKEPOS_NUMPAD_USE_PAYMENT_ICON)) { + $htmlReductionPercent = ''; + $htmlReductionAmount = ''; +} else { + $htmlReductionPercent = $langs->trans('ReductionShort') . '
    %'; + $htmlReductionAmount = $langs->trans('ReductionShort') . '
    ' . $langs->trans('Amount'); +} +?> + + + + + + +

    +
    +trans('Reduction').'">'; +?> +
    +
    + +
    +7'; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +?> +
    + + + diff --git a/htdocs/takepos/send.php b/htdocs/takepos/send.php index 0b16f555e2f..8078ddc1787 100644 --- a/htdocs/takepos/send.php +++ b/htdocs/takepos/send.php @@ -37,6 +37,11 @@ require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $invoiceid = GETPOST('facid', 'int'); +if (empty($user->rights->takepos->run)) { + access_forbidden(); +} + + /* * View */ diff --git a/htdocs/takepos/smpcb.php b/htdocs/takepos/smpcb.php index 445bc6da9cc..6bf81b1cdf6 100644 --- a/htdocs/takepos/smpcb.php +++ b/htdocs/takepos/smpcb.php @@ -1,5 +1,15 @@ rights->takepos->run)) { + access_forbidden(); +} if (isset($_GET['status'])) { die(strtoupper($_SESSION['SMP_CURRENT_PAYMENT'])); diff --git a/htdocs/theme/dolibarr_logo.svg b/htdocs/theme/dolibarr_logo.svg new file mode 100644 index 00000000000..44f6c07ece5 --- /dev/null +++ b/htdocs/theme/dolibarr_logo.svg @@ -0,0 +1,439 @@ + + + + + Logo Dolibarr ERP-CRM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Dolibarr + + + + + + Dolibarr + + + + + + + + + + + + image/svg+xml + + Logo Dolibarr ERP-CRM + + + + Laurent Destailleur + + + + + Laurent Destailleur + + + + + + + + + + + + + + + + + + + + + + + + + + + ERP/CRM + + + diff --git a/htdocs/theme/eldy/badges.inc.php b/htdocs/theme/eldy/badges.inc.php index db7802074c1..48619dfc7d0 100644 --- a/htdocs/theme/eldy/badges.inc.php +++ b/htdocs/theme/eldy/badges.inc.php @@ -23,7 +23,7 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> } .badge-status { - font-size: 1em; + font-size: 0.95em; padding: .19em .35em; /* more than 0.19 generate a change into heigth of lines */ } diff --git a/htdocs/theme/eldy/btn.inc.php b/htdocs/theme/eldy/btn.inc.php index edf40cf2b52..4831bb40c4a 100644 --- a/htdocs/theme/eldy/btn.inc.php +++ b/htdocs/theme/eldy/btn.inc.php @@ -2,6 +2,32 @@ if (!defined('ISLOADEDBYSTEELSHEET')) die('Must be call by steelsheet'); ?> /* '; $out .= '
      '; + if ($languagecodeselected) { - $shortcode = strtolower(substr($languagecodeselected, -2)); + // Convert $languagecodeselected into a long language code + if (strlen($languagecodeselected) == 2) { + $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]); + } + + $countrycode = strtolower(substr($languagecodeselected, -2)); $label = $weblangs->trans("Language_".$languagecodeselected); - if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); - $out .= '
    • '.$label; + if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + $out .= '
    • '.$label.''; $out .= ''; $out .= '
    • '; } @@ -1302,11 +1418,17 @@ class Website extends CommonObject { foreach ($languagecodes as $languagecode) { + // Convert $languagecode into a long language code + if (strlen($languagecode) == 2) { + $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]); + } + if ($languagecode == $languagecodeselected) continue; // Already output - $shortcode = strtolower(substr($languagecode, -2)); + + $countrycode = strtolower(substr($languagecode, -2)); $label = $weblangs->trans("Language_".$languagecode); - if ($shortcode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); - $out .= '
    • '.$label; + if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + $out .= '
    • '.$label.''; if (empty($i) && empty($languagecodeselected)) $out .= ''; $out .= '
    • '; $i++; diff --git a/htdocs/website/class/websitepage.class.php b/htdocs/website/class/websitepage.class.php index e260ddea3a3..7d1f345d8c2 100644 --- a/htdocs/website/class/websitepage.class.php +++ b/htdocs/website/class/websitepage.class.php @@ -98,6 +98,11 @@ class WebsitePage extends CommonObject */ public $date_modification; + /** + * @var string author_alias + */ + public $author_alias; + const STATUS_DRAFT = 0; const STATUS_VALIDATED = 1; @@ -128,7 +133,8 @@ class WebsitePage extends CommonObject 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>501), //'date_valid' =>array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>502), 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'notnull'=>true, 'position'=>510), - 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'position'=>511), + 'author_alias' =>array('type'=>'varchar(64)', 'label'=>'AuthorAlias', 'enabled'=>1, 'visible'=>-1, 'index'=>0, 'position'=>511, 'comment'=>'Author alias'), + 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-1, 'position'=>512), //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512), 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'index'=>1, 'position'=>1000, 'notnull'=>-1), ); @@ -158,6 +164,9 @@ class WebsitePage extends CommonObject $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + // Remove spaces and be sure we have main language only + $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en + return $this->createCommon($user, $notrigger); } @@ -168,7 +177,7 @@ class WebsitePage extends CommonObject * - If this is 0, the value into $page will be used. If not found or $page not defined, the default page of website_id will be used or the first page found if not set. * - If value is < 0, we must exclude this ID. * @param string $website_id Web site id (page name must also be filled if this parameter is used) - * @param string $page Page name (website id must also be filled if this parameter is used) + * @param string $page Page name (website id must also be filled if this parameter is used). Exemple 'myaliaspage' or 'fr/myaliaspage' * @param string $aliasalt Alternative alias to search page (slow) * * @return int <0 if KO, 0 if not found, >0 if OK @@ -196,6 +205,7 @@ class WebsitePage extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification,"; $sql .= " t.fk_user_creat,"; + $sql .= " t.author_alias,"; $sql .= " t.fk_user_modif"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; //$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level @@ -209,7 +219,17 @@ class WebsitePage extends CommonObject if ($id < 0) $sql .= ' AND t.rowid <> '.abs($id); if (null !== $website_id) { $sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'"; - if ($page) $sql .= " AND t.pageurl = '".$this->db->escape($page)."'"; + if ($page) { + $pagetouse = $page; + $langtouse = ''; + $tmppage = explode('/', $page); + if (! empty($tmppage[1])) { + $pagetouse = $tmppage[1]; + if (strlen($tmppage[0])) $langtouse = $tmppage[0]; + } + $sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'"; + if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; + } if ($aliasalt) $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')"; } } @@ -243,6 +263,7 @@ class WebsitePage extends CommonObject $this->date_creation = $this->db->jdate($obj->date_creation); $this->date_modification = $this->db->jdate($obj->date_modification); $this->fk_user_creat = $obj->fk_user_creat; + $this->author_alias = $obj->author_alias; $this->fk_user_modif = $obj->fk_user_modif; } $this->db->free($resql); @@ -261,7 +282,7 @@ class WebsitePage extends CommonObject } /** - * Load list of objects in memory from the database. + * Return array of all web site pages. * * @param string $websiteid Web site * @param string $sortorder Sort Order @@ -297,6 +318,7 @@ class WebsitePage extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.tms as date_modification,"; $sql .= " t.fk_user_creat,"; + $sql .= " t.author_alias,"; $sql .= " t.fk_user_modif"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' WHERE t.fk_website = '.$websiteid; @@ -306,6 +328,8 @@ class WebsitePage extends CommonObject foreach ($filter as $key => $value) { if ($key == 't.rowid' || $key == 't.fk_website') { $sqlwhere[] = $key.'='.$value; + } elseif ($key == 'lang' || $key == 't.lang') { + $sqlwhere[] = $key." = '".$this->db->escape(substr($value, 0, 2))."'"; } else { $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; } @@ -348,6 +372,7 @@ class WebsitePage extends CommonObject $record->date_creation = $this->db->jdate($obj->date_creation); $record->date_modification = $this->db->jdate($obj->date_modification); $record->fk_user_creat = $obj->fk_user_creat; + $record->author_alias = $obj->author_alias; $record->fk_user_modif = $obj->fk_user_modif; //var_dump($record->id); $records[$record->id] = $record; @@ -364,6 +389,59 @@ class WebsitePage extends CommonObject } } + /** + * Count objects in the database. + * + * @param string $websiteid Web site + * @param array $filter Filter array + * @param string $filtermode Filter mode (AND or OR) + * @return int int <0 if KO, array of pages if OK + */ + public function countAll($websiteid, array $filter = array(), $filtermode = 'AND') + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $result = 0; + + $sql = 'SELECT COUNT(t.rowid) as nb'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; + $sql .= ' WHERE t.fk_website = '.$websiteid; + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key == 't.rowid' || $key == 't.fk_website') { + $sqlwhere[] = $key.'='.$value; + } elseif ($key == 'lang' || $key == 't.lang') { + $sqlwhere[] = $key." = '".$this->db->escape(substr($value, 0, 2))."'"; + } else { + $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; + } + } + } + if (count($sqlwhere) > 0) { + $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')'; + } + + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + if ($obj) { + $result = $obj->nb; + } + + $this->db->free($resql); + + return $result; + } else { + $this->error = 'Error '.$this->db->lasterror(); + $this->errors[] = $this->error; + dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); + + return -1; + } + } + /** * Update object into database * @@ -377,6 +455,22 @@ class WebsitePage extends CommonObject $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + // Remove spaces and be sure we have main language only + $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en + + if ($this->fk_page > 0) { + if (empty($this->lang)) { + $this->error = "ErrorLanguageMandatoryIfPageSetAsTranslationOfAnother"; + return -1; + } + $tmppage = new WebsitePage($this->db); + $tmppage->fetch($this->fk_page); + if ($tmppage->lang == $this->lang) { + $this->error = "ErrorLanguageOfTranslatedPageIsSameThanThisPage"; + return -1; + } + } + return $this->updateCommon($user, $notrigger); } @@ -459,6 +553,7 @@ class WebsitePage extends CommonObject $object->pageurl = $newref; $object->aliasalt = ''; $object->fk_user_creat = $user->id; + $object->author_alias = ''; $object->date_creation = $now; $object->title = ($newtitle == '1' ? $object->title : ($newtitle ? $newtitle : $object->title)); if (!empty($newlang)) $object->lang = $newlang; @@ -513,7 +608,8 @@ class WebsitePage extends CommonObject $label .= '
      '; $label .= ''.$langs->trans('Ref').': '.$this->ref.'
      '; $label .= ''.$langs->trans('ID').': '.$this->id.'
      '; - $label .= ''.$langs->trans('Title').': '.$this->title; + $label .= ''.$langs->trans('Title').': '.$this->title.'
      '; + $label .= ''.$langs->trans('Language').': '.$this->lang; $url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id; @@ -614,5 +710,6 @@ class WebsitePage extends CommonObject $this->date_creation = $now - (24 * 30 * 3600); $this->date_modification = $now - (24 * 7 * 3600); $this->fk_user_creat = $user->id; + $this->author_alias = 'mypublicpseudo'; } } diff --git a/htdocs/website/index.php b/htdocs/website/index.php index 85b50b3d13b..0ce0e2f1bbd 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2016-2020 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,7 +24,7 @@ define('NOSCANPOSTFORINJECTION', 1); define('NOSTYLECHECK', 1); define('USEDOLIBARREDITOR', 1); -define('FORCE_CKEDITOR', 1); // We need CKEditor, even if module is off. +define('FORCE_CKEDITOR', 1); // We need CKEditor, even if module is off. //header('X-XSS-Protection:0'); // Disable XSS filtering protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated. @@ -40,56 +40,56 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; -$langs->loadLangs(array("admin","other","website","errors")); +$langs->loadLangs(array("admin", "other", "website", "errors")); -if (! $user->rights->website->read) accessforbidden(); +if (!$user->rights->website->read) accessforbidden(); -$conf->dol_hide_leftmenu = 1; // Force hide of left menu. +$conf->dol_hide_leftmenu = 1; // Force hide of left menu. -$error=0; -$websiteid=GETPOST('websiteid', 'int'); -$websitekey=GETPOST('website', 'alpha'); -$page=GETPOST('page', 'alpha'); -$pageid=GETPOST('pageid', 'int'); -$pageref=GETPOST('pageref', 'aZ09'); -$action=GETPOST('action', 'aZ09'); -$confirm=GETPOST('confirm', 'alpha'); -$cancel=GETPOST('cancel', 'alpha'); -$contextpage= GETPOST('contextpage', 'aZ')?GETPOST('contextpage', 'aZ'):'bomlist'; // 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') +$error = 0; +$websiteid = GETPOST('websiteid', 'int'); +$websitekey = GETPOST('website', 'alpha'); +$page = GETPOST('page', 'alpha'); +$pageid = GETPOST('pageid', 'int'); +$pageref = GETPOST('pageref', 'alphanohtml'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomlist'; // 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') -$type_container=GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha'); +$type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha'); $section_dir = GETPOST('section_dir', 'alpha'); $file_manager = GETPOST('file_manager', 'alpha'); $replacesite = GETPOST('replacesite', 'alpha'); -if (GETPOST('deletesite', 'alpha')) { $action='deletesite'; } -if (GETPOST('delete', 'alpha')) { $action='delete'; } -if (GETPOST('preview', 'alpha')) $action='preview'; -if (GETPOST('createsite', 'alpha')) { $action='createsite'; } -if (GETPOST('createcontainer', 'alpha')) { $action='createcontainer'; } -if (GETPOST('editcss', 'alpha')) { $action='editcss'; } -if (GETPOST('editmenu', 'alpha')) { $action='editmenu'; } -if (GETPOST('setashome', 'alpha')) { $action='setashome'; } -if (GETPOST('editmeta', 'alpha')) { $action='editmeta'; } -if (GETPOST('editsource', 'alpha')) { $action='editsource'; } -if (GETPOST('editcontent', 'alpha')) { $action='editcontent'; } -if (GETPOST('exportsite', 'alpha')) { $action='exportsite'; } -if (GETPOST('importsite', 'alpha')) { $action='importsite'; } -if (GETPOST('createfromclone', 'alpha')) { $action='createfromclone'; } -if (GETPOST('createpagefromclone', 'alpha')) { $action='createpagefromclone'; } -if (empty($action) && $file_manager) $action='file_manager'; -if (empty($action) && $replacesite) $action='replacesite'; +if (GETPOST('deletesite', 'alpha')) { $action = 'deletesite'; } +if (GETPOST('delete', 'alpha')) { $action = 'delete'; } +if (GETPOST('preview', 'alpha')) $action = 'preview'; +if (GETPOST('createsite', 'alpha')) { $action = 'createsite'; } +if (GETPOST('createcontainer', 'alpha')) { $action = 'createcontainer'; } +if (GETPOST('editcss', 'alpha')) { $action = 'editcss'; } +if (GETPOST('editmenu', 'alpha')) { $action = 'editmenu'; } +if (GETPOST('setashome', 'alpha')) { $action = 'setashome'; } +if (GETPOST('editmeta', 'alpha')) { $action = 'editmeta'; } +if (GETPOST('editsource', 'alpha')) { $action = 'editsource'; } +if (GETPOST('editcontent', 'alpha')) { $action = 'editcontent'; } +if (GETPOST('exportsite', 'alpha')) { $action = 'exportsite'; } +if (GETPOST('importsite', 'alpha')) { $action = 'importsite'; } +if (GETPOST('createfromclone', 'alpha')) { $action = 'createfromclone'; } +if (GETPOST('createpagefromclone', 'alpha')) { $action = 'createpagefromclone'; } +if (empty($action) && $file_manager) $action = 'file_manager'; +if (empty($action) && $replacesite) $action = 'replacesite'; if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) $pageid = 0; // Load variable for pagination -$limit = GETPOST('limit', 'int')?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'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; @@ -267,9 +267,9 @@ $manifestjsoncontentdefault .= '{ */ // Protections -if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) +if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) { - $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page. + $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page. } if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) // If we change the site, we reset the pageid and cancel addsite action. { @@ -279,20 +279,20 @@ if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETP $pageid = $object->fk_default_home; if (empty($pageid)) { - $array=$objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); + $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); + if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage = (is_array($array) && count($array) > 0); - $firstpageid=0; $homepageid=0; - foreach($array as $key => $valpage) + $firstpageid = 0; $homepageid = 0; + foreach ($array as $key => $valpage) { - if (empty($firstpageid)) $firstpageid=$valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid=$valpage->id; + if (empty($firstpageid)) $firstpageid = $valpage->id; + if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id; } - $pageid=($homepageid?$homepageid:$firstpageid); // We choose home page and if not defined yet, we take first page + $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page } } -if (GETPOST('refreshpage', 'alpha') && ! in_array($action, array('updatecss'))) $action='preview'; +if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) $action = 'preview'; // Cancel if ($cancel) @@ -396,9 +396,16 @@ if ($action == 'addsite') if (!$error) { + $arrayotherlang=explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); + foreach($arrayotherlang as $key => $val) { + $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only + } + $tmpobject = new Website($db); $tmpobject->ref = GETPOST('WEBSITE_REF', 'alpha'); - $tmpobject->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + $tmpobject->description = GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'); + $tmpobject->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $tmpobject->otherlang = join(',', $arrayotherlang); $tmpobject->virtualhost = GETPOST('virtualhost', 'alpha'); $result = $tmpobject->create($user); @@ -777,15 +784,17 @@ if ($action == 'addcontainer') } else { - $objectpage->title = GETPOST('WEBSITE_TITLE', 'alpha'); - $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha'); + $objectpage->title = GETPOST('WEBSITE_TITLE', 'alphanohtml'); + $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'aZ09'); $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); - $objectpage->aliasalt = GETPOST('WEBSITE_ALIASALT', 'alpha'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); + $objectpage->aliasalt = GETPOST('WEBSITE_ALIASALT', 'alphanohtml'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'); $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $objectpage->otherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alphanohtml'); $objectpage->htmlheader = GETPOST('htmlheader', 'none'); + $objectpage->author_alias = GETPOST('WEBSITE_AUTHORALIAS', 'alphanohtml'); $substitutionarray = array(); $substitutionarray['__WEBSITE_CREATE_BY__'] = $user->getFullName($langs); @@ -841,6 +850,13 @@ if ($action == 'addcontainer') { $error++; setEventMessages($object->error, $object->errors, 'errors'); + } else { + $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php'; + + // Generate the index.php page to be the home page + $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); + + if ($result <= 0) setEventMessages('Failed to write file '.$fileindex, null, 'errors'); } } } @@ -857,7 +873,7 @@ if ($action == 'addcontainer') $result = dolSavePageAlias($filealias, $object, $objectpage); if (!$result) { - setEventMessages('Failed to write file '.$filealias, null, 'errors'); + setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } // Save page of content @@ -1035,7 +1051,7 @@ if ($action == 'delete') } } -// Update css +// Update css Update site properties if ($action == 'updatecss') { // If we tried to reload another site/page, we stay on editcss mode. @@ -1059,7 +1075,14 @@ if ($action == 'updatecss') if (!$error) { + $arrayotherlang=explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); + foreach($arrayotherlang as $key => $val) { + $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only + } + $object->virtualhost = GETPOST('virtualhost', 'alpha'); + $object->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $object->otherlang = join(',', $arrayotherlang); $object->use_manifest = GETPOST('use_manifest', 'alpha'); $result = $object->update($user); @@ -1312,8 +1335,9 @@ if ($action == 'setashome') { $db->commit(); + $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php'; + // Generate the index.php page to be the home page - //------------------------------------------------- $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); @@ -1403,16 +1427,18 @@ if ($action == 'updatemeta') { $objectpage->old_object = clone $objectpage; - $objectpage->title = GETPOST('WEBSITE_TITLE', 'alpha'); - $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha'); + $objectpage->title = GETPOST('WEBSITE_TITLE', 'alphanohtml'); + $objectpage->type_container = GETPOST('WEBSITE_TYPE_CONTAINER', 'alphanohtml'); $objectpage->pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); $objectpage->aliasalt = GETPOST('WEBSITE_ALIASALT', 'alpha'); - $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha'); - $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alpha'); $objectpage->lang = GETPOST('WEBSITE_LANG', 'aZ09'); + $objectpage->otherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + $objectpage->description = GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml'); + $objectpage->image = GETPOST('WEBSITE_IMAGE', 'alpha'); + $objectpage->keywords = GETPOST('WEBSITE_KEYWORDS', 'alphanohtml'); $objectpage->htmlheader = trim(GETPOST('htmlheader', 'none')); $objectpage->fk_page = (GETPOST('pageidfortranslation', 'int') > 0 ? GETPOST('pageidfortranslation', 'int') : 0); + $objectpage->author_alias = trim(GETPOST('WEBSITE_AUTHORALIAS', 'alphanohtml')); $newdatecreation = dol_mktime(GETPOST('datecreationhour', 'int'), GETPOST('datecreationmin', 'int'), GETPOST('datecreationsec', 'int'), GETPOST('datecreationmonth', 'int'), GETPOST('datecreationday', 'int'), GETPOST('datecreationyear', 'int')); if ($newdatecreation) $objectpage->date_creation = $newdatecreation; @@ -1493,8 +1519,9 @@ if ($action == 'updatemeta') { if (trim($tmpaliasalt)) { - $result = dolSavePageAlias($pathofwebsite.'/'.trim($tmpaliasalt).'.php', $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.$pathofwebsite.'/'.trim($tmpaliasalt).'.php', null, 'errors'); + $filealias = $pathofwebsite.'/'.trim($tmpaliasalt).'.php'; + $result = dolSavePageAlias($filealias, $object, $objectpage); + if (!$result) setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } } } @@ -1750,7 +1777,7 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (!$result) setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); // Save page content $result = dolSavePageContent($filetpl, $object, $objectpage); @@ -2026,8 +2053,8 @@ if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource') if (!GETPOST('hide_websitemenu')) { - $disabled=''; - if (empty($user->rights->website->write)) $disabled=' disabled="disabled"'; + $disabled = ''; + if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; //var_dump($objectpage);exit; print '
      '; @@ -2047,7 +2074,7 @@ if (!GETPOST('hide_websitemenu')) // List of website print ''; $out = ''; - $out .= ''; if (empty($object->records)) $out .= ''; // Loop on each sites $i = 0; @@ -2071,19 +2098,19 @@ if (!GETPOST('hide_websitemenu')) if ($websitekey) { - $virtualurl=''; - $dataroot=DOL_DATA_ROOT.'/website/'.$websitekey; - if (! empty($object->virtualhost)) $virtualurl=$object->virtualhost; + $virtualurl = ''; + $dataroot = DOL_DATA_ROOT.'/website/'.$websitekey; + if (!empty($object->virtualhost)) $virtualurl = $object->virtualhost; } - $array=array(); + $array = array(); if ($object->id > 0) { - $array=$objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); + $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); $object->lines = $array; } - if (! is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); - $atleastonepage=(is_array($array) && count($array) > 0); + if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + $atleastonepage = (is_array($array) && count($array) > 0); if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { @@ -2170,7 +2197,26 @@ if (!GETPOST('hide_websitemenu')) $htmltext .= '
      '; $htmltext .= '
      '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); $htmltext .= '
      '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website
      '.DOL_DATA_ROOT.'/medias'); - $htmltext .= '
      '; + + $examplewithapache = ''."\n"; + $examplewithapache .= 'AllowOverride FileInfo Options + Options -Indexes -MultiViews -FollowSymLinks -ExecCGI + Require all granted + + + AllowOverride FileInfo Options + Options -Indexes -MultiViews +FollowSymLinks -ExecCGI + Require all granted + + + AllowOverride FileInfo Options + Options -Indexes -MultiViews -FollowSymLinks -ExecCGI + Require all granted + '; + + $htmltext .= '
      '.$langs->trans("ExampleToUseInApacheVirtualHostConfig").':
      '; + $htmltext .= '
      '.dol_nl2br(dol_escape_htmltag($examplewithapache, 1, 1)).'
      '; + $htmltext .= '
      '; $htmltext .= $langs->trans("YouCanAlsoTestWithPHPS", $dataroot); $htmltext .= '
      '; @@ -2214,7 +2260,7 @@ if (!GETPOST('hide_websitemenu')) if ($action != 'addcontainer') { - print ''.$formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action).''; + print ''.$formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action, 'maxwidth200onsmartphone').''; } else { @@ -2346,7 +2392,7 @@ if (!GETPOST('hide_websitemenu')) if (! isEditingEnabled || forceenable) { console.log("Enable inline edit"); - jQuery(\'section[contenteditable="true"]\').each(function(idx){ + jQuery(\'section[contenteditable="true"],div[contenteditable="true"]\').each(function(idx){ var idtouse = $(this).attr(\'id\'); console.log("Enable inline edit for "+idtouse); CKEDITOR.inline(idtouse, { @@ -2375,7 +2421,9 @@ if (!GETPOST('hide_websitemenu')) print $langs->trans("EditInLine"); print '
      '; - if ($websitepage->grabbed_from) + //$disableeditinline = $websitepage->grabbed_from; + $disableeditinline = 0; + if ($disableeditinline) { //print ''; print ''.img_picto($langs->trans("OnlyEditionOfSourceForGrabbedContent"), 'switch_off', '', false, 0, 0, '', 'nomarginleft').''; @@ -2396,12 +2444,6 @@ if (!GETPOST('hide_websitemenu')) print '
      '; print '
      '; print $langs->trans("ShowSubcontainers"); - /*if ($websitepage->grabbed_from) - { - print ''.img_picto($langs->trans("OnlyEditionOfSourceForGrabbedContent"),'switch_off','',false,0,0,'','nomarginleft').''; - } - else - {*/ if (empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { print ''.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').''; @@ -2446,16 +2488,19 @@ if (!GETPOST('hide_websitemenu')) $htmltext .= '
      '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); $htmltext .= '
      '.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("WritePerm"), DOL_DATA_ROOT.'/website
      '.DOL_DATA_ROOT.'/medias'); - print ''; + print ''; - print '
      '; + /*print '
      '; print ''; $htmltext = $langs->trans("PageNameAliasHelp", $langs->transnoentitiesnoconv("EditPageMeta")); print $form->textwithpicto('', $htmltext, 1, 'help', '', 0, 2, 'helppagealias'); - print '
      '; + print '
      ';*/ + /* $urlext = $virtualurl.'/'.$pagealias.'.php'; $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey; @@ -2464,6 +2509,7 @@ if (!GETPOST('hide_websitemenu')) print ''; print $form->textwithpicto('', $htmltext, 1, 'preview_ext'); print ''; + */ //print ''; // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext @@ -2685,12 +2731,30 @@ if ($action == 'editcss') print ''; // Website - print ''; + // Main language + print ''; + print ''; + + // Other languages + print ''; + print ''; + // VirtualHost print '
      '; + print '
      '; print $langs->trans('WebSite'); print ''; print $websitekey; print '
      '; + $htmltext=''; + print $form->textwithpicto($langs->trans('MainLanguage'), $htmltext, 1, 'help', '', 0, 2, 'WEBSITE_LANG'); + print ''; + print $formadmin->select_language((GETPOSTISSET('WEBSITE_LANG') ? GETPOST('WEBSITE_LANG', 'aZ09comma') : ($object->lang ? $object->lang : '0')), 'WEBSITE_LANG', 0, null, 1, 0, 0, 'minwidth300', 2, 0, 0, array(), 1); + print '
      '; + $htmltext = ''; + print $form->textwithpicto($langs->trans('OtherLanguages'), $htmltext, 1, 'help', '', 0, 2, 'WEBSITE_OTHERLANG'); + print ''; + print ''; + print '
      '; @@ -2816,8 +2880,11 @@ if ($action == 'createsite') print ''; + $siteref = $sitedesc = $sitelang = $siteotherlang = ''; if (GETPOST('WEBSITE_REF')) $siteref = GETPOST('WEBSITE_REF', 'alpha'); if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + if (GETPOST('WEBSITE_LANG')) $sitelang = GETPOST('WEBSITE_LANG', 'aZ09'); + if (GETPOST('WEBSITE_OTHERLANG')) $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); print ''; + print ''; + print ''; + + print ''; print ''; // Translation of @@ -3136,6 +3236,12 @@ if ($action == 'editmeta' || $action == 'createcontainer') } print ''; + print ''; + print ''; print ''; print ''; print '
      '; print $langs->trans('Ref'); @@ -2825,10 +2892,23 @@ if ($action == 'createsite') print ''; print '
      '; + print $langs->trans('MainLanguage'); + print ''; + $shortlangcode = preg_replace('/[_-].*$/', '', trim($langs->defaultlang)); + print $formadmin->select_language((GETPOSTISSET('WEBSITE_LANG') ? GETPOST('WEBSITE_LANG', 'aZ09comma') : $shortlangcode), 'WEBSITE_LANG', 0, null, 1, 0, 0, 'minwidth300', 2, 0, 0, array(), 1); + print '
      '; print $langs->trans('Description'); print ''; - print ''; + print ''; + print '
      '; + print $langs->trans('OtherLanguages'); + print ''; + print ''; print '
      '; @@ -2988,6 +3068,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') $pagedatemodification = $objectpage->date_modification; $pageauthorid = $objectpage->fk_user_creat; $pageusermodifid = $objectpage->fk_user_modif; + $pageauthoralias = $objectpage->author_alias; } else { @@ -2995,6 +3076,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') $pagedatecreation = dol_now(); $pageauthorid = $user->id; $pageusermodifid = 0; + $pageauthoralias = ''; } if (GETPOST('WEBSITE_TITLE', 'alpha')) $pagetitle = GETPOST('WEBSITE_TITLE', 'alpha'); if (GETPOST('WEBSITE_PAGENAME', 'alpha')) $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); @@ -3057,7 +3139,25 @@ if ($action == 'editmeta' || $action == 'createcontainer') print '
      '; print $langs->trans('Language'); print ''; - print $formadmin->select_language($pagelang ? $pagelang : $langs->defaultlang, 'WEBSITE_LANG', 0, null, '1', 0, 0, 'minwidth200'); + $onlykeys = array(); + if ($object->lang) $onlykeys[$object->lang] = $object->lang; + else $onlykeys[$langs->defaultlang] = $langs->defaultlang; + if ($object->otherlang) { + $tmparray = explode(',', $object->otherlang); + foreach ($tmparray as $key) { + $tmpkey = trim($key); + if (strlen($key) == 2) { + $tmpkey = strtolower($key); + } + $onlykeys[$tmpkey] = $tmpkey; + } + } + if (empty($object->lang) && empty($object->otherlang)) { + $onlykeys = null; // We keep full list of languages + } + print $formadmin->select_language($pagelang ? $pagelang : '', 'WEBSITE_LANG', 0, null, '1', 0, 0, 'minwidth200', 0, 0, 0, $onlykeys, 1); + $htmltext = $langs->trans("AvailableLanguagesAreDefinedIntoWebsiteProperties"); + print $form->textwithpicto('', $htmltext); print '
      '; + print $langs->trans('PublicAuthorAlias'); + print ''; + print ''; + print '
      '; print $langs->trans('DateCreation'); print ''; @@ -3380,7 +3486,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') { print '
      '.$langs->trans("Container").' - '; - print $langs->trans($answerrecord->type_container); // TODO Use label of container + print $langs->trans($answerrecord->type_container); // TODO Use label of container print ''; print $answerrecord->getNomUrl(1); @@ -3389,6 +3495,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') print ''.$answerrecord->description.''; $param = '?action=replacesiteconfirm'; + $param .= '&websiteid='.$website->id; $param .= '&optioncontent='.GETPOST('optioncontent'); $param .= '&optionmeta='.GETPOST('optionmeta'); $param .= '&optionsitefiles='.GETPOST('optionsitefiles'); @@ -3417,7 +3524,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm') 'website_readme'=>'WEBSITE_README', 'website_manifestjson'=>'WEBSITE_MANIFEST_JSON' ); - if (! empty($translateofrecordtype[$answerrecord['type']])) { + if (!empty($translateofrecordtype[$answerrecord['type']])) { print $langs->trans($translateofrecordtype[$answerrecord['type']]); } else { print $answerrecord['type']; @@ -3535,10 +3642,20 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa // If mode WEBSITE_SUBCONTAINERSINLINE is on if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { + // TODO Check file $filephp exists, if not create it. + //var_dump($filetpl); $filephp = $filetpl; ob_start(); - include $filephp; + try { + $res = include $filephp; + if (empty($res)) { + print "ERROR: Failed to include file '".$filephp."'. Try to edit and save page."; + } + } catch(Exception $e) + { + print $e->getMessage(); + } $newcontent = ob_get_contents(); ob_end_clean(); } diff --git a/htdocs/website/samples/wrapper.html b/htdocs/website/samples/wrapper.php similarity index 57% rename from htdocs/website/samples/wrapper.html rename to htdocs/website/samples/wrapper.php index 7a3932c1608..8f38c0b2043 100644 --- a/htdocs/website/samples/wrapper.html +++ b/htdocs/website/samples/wrapper.php @@ -5,11 +5,17 @@ if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_ include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $encoding = ''; + +// Parameters to download files $hashp=GETPOST('hashp', 'aZ09'); $modulepart=GETPOST('modulepart', 'aZ09'); $entity=GETPOST('entity', 'int')?GETPOST('entity', 'int'):$conf->entity; $original_file=GETPOST("file", "alpha"); +// Parameters for RSS +$rss=GETPOST('rss', 'aZ09'); +if ($rss) $original_file = 'blog.rss'; + // If we have a hash public (hashp), we guess the original_file. if (! empty($hashp)) { @@ -60,7 +66,7 @@ if (! empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) $attachment=false // Define mime type $type = 'application/octet-stream'; -if (GETPOST('type','none')) $type=GETPOST('type', 'alpha'); +if (GETPOSTISSET('type')) $type=GETPOST('type', 'alpha'); else $type=dol_mimetype($original_file); // Security: Delete string ../ into $original_file @@ -75,26 +81,119 @@ if (GETPOST("cache",'none') || image_format_supported($original_file) >= 0) header('Pragma: cache'); // This is to avoid having Pragma: no-cache } -// Find the subdirectory name as the reference $refname=basename(dirname($original_file)."/"); -if ($_GET["modulepart"] == "mycompany" && preg_match('/^\/?logos\//', $original_file)) +// Get RSS news +if ($rss) { + $format = 'rss'; + $type = ''; + $cachedelay = 0; + $filename = $original_file; + $filters = array('type_container'=>'blogpost', 'lang'=>'en_US'); + $dir_temp = $conf->website->dir_temp; + include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; + include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; + $website = new Website($db); + $websitepage = new WebsitePage($db); + + $website->fetch('', $websitekey); + + $MAXNEWS = 20; + $arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters); + $eventarray = $arrayofblogs; + + require_once DOL_DOCUMENT_ROOT."/core/lib/xcal.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; + require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; + + dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); + + // Check parameters + if (empty($format)) return -1; + + // Clean parameters + if (!$filename) + { + $extension = 'vcs'; + if ($format == 'ical') $extension = 'ics'; + $filename = $format.'.'.$extension; + } + + // Create dir and define output file (definitive and temporary) + $result = dol_mkdir($dir_temp); + $outputfile = $dir_temp.'/'.$filename; + + $result = 0; + + $buildfile = true; + + if ($cachedelay) + { + $nowgmt = dol_now(); + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) + { + dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); + $buildfile = false; + } + } + + if ($buildfile) + { + $title=$desc=$langs->transnoentities('LastBlogPosts'); + + // Create temp file + $outputfiletmp=tempnam($dir_temp, 'tmp'); // Temporary file (allow call of function by different threads + @chmod($outputfiletmp, octdec($conf->global->MAIN_UMASK)); + + // Write file + if ($format == 'vcal') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); + elseif ($format == 'ical') $result=build_calfile($format, $title, $desc, $eventarray, $outputfiletmp); + elseif ($format == 'rss') $result=build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp); + + if ($result >= 0) + { + if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result=1; + else + { + $error='Failed to rename '.$outputfiletmp.' into '.$outputfile; + dol_syslog("build_exportfile ".$error, LOG_ERR); + dol_delete_file($outputfiletmp, 0, 1); + print $error; + exit(-1); + } + } + else + { + dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); + dol_delete_file($outputfiletmp, 0, 1); + $langs->load("errors"); + print $langs->trans("ErrorFailToCreateFile", $outputfile); + exit(-1); + } + } + + return $result; +} +// Get logos +elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) { readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file)); } -else +else { + // Find the subdirectory name as the reference include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name - if (! empty($_GET["hashp"])) + if ($hashp) { $accessallowed = 1; // When using hashp, link is public so we force $accessallowed $sqlprotectagainstexternals = ''; } - + // Security: // Limit access if permissions are wrong if (! $accessallowed) diff --git a/htdocs/zapier/hook_agenda.php b/htdocs/zapier/hook_agenda.php index 6792ecbbc05..ca046392cec 100644 --- a/htdocs/zapier/hook_agenda.php +++ b/htdocs/zapier/hook_agenda.php @@ -60,7 +60,7 @@ $search_agenda_label = GETPOST('search_agenda_label'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; diff --git a/htdocs/zapier/hook_document.php b/htdocs/zapier/hook_document.php index bedb4eb3590..a5610543eac 100644 --- a/htdocs/zapier/hook_document.php +++ b/htdocs/zapier/hook_document.php @@ -48,7 +48,7 @@ $ref = GETPOST('ref', 'alpha'); // Get parameters $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = GETPOST("page", 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : 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; diff --git a/htdocs/zapier/hook_list.php b/htdocs/zapier/hook_list.php index 56a68ad7300..7c8b0057fec 100644 --- a/htdocs/zapier/hook_list.php +++ b/htdocs/zapier/hook_list.php @@ -51,7 +51,7 @@ $id = GETPOST('id', 'int'); $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); $sortorder = GETPOST('sortorder', 'alpha'); -$page = GETPOST('page', 'int'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $page = 0; diff --git a/scripts/website/blogpost-footer.txt b/scripts/website/blogpost-footer.txt new file mode 100644 index 00000000000..e79ea4f6a4a --- /dev/null +++ b/scripts/website/blogpost-footer.txt @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/scripts/website/blogpost-header.txt b/scripts/website/blogpost-header.txt new file mode 100644 index 00000000000..5c414286e77 --- /dev/null +++ b/scripts/website/blogpost-header.txt @@ -0,0 +1,4 @@ + +

      title ?>

      + + \ No newline at end of file diff --git a/scripts/website/migrate_news_joomla2dolibarr.php b/scripts/website/migrate_news_joomla2dolibarr.php new file mode 100755 index 00000000000..e9f6c3c2295 --- /dev/null +++ b/scripts/website/migrate_news_joomla2dolibarr.php @@ -0,0 +1,188 @@ +#!/usr/bin/env php + + * + * 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 scripts/website/migrate_news_joomla2dolibarr.php + * \ingroup scripts + * \brief Migrate news from a Joomla databse into a Dolibarr website + */ + +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path = __DIR__.'/'; + +// Test if batch mode +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit(-1); +} + +@set_time_limit(0); // No timeout for this script +define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only". + +$error = 0; + +$mode = empty($argv[1])?'':$argv[1]; +$websiteref = empty($argv[2])?'':$argv[2]; +$joomlaserverinfo = empty($argv[3])?'':$argv[3]; +$image = 'image/__WEBSITE_KEY__/images/stories/dolibarr.png'; + +$max = (!isset($argv[4]) || (empty($argv[4]) && $argv[4] !== '0'))?'10':$argv[4]; + +if (empty($argv[3]) || !in_array($argv[1], array('test', 'confirm')) || empty($websiteref)) { + print '***** '.$script_file.' *****'."\n"; + print "Usage: $script_file (test|confirm) website login:pass@serverjoomla/tableprefix/databasejoomla [nbmaxrecord]\n"; + print "\n"; + print "Load joomla news and create them into Dolibarr database (if they don't alreay exist).\n"; + exit(-1); +} + +require $path."../../htdocs/master.inc.php"; +include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; +include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/website2.lib.php'; + +$langs->load('main'); + +$joomlaserverinfoarray = preg_split('/(:|@|\/)/', $joomlaserverinfo); +$joomlalogin = $joomlaserverinfoarray[0]; +$joomlapass = $joomlaserverinfoarray[1]; +$joomlahost = $joomlaserverinfoarray[2]; +$joomlaprefix = $joomlaserverinfoarray[3]; +$joomladatabase = $joomlaserverinfoarray[4]; +$joomlaport = 3306; + + +$website = new Website($db); +$result = $website->fetch(0, $websiteref); +if ($result <= 0) { + print 'Error, web site '.$websiteref.' not found'."\n"; + exit(-1); +} +$websiteid = $website->id; +$importid = dol_print_date(dol_now(), 'dayhourlog'); + +$dbjoomla=getDoliDBInstance('mysqli', $joomlahost, $joomlalogin, $joomlapass, $joomladatabase, $joomlaport); +if ($dbjoomla->error) +{ + dol_print_error($dbjoomla, "host=".$joomlahost.", port=".$joomlaport.", user=".$joomlalogin.", databasename=".$joomladatabase.", ".$dbjoomla->error); + exit(-1); +} + +$sql = 'SELECT c.id, c.title, c.alias, c.created, c.introtext, `fulltext`, c.metadesc, c.metakey, c.language, c.created, c.publish_up, u.username FROM '.$joomlaprefix.'_content as c'; +$sql.= ' LEFT JOIN '.$joomlaprefix.'_users as u ON u.id = c.created_by'; +$sql.= ' WHERE featured = 1'; +$sql.= ' ORDER BY publish_up ASC'; +$resql = $dbjoomla->query($sql); + +if (! $resql) { + dol_print_error($dbjoomla); + exit; +} + +$blogpostheader = file_get_contents($path.'blogpost-header.txt'); +if ($blogpostheader === false) { + print "Error: Failed to load file content of 'blogpost-header.txt'\n"; + exit(-1); +} +$blogpostfooter = file_get_contents($path.'blogpost-footer.txt'); +if ($blogpostfooter === false) { + print "Error: Failed to load file content of 'blogpost-footer.txt'\n"; + exit(-1); +} + + + +$db->begin(); + +$i = 0; $nbimported = 0; $nbalreadyexists = 0; +while ($obj = $dbjoomla->fetch_object($resql)) { + if ($obj) { + $i++; + $id = $obj->id; + $alias = $obj->alias; + $title = $obj->title; + //$description = dol_string_nohtmltag($obj->introtext); + $description = trim(dol_trunc(dol_string_nohtmltag($obj->metadesc), 250)); + if (empty($description)) $description = trim(dol_trunc(dol_string_nohtmltag($obj->introtext), 250)); + + $htmltext = ""; + if ($blogpostheader) $htmltext .= $blogpostheader."\n"; + $htmltext .= '
      '."\n"; + $htmltext .= $obj->introtext; + if ($obj->fulltext) { + $htmltext .= '
      '."\n".'
      '."\n".'
      '."\n".$obj->fulltext; + } + $htmltext .= "\n
      "; + if ($blogpostfooter) $htmltext .= "\n".$blogpostfooter; + + $language = ($obj->language && $obj->language != '*' ? $obj->language : 'en'); + $keywords = $obj->metakey; + $author_alias = $obj->username; + + $date_creation = $dbjoomla->jdate($obj->publish_up); + + print '#'.$i.' id='.$id.' '.$title.' lang='.$language.' keywords='.$keywords.' importid='.$importid."\n"; + + $sqlinsert = 'INSERT INTO '.MAIN_DB_PREFIX.'website_page(fk_website, pageurl, aliasalt, title, description, keywords, content, status, type_container, lang, import_key, image, date_creation, author_alias)'; + $sqlinsert .= " VALUES(".$websiteid.", '".$db->escape($alias)."', '', '".$db->escape($title)."', '".$db->escape($description)."', '".$db->escape($keywords)."', "; + $sqlinsert .= " '".$db->escape($htmltext)."', '1', 'blogpost', '".$db->escape($language)."', '".$db->escape($importid)."', '".$db->escape($image)."', '".$db->idate($date_creation)."', '".$db->escape($author_alias)."')"; + print $sqlinsert."\n"; + + $result = $db->query($sqlinsert); + if ($result <= 0) { + print 'ERROR: '.$db->lasterrno.": ".$sqlinsert."\n"; + if ($db->lasterrno != 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $error++; + } else { + $nbalreadyexists++; + } + } else { + $pageid = $db->last_insert_id(MAIN_DB_PREFIX.'website_page'); + + if ($pageid > 0) { // We must also regenerate page on disk + global $dolibarr_main_data_root; + $pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteref; + $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php'; + $websitepage = new WebsitePage($db); + $websitepage->fetch($pageid); + dolSavePageContent($filetpl, $website, $websitepage); + } + + print "Insert done - pageid = ".$pageid."\n"; + $nbimported++; + } + + if ($max && $i >= $max) { + print 'Nb max of record ('.$max.') reached. We stop now.'."\n"; + break; + } + } +} + +if ($mode == 'confirm' && ! $error) { + print "Commit\n"; + print $nbalreadyexists." page(s) already exists.\n"; + print $nbimported." page(s) imported with importid=".$importid."\n"; + $db->commit(); +} else { + print "Rollback\n"; + $db->rollback(); +} + +exit($error); diff --git a/scripts/website/regenerate_pages.php b/scripts/website/regenerate_pages.php new file mode 100755 index 00000000000..8ce78e0082d --- /dev/null +++ b/scripts/website/regenerate_pages.php @@ -0,0 +1,97 @@ +#!/usr/bin/env php + + * + * 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 scripts/website/regenerate_pages.php + * \ingroup scripts + * \brief Regenerate all pages of a web site + */ + +$sapi_type = php_sapi_name(); +$script_file = basename(__FILE__); +$path = __DIR__.'/'; + +// Test if batch mode +if (substr($sapi_type, 0, 3) == 'cgi') { + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit(-1); +} + +@set_time_limit(0); // No timeout for this script +define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only". + +$error = 0; + +$mode = empty($argv[1])?'':$argv[1]; +$websiteref = empty($argv[2])?'':$argv[2]; +$max = (!isset($argv[3]) || (empty($argv[3]) && $argv[3] !== '0'))?'10':$argv[3]; + +if (empty($argv[2]) || !in_array($argv[1], array('test', 'confirm')) || empty($websiteref)) { + print '***** '.$script_file.' *****'."\n"; + print "Usage: $script_file (test|confirm) website [nbmaxrecord]\n"; + print "\n"; + print "Regenerate all pages of a web site.\n"; + exit(-1); +} + +require $path."../../htdocs/master.inc.php"; +include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php'; +include_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php'; +include_once DOL_DOCUMENT_ROOT.'/core/lib/website2.lib.php'; + +$langs->load('main'); + +$website = new Website($db); +$result = $website->fetch(0, $websiteref); +if ($result <= 0) { + print 'Error, web site '.$websiteref.' not found'."\n"; + exit(-1); +} + +$websitepagestatic = new WebsitePage($db); + +$db->begin(); + +$listofpages = $websitepagestatic->fetchAll($website->id, '', $max); + +$nbgenerated = 0; +foreach($listofpages as $websitepage) { + global $dolibarr_main_data_root; + $pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteref; + $filealias = $pathofwebsite.'/'.$websitepage->pageurl.'.php'; + $filetpl = $pathofwebsite.'/page'.$websitepage->id.'.tpl.php'; + if ($mode == 'confirm') { + dolSavePageAlias($filealias, $website, $websitepage); + dolSavePageContent($filetpl, $website, $websitepage); + } + print "Generation of page done - pageid = ".$websitepage->id." - ".$websitepage->pageurl."\n"; + $nbgenerated++; + + if ($max && $nbgenerated >= $max) { + print 'Nb max of record ('.$max.') reached. We stop now.'."\n"; + break; + } +} + +if ($mode == 'confirm') { + print $nbgenerated." page(s) generated\n"; +} else { + print $nbgenerated." page(s) found but not generated (test mode)\n"; +} + +exit($error); diff --git a/test/README b/test/README index 3e13bbbec70..2c53e31daee 100644 --- a/test/README +++ b/test/README @@ -3,6 +3,10 @@ README (English) This directory contains unit tests and docs for Dolibarr quality analysis. +- PHPUnit - https://phpunit.de +- PHP_CodeSniffer - https://pear.php.net/package/PHP_CodeSniffer/ +- PHP Depend - https://pdepend.org/ + PHPUNIT ------- diff --git a/test/phpunit/CodingPhpTest.php b/test/phpunit/CodingPhpTest.php index e7f232e1049..733071c0f58 100644 --- a/test/phpunit/CodingPhpTest.php +++ b/test/phpunit/CodingPhpTest.php @@ -158,6 +158,19 @@ class CodingPhpTest extends PHPUnit\Framework\TestCase $filecontent=file_get_contents($file['fullname']); + $ok=true; + $matches=array(); + // Check string ='".$this->xxx with xxx that is not 'escape'. It means we forget a db->escape when forging sql request. + preg_match_all('/'.preg_quote('get_class($this)."::".__METHOD__', '/').'/', $filecontent, $matches, PREG_SET_ORDER); + foreach($matches as $key => $val) + { + $ok=false; + break; + } + //print __METHOD__." Result for checking we don't have non escaped string in sql requests for file ".$file."\n"; + $this->assertTrue($ok, 'Found string get_class($this)."::".__METHOD__ that must be replaced with __METHOD__ only in '.$file['fullname']); + //exit; + $ok=true; $matches=array(); // Check string ='".$this->xxx with xxx that is not 'escape'. It means we forget a db->escape when forging sql request. diff --git a/test/phpunit/SecurityTest.php b/test/phpunit/SecurityTest.php index 36f29685e29..4130426d806 100644 --- a/test/phpunit/SecurityTest.php +++ b/test/phpunit/SecurityTest.php @@ -187,28 +187,28 @@ class SecurityTest extends PHPUnit\Framework\TestCase print __METHOD__." result=".$result."\n"; $this->assertEquals($result, $_GET["param2"]); - $result=GETPOST("param3", 'alpha'); // Must return '' as there is a forbidden char " + $result=GETPOST("param3", 'alpha'); // Must return string sanitized from char " print __METHOD__." result=".$result."\n"; - $this->assertEquals($result, ''); + $this->assertEquals($result, 'a/b#e(pr)qq-rr\cc'); - $result=GETPOST("param4", 'alpha'); // Must return '' as there is a forbidden char ../ + $result=GETPOST("param4", 'alpha'); // Must return string sanitized from ../ print __METHOD__." result=".$result."\n"; - $this->assertEquals($result, ''); + $this->assertEquals($result, 'dir'); // Test aZ09 - $result=GETPOST("param1", 'aZ09'); // Must return '' as there is a forbidden char ../ + $result=GETPOST("param1", 'aZ09'); print __METHOD__." result=".$result."\n"; $this->assertEquals($result, $_GET["param1"]); - $result=GETPOST("param2", 'aZ09'); // Must return '' as there is a forbidden char ../ + $result=GETPOST("param2", 'aZ09'); // Must return '' as string contains car not in aZ09 definition print __METHOD__." result=".$result."\n"; $this->assertEquals($result, ''); - $result=GETPOST("param3", 'aZ09'); // Must return '' as there is a forbidden char ../ + $result=GETPOST("param3", 'aZ09'); // Must return '' as string contains car not in aZ09 definition print __METHOD__." result=".$result."\n"; $this->assertEquals($result, ''); - $result=GETPOST("param4", 'aZ09'); // Must return '' as there is a forbidden char ../ + $result=GETPOST("param4", 'aZ09'); // Must return '' as string contains car not in aZ09 definition print __METHOD__." result=".$result."\n"; $this->assertEquals($result, ''); diff --git a/test/selenium/README b/test/selenium/README new file mode 100644 index 00000000000..1d0b7ad44d1 --- /dev/null +++ b/test/selenium/README @@ -0,0 +1,11 @@ +README (English) +-------------------------------- + +This directory contains test files for Selenium. + +Selenium is a tool for automatic testing of web applications. + +https://www.selenium.dev/ + + + diff --git a/test/test_serialize.php b/test/test_serialize.php new file mode 100644 index 00000000000..873698e95c2 --- /dev/null +++ b/test/test_serialize.php @@ -0,0 +1,50 @@ +#!/usr/bin/env php +aaa = 'aaa'; +$object->bbb = 'bbb'; +$object->thirdparty = new stdClass(); +$tmp = new Societe($db); +$tmp->name = 'MyBigCompany'; +foreach ($tmp as $key=>$value) +{ + if (!in_array($key, array( + 'name', 'name_alias', 'ref_ext', 'address', 'zip', 'town', 'state_code', 'country_code' + ))) continue; // Discard if not into a dedicated list + if (!is_object($value)) $object->thirdparty->{$key} = $value; +} + + +// Show information +print "\n"; +print "*** PHP Version : ".PHP_VERSION." - Dolibarr Version : ".DOL_VERSION."\n"; + +print "*** print_r() of object used to generate the key to hash for blockedlog on the object sample:\n"; +print print_r($object, true); +print "*** We build hash(256) of this string:\n"; +print hash('sha256', print_r($object, true)); +print "\n"; + +print "*** When it is serialized() to store in db, we got:\n"; +print serialize($object); +print "\n"; + +print "*** And when it is print_r(unserialized()) to reuse it:\n"; +print print_r(unserialize(serialize($object)), true); +print "*** We build hash(256) of this string:\n"; +print hash('sha256', print_r(unserialize(serialize($object)), true)); +print "\n"; + +print "\n"; + +//print print_r(unserialize(serialize($object)));