diff --git a/.gitignore b/.gitignore index d0f4a919cde..9b639ce64a6 100755 --- a/.gitignore +++ b/.gitignore @@ -17,7 +17,4 @@ doxygen_warnings.log *.iml Thumbs.db # Vagrant generated files -.vagrant -/index.html -/phpmyadmin -/xhprof +.vagrant \ No newline at end of file diff --git a/.scrutinizer.yml b/.scrutinizer.yml index 73b43e95f4b..1db2aa867ae 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -180,8 +180,38 @@ tools: - 'htdocs/includes/*' paths: { } + php_changetracking: + enabled: false + bug_patterns: + - '\bfix(?:es|ed)?\b' + feature_patterns: + - '\badd(?:s|ed)?\b' + - '\bimplement(?:s|ed)?\b' + filter: + excluded_paths: + - 'build/*' + - 'dev/*' + - 'doc/*' + - 'test/*' + - 'htdocs/includes/*' + paths: { } + # Coding-Style / Bug Detection - js_hint: false + js_hint: + enabled: false + use_native_config: true + extensions: + - js + filter: + excluded_paths: + - 'build/*' + - 'dev/*' + - 'doc/*' + - 'test/*' + - 'htdocs/includes/*' + paths: { } + config: { } + path_configs: { } before_commands: { } diff --git a/.travis.yml b/.travis.yml index 9c7f18481f5..c97b547e499 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,6 +36,7 @@ before_script: - echo Install phpcs then show installed rules - pyrus install pear/PHP_CodeSniffer - phpenv rehash + - phpcs --version - phpcs -i - echo Create dir $(pwd)/htdocs/documents - sudo mkdir -p $(pwd)/htdocs/documents/admin/temp; @@ -53,12 +54,14 @@ before_script: - sh -c "if [ '$PHPV' = '5.3' ]; then echo 'zend_extension_ts = xdebug.so' >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi" - sh -c "if [ '$PHPV' = '5.4' ]; then echo 'zend_extension_ts = xdebug.so' >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi" - cat ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini + - echo Mysql version + - mysql --version - echo Init database - sh -c "if [ '$DB' = 'pgsql' ]; then psql -c 'DROP DATABASE IF EXISTS myapp_test;' -U postgres; fi" - sh -c "if [ '$DB' = 'pgsql' ]; then psql -c 'CREATE DATABASE myapp_test;' -U postgres; fi" - sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'DROP DATABASE IF EXISTS myapp_test;'; fi" - sh -c "if [ '$DB' = 'mysql' ]; then mysql -e 'CREATE DATABASE IF NOT EXISTS myapp_test;'; fi" - - sh -c "if [ '$DB' = 'mysql' ]; then mysql -D myapp_test < $(pwd)/dev/initdata/mysqldump_dolibarr_3.4.0.sql; fi" + - sh -c "if [ '$DB' = 'mysql' ]; then mysql -D myapp_test < $(pwd)/dev/initdata/mysqldump_dolibarr_3.5.0.sql; fi" - echo Create config file htdocs/conf/conf.php - echo ' htdocs/conf/conf.php - sh -c "if [ '$DB' = 'pgsql' ]; then echo '$'dolibarr_main_db_type=\'pgsql\'';' >> htdocs/conf/conf.php; fi" @@ -87,18 +90,22 @@ before_script: script: - cd htdocs/install - - php upgrade.php 3.4.0 3.5.0 > upgrade.log - - php upgrade2.php 3.4.0 3.5.0 > upgrade2.log + - date +# - php upgrade.php 3.4.0 3.5.0 > upgrade.log +# - php upgrade2.php 3.4.0 3.5.0 > upgrade2.log - php upgrade.php 3.5.0 3.6.0 >> upgrade.log - php upgrade2.php 3.5.0 3.6.0 >> upgrade2.log -# - cat upgrade.log + - php upgrade.php 3.6.0 3.7.0 >> upgrade.log +# - cat upgrade360370.log + - php upgrade2.php 3.6.0 3.7.0 >> upgrade2.log # - cat upgrade2.log - cd ../.. - date -# - phpcs -p --warning-severity=0 -s --report-summary --standard=dev/codesniffer/ruleset.xml --tab-width=4 --ignore=/build/html/,/dev/vagrant/,/documents/,/includes/,/test/report/ htdocs/core/class/dolgraph.class.php 2>&1 - - phpcs -p --warning-severity=0 -s --report-checkstyle --report-summary --standard=dev/codesniffer/ruleset.xml --tab-width=4 --ignore=/build/html/,/dev/vagrant/,/documents/,/includes/,/test/report/ . 2>&1 - - date - phpunit -d memory_limit=-1 --configuration test/phpunit/phpunittest.xml test/phpunit/AllTests.php + - date +# - phpcs -p --warning-severity=0 -s --report-summary --standard=dev/codesniffer/ruleset.xml --tab-width=4 --ignore=/build/html/,/dev/vagrant/,/documents/,/includes/,/test/report/ htdocs/core/class/dolgraph.class.php 2>&1 + - phpcs -p --warning-severity=0 -s --report-checkstyle --report-summary --standard=dev/codesniffer/ruleset.xml --tab-width=4 --ignore=/htdocs/conf/conf.php,/build/html/,/dev/vagrant/,/documents/,/includes/,/test/report/ . 2>&1 + - date after_script: # - echo Output dolibarr log file; cat $(pwd)/htdocs/documents/dolibarr.log diff --git a/.tx/config b/.tx/config index fcd276390ee..e4d1fc65732 100644 --- a/.tx/config +++ b/.tx/config @@ -2,6 +2,12 @@ host = https://www.transifex.com lang_map = uz: uz_UZ +[dolibarr.accountancy] +file_filter = htdocs/langs//accountancy.lang +source_file = htdocs/langs/en_US/accountancy.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.admin] file_filter = htdocs/langs//admin.lang source_file = htdocs/langs/en_US/admin.lang @@ -212,12 +218,6 @@ source_file = htdocs/langs/en_US/orders.lang source_lang = en_US type = MOZILLAPROPERTIES -[dolibarr.oscommerce] -file_filter = htdocs/langs//oscommerce.lang -source_file = htdocs/langs/en_US/oscommerce.lang -source_lang = en_US -type = MOZILLAPROPERTIES - [dolibarr.other] file_filter = htdocs/langs//other.lang source_file = htdocs/langs/en_US/other.lang @@ -236,6 +236,18 @@ source_file = htdocs/langs/en_US/paypal.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.printipp] +file_filter = htdocs/langs//printipp.lang +source_file = htdocs/langs/en_US/printipp.lang +source_lang = en_US +type = MOZILLAPROPERTIES + +[dolibarr.productbatch] +file_filter = htdocs/langs//productbatch.lang +source_file = htdocs/langs/en_US/productbatch.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.products] file_filter = htdocs/langs//products.lang source_file = htdocs/langs/en_US/products.lang @@ -254,6 +266,12 @@ source_file = htdocs/langs/en_US/propal.lang source_lang = en_US type = MOZILLAPROPERTIES +[dolibarr.resource] +file_filter = htdocs/langs//resource.lang +source_file = htdocs/langs/en_US/resource.lang +source_lang = en_US +type = MOZILLAPROPERTIES + [dolibarr.salaries] file_filter = htdocs/langs//salaries.lang source_file = htdocs/langs/en_US/salaries.lang @@ -266,12 +284,6 @@ source_file = htdocs/langs/en_US/sendings.lang source_lang = en_US type = MOZILLAPROPERTIES -[dolibarr.shop] -file_filter = htdocs/langs//shop.lang -source_file = htdocs/langs/en_US/shop.lang -source_lang = en_US -type = MOZILLAPROPERTIES - [dolibarr.sms] file_filter = htdocs/langs//sms.lang source_file = htdocs/langs/en_US/sms.lang @@ -313,4 +325,3 @@ file_filter = htdocs/langs//workflow.lang source_file = htdocs/langs/en_US/workflow.lang source_lang = en_US type = MOZILLAPROPERTIES - diff --git a/COPYRIGHT b/COPYRIGHT index ed8a667acc8..2e1c6e921b9 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -9,41 +9,41 @@ More information: http://www.gnu.org/licenses/gpl-3.0.txt Dolibarr uses some external libraries released under different licenses. This is compatibility summary: -Component Version License GPL Compatible Usage +Component Version License GPL Compatible Usage ------------------------------------------------------------------------------------- PHP libraries: -AdoDb-Date 0.32 Modified BSD License Yes Date convertion (not into rpm package) -CKEditor 4.3.3 LGPL-2.1+ Yes Editor WYSIWYG -FPDI 1.4.2 Apache Software License 2.0 Yes PDF templates management -FPDF_TPL 1.2 Apache Software License 2.0 Yes PDF templates management -GeoIP 1.4 LGPL-2.1+ Yes Sample code to make geoip convert (not into deb package) -NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package) -odtPHP 1.0.1 GPL-2+ b Yes Library to build/edit ODT files -PHPExcel 1.7.6 LGPL-2.1+ Yes Read/Write XLS files, read ODS files -PHPPrintIPP 1.3 GPL-2+ Yes Library to send print IPP requests -TCPDF 6.0.093 LGPL-3+ Yes PDF generation +AdoDb-Date 0.32 Modified BSD License Yes Date convertion (not into rpm package) +CKEditor 4.3.3 LGPL-2.1+ Yes Editor WYSIWYG +FPDI 1.4.2 Apache Software License 2.0 Yes PDF templates management +FPDF_TPL 1.2 Apache Software License 2.0 Yes PDF templates management +GeoIP 1.4 LGPL-2.1+ Yes Sample code to make geoip convert (not into deb package) +NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package) +odtPHP 1.0.1 GPL-2+ b Yes Library to build/edit ODT files +PHPExcel 1.7.8 LGPL-2.1+ Yes Read/Write XLS files, read ODS files +PHPPrintIPP 1.3 GPL-2+ Yes Library to send print IPP requests +TCPDF 6.0.093 LGPL-3+ Yes PDF generation JS libraries: -jQuery 1.8.2 MIT License Yes JS library -jQuery UI 1.9.1 GPL and MIT License Yes JS library plugin UI -jQuery UI Multiselect ? GPL and MIT License Yes JS library plugin for sexier multiselect -jQuery blockUI 2.43 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) -jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors -jQuery DataTables 1.9.4 BSD Yes JS library for tables output -jQuery FileUpload 5.0.3 GPL and MIT License Yes JS library to upload files -jQuery Flot 0.7 MIT License Yes JS library to build graph -jQuery JCrop 0.9.8 GPL and MIT License Yes JS library plugin Crop (to crop images) -jQuery Jeditable 1.7.1 GPL and MIT License Yes JS library plugin jeditable (to edit in place) -jQuery jNotify 1.1.00 Apache Software License 2.0 Yes JS library plugin jNotify (to use ajax popups) -jQuery jPicker 1.1.6 GPL and MIT License Yes JS library for color picker with not defined list of colors -jQuery jqueryFileTree 1.0.1 GPL and MIT License Yes JS library for color picker with not defined list of colors -jQuery jquerytreeview 1.4.1 MIT License Yes JS library for color picker with not defined list of colors -jQuery Layout 1.3.0rc30.74 GPL and MIT License Yes JS library plugin Layout (RC-29.15) -jQuery Mobile 1.3.0 GPL and MIT License Yes JS library for smartphone (not used) -jQuery TableDnD 0.6 GPL and MIT License Yes JS library plugin TableDnD (to reorder table rows) -jQuery Timepicker 1.1.0 GPL and MIT License Yes JS library Timepicker addon for Datepicker -jQuery Tiptip 1.3 GPL and MIT License Yes JS library for tooltips -jsGantt 1.2 BSD License Yes JS library (to build Gantt reports) +jQuery 1.8.2 MIT License Yes JS library +jQuery UI 1.9.1 GPL and MIT License Yes JS library plugin UI +jQuery select2 3.5.2 GPL and Apache License Yes JS library plugin for sexier multiselect +jQuery blockUI 2.43 GPL and MIT License Yes JS library plugin blockUI (to use ajax popups) +jQuery Colorpicker 1.1 MIT License Yes JS library for color picker for a defined list of colors +jQuery DataTables 1.9.4 BSD Yes JS library for tables output +jQuery FileUpload 5.0.3 GPL and MIT License Yes JS library to upload files +jQuery Flot 0.7 MIT License Yes JS library to build graph +jQuery JCrop 0.9.8 GPL and MIT License Yes JS library plugin Crop (to crop images) +jQuery Jeditable 1.7.1 GPL and MIT License Yes JS library plugin jeditable (to edit in place) +jQuery jNotify 1.1.00 Apache Software License 2.0 Yes JS library plugin jNotify (to use ajax popups) +jQuery jPicker 1.1.6 GPL and MIT License Yes JS library for color picker with not defined list of colors +jQuery jqueryFileTree 1.0.1 GPL and MIT License Yes JS library for color picker with not defined list of colors +jQuery jquerytreeview 1.4.1 MIT License Yes JS library for color picker with not defined list of colors +jQuery Layout 1.3.0rc30.74 GPL and MIT License Yes JS library plugin Layout (RC-29.15) +jQuery Mobile 1.3.0 GPL and MIT License Yes JS library for smartphone (not used) +jQuery TableDnD 0.6 GPL and MIT License Yes JS library plugin TableDnD (to reorder table rows) +jQuery Timepicker 1.1.0 GPL and MIT License Yes JS library Timepicker addon for Datepicker +jQuery Tiptip 1.3 GPL and MIT License Yes JS library for tooltips +jsGantt 1.2 BSD License Yes JS library (to build Gantt reports) For licenses compatibility informations: http://www.fsf.org/licensing/licenses/index_html diff --git a/ChangeLog b/ChangeLog index 9bf2c0bc7cb..e184f0045b8 100644 --- a/ChangeLog +++ b/ChangeLog @@ -2,8 +2,170 @@ English Dolibarr ChangeLog -------------------------------------------------------------- -***** ChangeLog for 3.5.7 compared to 3.5.6 ***** -Fix: Paypal link were broken dur to SSL v3 closed. +***** ChangeLog for 3.7 compared to 3.6.* ***** +For users: +- New: Match other auth system: Login can be done entering login or user + email (this open the road for SSO). +- New: Agenda export by project #1967. +- New: Increase length of thirdparty to 128 chars. +- New: "Is Order shippable" icon #1975. +- New: statistics on supplier orders and invoices on home page. +- New: Add permissions to read all trips and expenses. +- New: Can filter on date into tab "Referring object" of a project. +- New: Module notification has been enhanced: + EMail use now language of target contact. + Can also define a fixed email for notifications. +- New: Feature to link manually an order to an invoice does not disappear once + link has been done. +- New: Can set a color on user card (visible into agenda view). +- New: extrafields for projects and tasks are exported to ODT documents. +- New: Add number of active notification into tab title (like we do for notes and documents) +- New: Can add product into category from category card. +- New: PDF event report show project and status of event. +- New: Can filter on status on interventions. +- New: Add help info of field type into dictionary of payment types. +- New: Add proposals into referer page of thirdparty. +- New: On contact list can set filter on both active and not active (no more exclusive select). +- New: Intervention documents are now available in ECM module. +- New: Can attach supplier order to a customer order. +- New: Supervisor is now visible into user list. +- New: Add user of creation and validation on invoice export. +- New: Add info page about browser. +- New: Enable feature developed for 3.6 we forgot to enabled: Adding prefix + on uploaded file names. +- New: No more dependency between contract and service module. +- New: [ task #867 ] Remove ESAEB external module code from core. +- New: Can create proposal from an intervention. +- New: An event can be assigned to several users. +- New: Can filter events on a group of users. +- New: Can filter events of a thirdparty. +- New: Onto event summary of elements, end date and status are visible. +- New: Split Agenda view (month, week, day) into different tabs. +- New: Add a view "per user" of agenda events (with different colors according to type of event). +- New: Each user can include its own external ics calendar into dolibarr agenda view. +- New: Add event FICHINTER_CLASSIFY_BILLED into list of possible events to + create an automatic event into agenda. +- New: Add new type of event (when type of events are used, not by default). +- New: Can disable predefined type of events. +- New: Form to add a photo is immediatly available on photo page if + permissions are ok (save one click per photo to add). +- New: Add option PRODUCT_MAX_VISIBLE_PHOTO to limit number of photos + shown on main product card. +- New: Add country into table of thirdparties type. This will allow to provide + a list of thirdparty types specific to a country (like argentina that + need type A or B). +- New: Can force a specific bank account onto an invoice/order. +- New: Home page of project area shows list of draft project (like other main page). +- New: Can search on project ref or string from project main page (like other main page). +- New: First change to match accessibility rules: http://www.w3.org/TR/WCAG10-HTML-TECHS/ + Differentiate text and img. + Use label into quick search form. + Use accesskey on form search. +- New: Intervention documents are now available in ECM module. +- New: Add attachments on user card + in ECM module. +- New: Can add __PROJECT_REF__ and __TIHRPARTY_NAME__ into email topic or content template. +- New: [ task #1204 ] add Numering contrat module free (like leopard in product module). +- New: [ task #712 ] Add warning when creating invoice from proposal or order, when there is already one invoice. +- New: Enable supplier price log table. +- New: [ task #1204 ] add a supplier reference to contract. +- New: [ task #1218 ] Can drag and drop an event from calendar to change its day. +- New: Optimize size of image static resources. +- New: Add hourly and daily amount on user card. Add weekly working hours and salary on user card. +- New: Content of predefined email come firstly from table llx_c_email_template, then translation key. +- New: Add option MAIN_GENERATE_INVOICES_WITH_PICTURE to show picture + onto PDF like MAIN_GENERATE_PROPOSALS_WITH_PICTURE dir for proposals. +- New: Add more search field in list of cheque deposits. +- New: Add feature to order to invoice on supplier part. +- New : Use of MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR to use disk cache for big excel export. +- New: Direct invoice creation from predefined invoice. +- New: Add dunning into accountancy report. +- New: Add favorite button into country dictionary to put value on top select list +- Upgrade phpexcel lib to 1.7.8 +- New : Use of MAIN_USE_FILECACHE_EXPORT_EXCEL_DIR to use disk cache for big excel export. +- New : Option on extrafields to have them always editable regardless of the document status. +- New : New module PrintIPP to print without opening document is available as stable. +- Fix: [ bug #1487 ] PAYMENT_DELETE trigger does not intercept trigger action +- Fix: [ bug #1470, #1472, #1473] User trigger problem +- Fix: [ bug #1489, #1491 ] Intervention trigger problem +- Fix: [ bug #1492, #1493 ] Member trigger problem +- Fix: [ bug #1474, #1475 ] Contract trigger problem +- Fix: [ bug #1496 ] ACTION_DELETE trigger does not show trigger error +- Fix: [ bug #1494 ] CATEGORY_CREATE and CATEGORY_MODIFY triggers do not intercept trigger action +- Fix: [ bug #1502 ] DON_CREATE trigger does not intercept trigger action +- Fix: [ bug #1505, #1504] Project trigger problem +- Fix: [ bug #1463, #1464 ] Proposal triggers problem +- Fix: [ bug #1498, #1499 ] Shipment/Delivery triggers problem +- Fix: [ bug #1465, #1466 ] Product triggers problem +- Fix: [ bug #1508 ] STOCK_MOVEMENT does not show trigger error message +- Fix: [ bug #1501 ] DEPLACEMENT_CREATE trigger do not intercept trigger action +- Fix: [ bug #1506, #1507 ] ECM trigger error problem +- Fix: [ bug #1469 ] Triggers CONTACT_MODIFY and CONTACT_DELETE duplicates error message +- Fix: [ bug #1537 ] Difference between societe.nom and adherent.societe. +- Fix: [ bug #1535 ] Supplier invoice Extrafields are not shown +- Fix: datepicker first day of week can be monday by setting into display setup + +For users, new experimental module (need to set feature level of instance to experimental to see them): +- New: Module Accounting Expert to manage accountancy + Special Thanks to developpers : + Olivier Geffroy + Alexandre Spangaro + Ari Elbaz + Florian Henry + Juanjo Menent + And to the contributors : + Jeff Info 2000 euros + Nord Anim 120 euros + Hydroflex 120 euros + Asysteo 120 euros + Fournisseur médical 120 euros +- Removed: unmaintained OScommerce module + +For translators: +- Update language files. +- New: When a translation is not available we always jump to en_US and only en_US. + +For developers: +- New: Add a css style "cursorpointer". +- New: Select list of users can return user into hierarchy. +- New: getBrowserInfo can return type of layout of browser (classic/phone/tablet) +- New: Add hook "searchAgendaFrom" and "beforePDFCreation". +- New: Add trigger DON_UPDATE, DON_DELETE +- New: Add country iso code on 3 chars into table of countries. +- Qual: Removed hard coded rowid into data init of table llx_c_action_trigger. +- LINEBILL_DELETE, LINK_DELETE, ORDER_SUPPLIER_DELETE, RESOURCE_DELETE trigger called before SQL delete +- New: [ Task #1481 ] Add trigger BILL_SUPPLIER_UPDATE. +- New: [ Task #1495 ] Add trigger LINECONTRACT_CREATE. +- New: Added hook "formConfirm" and "doActions" for supplier invoice card. +- New: [ task #1511, #1426 ] Added hook "doActions" for supplier card and supplier order card. +- New: renamed table llx_c_pays to llx_c_country & libelle field to label. +- New: Added hook "formConfirm" and "doActions" for fichinter card +- New: Can search list of thirdparties from web service on part of name. +- New: Function getCurrencyAmount is marked as deprecated. Use function price to output a price + including currency symbol. +- Qual: Renamed table llx_c_civilite into llx_c_civility, + field civilite into label in the same table, + and field civilite into civility in other table. +- Qual: Renamed all files & links "liste.php" into "list.php". +- Qual: Renamed all files & links "fiche.php" into "card.php". +- Qual: Replace all constants COMPTA_* by ACCOUNTING_*. +- Qual: Replace all constants ACCOUNTINGEX_* by ACCOUNTING_* to simplify migration of the module + +WARNING: Following changes may create regression for some external modules, but was necessary to make +Dolibarr better: + +- If you can't see trips and expenses records, check that you have the new permission "read all + trips and expenses". +- Deprecated module "oscommerce" were removed. +- Changed the way parameters are provided to scripts sync_xxx_ldap2dolibarr.php +- Some field into database were renamed from "libelle" to "label". +- Table llx_c_pays were renamed into llx_c_country. +- Triggers *_BUILDDOC are removed. Building a doc is not a business event. For action after + creation of a pdf or odt, hook "afterPDFCreation" or "afterODTCreation" must be used instead. +- A lot of pages called fiche.php were renamed into card.php +- A lot of pages called liste.php were renamed into list.php +- If you used warehouse/stock module, recheck setup of stock increase/decrease rules of the + warehouse module and your Point Of Sale module if you use one. + ***** ChangeLog for 3.6.2 compared to 3.6.1 ***** - Fix: fix ErrorBadValueForParamNotAString error message in price customer multiprice. @@ -109,6 +271,9 @@ For users: - Fix: Add actions events not implemented. - Fix: Price min of composition is not supplier price min by quantity. - Fix: [ bug #1356 ] Bank accountancy number is limited to 8 numbers. +- Fix: [ bug #1439 ] impossible to remove a a translation (multilanguage-feature) +- New: If multilangue is enabled, mail (from propal, invoice, etc...) message is pre-defaulted in Customer language +- Fix: [ bug #1459 ] _ADD_CONTACT and _DEL_CONTACT triggers do not intercept insertion when reported an error - Fix: [ bug #1478 ] BILL_PAYED trigger action does not intercept failure under some circumstances - Fix: [ bug #1479 ] Several customer invoice triggers do not intercept trigger action - Fix: [ bug #1477 ] Several customer invoice triggers do not show trigger error messages @@ -136,6 +301,8 @@ For developers: - New: A module can disable a standard ECM view. - New: Add multilang support into product webservice. - New: Add hooks on project card page. +- New: Add call_trigger method on CommonObject class. So new trigger call within object is just : +$result = $this->call_trigger($trigger_name, $user) WARNING: Following change may create regression for some external modules, but was necessary to make Dolibarr better: @@ -143,16 +310,19 @@ Dolibarr better: - The deprecated way (with 4 parameters) to declare a new tab into a module descriptor file has been removed. You must now use the 6 parameters way. See file modMyModule.class.php for example. - Remove the javascript function ac_delay() that is not used anymore by core code. -- Properties "dictionnaries" into module descriptor files has been renamed into "dictionaries". +- Properties "dictionnaries" into module descriptor files have been renamed into "dictionaries". - Method form->select_currency() has been removed. Use instead print form->selectCurrency(). - Method form->select_methodes_commande() has been renamed into english name selectInputMethod(). - The following hooks are now 'addreplace' hooks: "formCreateThirdpartyOptions" - So check that return value is 0 to keep default standard behaviour after hook or 1 to disable + So check that return value is 0 to keep default standard behaviour after hook, or 1 to disable default standard behaviour. - Properties "civilite_id" were renamed into "civility_id". - Remove add_photo_web() that is ot used anymore by core code. +***** ChangeLog for 3.5.7 compared to 3.5.6 ***** +Fix: Paypal link were broken dur to SSL v3 closed. + ***** ChangeLog for 3.5.6 compared to 3.5.5 ***** Fix: Avoid missing class error for fetch_thirdparty method #1973 Fix: Can't update phone_pro from web service diff --git a/build.xml b/build.xml index fc267bf196e..570821a7c7b 100644 --- a/build.xml +++ b/build.xml @@ -1,6 +1,6 @@ - +fdfds diff --git a/build/debian/README.howto b/build/debian/README.howto index 6b6e71c4874..f9bb31c6fcf 100644 --- a/build/debian/README.howto +++ b/build/debian/README.howto @@ -153,6 +153,9 @@ from origin/upstream and origin/pristine. * Into root dir, launch: > debian/get-orig-source.sh +If script fails with error Bad certificate, you can set "export PERL_LWP_SSL_VERIFY_HOSTNAME=0" to solve this. + +* Some files are removed from archive by the get-orig-source.sh * Staying into git root directory, run > git-import-orig -vv ../tcpdf_x.y.z+dfsg.orig.tar.xz @@ -160,9 +163,9 @@ from origin/upstream and origin/pristine. Note: If there was errors solved manually, you may need to make a git commit * Add an entry into debian/changelog -> dch -v x.y.z-dsfg-1 "My comment" will add entry. -For example: dch -v x.y.z-dsfg-1 "New upstream release." for a new version -Then modify changelog to replace "unstable" with "UNRELEASED". +> dch -v x.y.z+dfsg-1 "My comment" will add entry. +For example: dch -v x.y.z+dfsg-1 "New upstream release." for a new version +Then modify changelog to replace "version" or "unstable" with "UNRELEASED". Warning: Date must have format reported by "date -R" Warning: Name and email must match value into debian/control file (Entry added here is used by next step). @@ -228,23 +231,29 @@ from origin/upstream and origin/pristine. * If new upstream is available onto sourceforge, launch: > debian/get-orig-source.sh +If script fails with error Bad certificate, you can set "export PERL_LWP_SSL_VERIFY_HOSTNAME=0" to solve this. -* Edit tgz file to remove ckeditor and phpexcel and rename file into -dolibarr-x.y.z+dsfgw.tgz -(x.y.z = version, w start from 1 and is increased for each new import) +* Edit tgz file to remove +- htdocs/includes/ckeditor +- htdocs/includes/jquery/plugins/datatables/extras/TableTools/swf +- htdocs/includes/phpexcel +- htdocs/includes/tcpdf +And rename file into +dolibarr-x.y.z+dfsgw.tgz +(x.y.z = version, w start from 1 and is increased for each new git-import-orig already done) * Staying into git root directory, run -> git-import-orig -vv ../dolibarr-x.y.z+dsfgw.tgz +> git-import-orig -vv ../dolibarr-x.y.z+dfsgw.tgz and enter version when requested with format -x.y.z+dsfgw +x.y.z+dfsgw (x.y.z = version, w start from 1 and is increased for each new import) Note: If there was errors solved manually after get-orig-sources.sh, you may need to make a git commit * Add an entry into debian/changelog -> dch -v x.y.z-w "My comment" will add entry. -For example: dch -v x.y.z-w "New upstream release." for a new version (x.y.z = version, w start from 1 and increaed for each new import) -Then modify changelog to replace "unstable" with "UNRELEASED". +> dch -v x.y.z+dfsg-w "My comment" will add entry. +For example: dch -v x.y.z+dfsgw-1 "New upstream release." for a new version (x.y.z = version, w start from 1 and increaed for each new import) +Then modify changelog to replace "version" or "unstable" with "UNRELEASED". Then check/modify also the user/date signature: - Date must have format reported by "date -R" - Name and email must match value into debian/control file (Entry added here is used by next step). diff --git a/build/debian/changelog b/build/debian/changelog index ab2fe33ec0a..e8ea7be4823 100644 --- a/build/debian/changelog +++ b/build/debian/changelog @@ -1,13 +1,6 @@ -dolibarr (3.6.1-3) unstable; urgency=low +dolibarr (3.7.0-3) UNRELEASED; urgency=low [ Laurent Destailleur (eldy) ] * New upstream release. - -- Laurent Destailleur (eldy) Tue, 23 Sep 2014 12:00:00 +0100 - -dolibarr (3.6.0-3) unstable; urgency=low - - [ Laurent Destailleur (eldy) ] - * New upstream release. - - -- Laurent Destailleur (eldy) Tue, 15 July 2014 12:00:00 +0100 + -- Laurent Destailleur (eldy) Tue, 21 Oct 2014 12:00:00 +0100 \ No newline at end of file diff --git a/build/debian/get-orig-source.sh b/build/debian/get-orig-source.sh index 418bbbc2199..cc22a53c908 100755 --- a/build/debian/get-orig-source.sh +++ b/build/debian/get-orig-source.sh @@ -1,10 +1,9 @@ #!/bin/sh -# Scan for new official sources and download file -# run with debian/get-orig-source.sh [x.y.z] tmpdir=$(mktemp -d) -echo "tmpdir = $tmpdir" + +# Download source file if [ -n "$1" ]; then uscan_opts="--download-version=$1" fi diff --git a/build/exe/doliwamp/doliwamp.iss b/build/exe/doliwamp/doliwamp.iss index 1657ff1c7e7..3a43f7fe656 100644 --- a/build/exe/doliwamp/doliwamp.iss +++ b/build/exe/doliwamp/doliwamp.iss @@ -17,9 +17,9 @@ ; ----- Change this ----- AppName=DoliWamp ; DoliWamp-x.x.x or DoliWamp-x.x.x-alpha or DoliWamp-x.x.x-beta or DoliWamp-x.x.x-rc or DoliWamp-x.x.x -AppVerName=DoliWamp-3.6.1 +AppVerName=DoliWamp-3.7.0-beta ; DoliWamp-x.x x or DoliWamp-x.x.x-alpha or DoliWamp-x.x.x-beta or DoliWamp-x.x.x-rc or DoliWamp-x.x.x -OutputBaseFilename=DoliWamp-3.6.1 +OutputBaseFilename=DoliWamp-3.7.0-beta ; ----- End of change ;OutputManifestFile=build\doliwampbuild.log ; Define full path from which all relative path are defined diff --git a/build/launchpad/README b/build/launchpad/README index 973509aa6d1..03ddc7fd4e6 100644 --- a/build/launchpad/README +++ b/build/launchpad/README @@ -61,13 +61,17 @@ If you want to build/test package locally: - List of series are visible here: https://launchpad.net/dolibarr/+series -# To update Dolibarr into launchpad (when repository for sources already exists) +# To update Dolibarr into launchpad (when remote repository for sources already exists) #---------------------------------- + # create local repository cd bzr - bzr branch lp:~yourlogin/dolibarr/[dev|beta|stable] + bzr branch lp:~yourlogin/dolibarr/[develop|beta|stable] dolibarr-[dev|beta|stable] cd dolibarr-[dev|beta|stable] + # Update + bzr update + -- Update files here. Remove all and overwrite -- bzr status - -- Update files here -- + bzr add * bzr commit -m "Description of change" bzr push diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 8abac38d802..370c04591a9 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -63,19 +63,19 @@ $PUBLISHSTABLE="eldy,dolibarr\@frs.sourceforge.net:/home/frs/project/dolibarr"; $PUBLISHBETARC="ldestailleur\@asso.dolibarr.org:/home/dolibarr/dolibarr.org/files"; if (! $ENV{"DESTIBETARC"} || ! $ENV{"DESTISTABLE"}) { - print "Error: Missing environment variables.\n"; + print "Error: Missing environment variables.\n"; print "You must define the environment variable DESTIBETARC and DESTISTABLE to point to the\ndirectories where you want to save the generated packages.\n"; print "Example: DESTIBETARC='/media/HDDATA1_LD/Mes Sites/Web/Dolibarr/dolibarr.org/files/lastbuild'\n"; print "Example: DESTISTABLE='/media/HDDATA1_LD/Mes Sites/Web/Dolibarr/dolibarr.org/files/stable'\n"; print "$PROG.$Extension aborted.\n"; - sleep 2; + sleep 2; exit 1; } if (! -d $ENV{"DESTIBETARC"} || ! -d $ENV{"DESTISTABLE"}) { - print "Error: Directory of environment variable DESTIBETARC or DESTISTABLE does not exist.\n"; + print "Error: Directory of environment variable DESTIBETARC or DESTISTABLE does not exist.\n"; print "$PROG.$Extension aborted.\n"; - sleep 2; + sleep 2; exit 1; } @@ -85,31 +85,31 @@ if ("$^O" =~ /linux/i || (-d "/etc" && -d "/var" && "$^O" !~ /cygwin/i)) { $OS=' elsif (-d "/etc" && -d "/Users") { $OS='macosx'; $CR=''; } elsif ("$^O" =~ /cygwin/i || "$^O" =~ /win32/i) { $OS='windows'; $CR="\r"; } if (! $OS) { - print "Error: Can't detect your OS.\n"; + print "Error: Can't detect your OS.\n"; print "Can't continue.\n"; print "$PROG.$Extension aborted.\n"; - sleep 2; + sleep 2; exit 1; } # Define buildroot # ---------------- if ($OS =~ /linux/) { - $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"/tmp"; + $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"/tmp"; } if ($OS =~ /macos/) { - $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"/tmp"; + $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"/tmp"; } if ($OS =~ /windows/) { - $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"c:/temp"; - $PROGPATH=$ENV{"ProgramFiles"}; + $TEMP=$ENV{"TEMP"}||$ENV{"TMP"}||"c:/temp"; + $PROGPATH=$ENV{"ProgramFiles"}; } if (! $TEMP || ! -d $TEMP) { - print "Error: A temporary directory can not be find.\n"; - print "Check that TEMP or TMP environment variable is set correctly.\n"; + print "Error: A temporary directory can not be find.\n"; + print "Check that TEMP or TMP environment variable is set correctly.\n"; print "$PROG.$Extension aborted.\n"; - sleep 2; - exit 2; + sleep 2; + exit 2; } $BUILDROOT="$TEMP/buildroot"; @@ -169,10 +169,10 @@ my $batch=0; for (0..@ARGV-1) { if ($ARGV[$_] =~ /^-*target=(\w+)/i) { $target=$1; $batch=1; } if ($ARGV[$_] =~ /^-*desti=(.+)/i) { $DESTI=$1; } - if ($ARGV[$_] =~ /^-*prefix=(.+)/i) { - $PREFIX=$1; - $FILENAMESNAPSHOT.="-".$PREFIX; - } + if ($ARGV[$_] =~ /^-*prefix=(.+)/i) { + $PREFIX=$1; + $FILENAMESNAPSHOT.="-".$PREFIX; + } } if ($ENV{"DESTIBETARC"} && $BUILD =~ /[a-z]/i) { $DESTI = $ENV{"DESTIBETARC"}; } # Force output dir if env DESTIBETARC is defined if ($ENV{"DESTISTABLE"} && $BUILD =~ /^[0-9]+$/) { $DESTI = $ENV{"DESTISTABLE"}; } # Force output dir if env DESTISTABLE is defined @@ -192,7 +192,7 @@ print "Target directory (DESTI) : $DESTI\n"; if ($target) { if ($target eq "ALL") { foreach my $key (@LISTETARGET) { - if ($key ne 'SNAPSHOT' && $key ne 'SF' && $key ne 'ASSO') { $CHOOSEDTARGET{$key}=1; } + if ($key ne 'SNAPSHOT' && $key ne 'SF' && $key ne 'ASSO') { $CHOOSEDTARGET{$key}=1; } } } if ($target ne "ALL" && $target ne "SF" && $target ne "ASSO") { $CHOOSEDTARGET{uc($target)}=1; } @@ -200,56 +200,56 @@ if ($target) { if ($target eq "ASSO") { $CHOOSEDPUBLISH{"ASSO"}=1; } } else { - my $found=0; - my $NUM_SCRIPT; - my $cpt=0; - while (! $found) { - printf(" %2d - %-14s (%s)\n",$cpt,"ALL (1..9)","Need ".join(",",values %REQUIREMENTTARGET)); - foreach my $target (@LISTETARGET) { - $cpt++; - printf(" %2d - %-14s (%s)\n",$cpt,$target,"Need ".$REQUIREMENTTARGET{$target}); - } - $cpt=98; - printf(" %2d - %-14s (%s)\n",$cpt,"ASSO (publish)","Need ".join(",",values %REQUIREMENTPUBLISH)); - $cpt=99; - printf(" %2d - %-14s (%s)\n",$cpt,"SF (publish)","Need ".join(",",values %REQUIREMENTPUBLISH)); - - # Ask which target to build - print "Choose one package number or several separated with space (0 - ".$cpt."): "; - $NUM_SCRIPT=; - chomp($NUM_SCRIPT); - if ($NUM_SCRIPT !~ /^[0-9\s]+$/) - { - print "This is not a valid package number list.\n"; - $found = 0; - } - else - { - $found = 1; - } - } - print "\n"; - if ($NUM_SCRIPT eq "98") { - $CHOOSEDPUBLISH{"ASSO"}=1; - } - else - { - if ($NUM_SCRIPT eq "99") { - $CHOOSEDPUBLISH{"SF"}=1; - } - else { - if ($NUM_SCRIPT eq "0") { - foreach my $key (@LISTETARGET) { - if ($key ne 'SNAPSHOT' && $key ne 'ASSO' && $key ne 'SF') { $CHOOSEDTARGET{$key}=1; } - } - } - else { - foreach my $num (split(/\s+/,$NUM_SCRIPT)) { - $CHOOSEDTARGET{$LISTETARGET[$num-1]}=1; - } - } - } - } + my $found=0; + my $NUM_SCRIPT; + my $cpt=0; + while (! $found) { + printf(" %2d - %-14s (%s)\n",$cpt,"ALL (1..9)","Need ".join(",",values %REQUIREMENTTARGET)); + foreach my $target (@LISTETARGET) { + $cpt++; + printf(" %2d - %-14s (%s)\n",$cpt,$target,"Need ".$REQUIREMENTTARGET{$target}); + } + $cpt=98; + printf(" %2d - %-14s (%s)\n",$cpt,"ASSO (publish)","Need ".join(",",values %REQUIREMENTPUBLISH)); + $cpt=99; + printf(" %2d - %-14s (%s)\n",$cpt,"SF (publish)","Need ".join(",",values %REQUIREMENTPUBLISH)); + + # Ask which target to build + print "Choose one package number or several separated with space (0 - ".$cpt."): "; + $NUM_SCRIPT=; + chomp($NUM_SCRIPT); + if ($NUM_SCRIPT !~ /^[0-9\s]+$/) + { + print "This is not a valid package number list.\n"; + $found = 0; + } + else + { + $found = 1; + } + } + print "\n"; + if ($NUM_SCRIPT eq "98") { + $CHOOSEDPUBLISH{"ASSO"}=1; + } + else + { + if ($NUM_SCRIPT eq "99") { + $CHOOSEDPUBLISH{"SF"}=1; + } + else { + if ($NUM_SCRIPT eq "0") { + foreach my $key (@LISTETARGET) { + if ($key ne 'SNAPSHOT' && $key ne 'ASSO' && $key ne 'SF') { $CHOOSEDTARGET{$key}=1; } + } + } + else { + foreach my $num (split(/\s+/,$NUM_SCRIPT)) { + $CHOOSEDTARGET{$LISTETARGET[$num-1]}=1; + } + } + } + } } # Test if requirement is ok @@ -265,34 +265,34 @@ foreach my $target (keys %CHOOSEDTARGET) { } $atleastonerpm=1; } - foreach my $req (split(/[,\s]/,$REQUIREMENTTARGET{$target})) - { - # Test - print "Test requirement for target $target: Search '$req'... "; - $newreq=$req; $newparam=''; - if ($newreq eq 'zip') { $newparam.='-h'; } - if ($newreq eq 'xz') { $newparam.='-h'; } - $cmd="\"$newreq\" $newparam 2>&1"; - print "Test command ".$cmd."... "; - $ret=`$cmd`; - $coderetour=$?; $coderetour2=$coderetour>>8; - if ($coderetour != 0 && (($coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i) || ($coderetour2 == 127 && $OS !~ /windows/)) && $PROGPATH) { - # Not found error, we try in PROGPATH - $ret=`"$PROGPATH/$ALTERNATEPATH{$req}/$req\" 2>&1`; - $coderetour=$?; $coderetour2=$coderetour>>8; - $REQUIREMENTTARGET{$target}="$PROGPATH/$ALTERNATEPATH{$req}/$req"; - } + foreach my $req (split(/[,\s]/,$REQUIREMENTTARGET{$target})) + { + # Test + print "Test requirement for target $target: Search '$req'... "; + $newreq=$req; $newparam=''; + if ($newreq eq 'zip') { $newparam.='-h'; } + if ($newreq eq 'xz') { $newparam.='-h'; } + $cmd="\"$newreq\" $newparam 2>&1"; + print "Test command ".$cmd."... "; + $ret=`$cmd`; + $coderetour=$?; $coderetour2=$coderetour>>8; + if ($coderetour != 0 && (($coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i) || ($coderetour2 == 127 && $OS !~ /windows/)) && $PROGPATH) { + # Not found error, we try in PROGPATH + $ret=`"$PROGPATH/$ALTERNATEPATH{$req}/$req\" 2>&1`; + $coderetour=$?; $coderetour2=$coderetour>>8; + $REQUIREMENTTARGET{$target}="$PROGPATH/$ALTERNATEPATH{$req}/$req"; + } - if ($coderetour != 0 && (($coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i) || ($coderetour2 == 127 && $OS !~ /windows/))) { - # Not found error - print "Not found\nCan't build target $target. Requirement '$req' not found in PATH\n"; - $CHOOSEDTARGET{$target}=-1; - last; - } else { - # Pas erreur ou erreur autre que programme absent - print " Found ".$req."\n"; - } - } + if ($coderetour != 0 && (($coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i) || ($coderetour2 == 127 && $OS !~ /windows/))) { + # Not found error + print "Not found\nCan't build target $target. Requirement '$req' not found in PATH\n"; + $CHOOSEDTARGET{$target}=-1; + last; + } else { + # Pas erreur ou erreur autre que programme absent + print " Found ".$req."\n"; + } + } } print "\n"; @@ -303,7 +303,7 @@ $nboftargetok=0; $nboftargetneedbuildroot=0; $nbofpublishneedtag=0; foreach my $target (keys %CHOOSEDTARGET) { - if ($CHOOSEDTARGET{$target} < 0) { next; } + if ($CHOOSEDTARGET{$target} < 0) { next; } if ($target ne 'EXE' && $target ne 'EXEDOLIWAMP') { $nboftargetneedbuildroot++; @@ -311,7 +311,7 @@ foreach my $target (keys %CHOOSEDTARGET) { $nboftargetok++; } foreach my $target (keys %CHOOSEDPUBLISH) { - if ($CHOOSEDPUBLISH{$target} < 0) { next; } + if ($CHOOSEDPUBLISH{$target} < 0) { next; } if ($target eq 'ASSO') { $nbofpublishneedtag++; } if ($target eq 'SF') { $nbofpublishneedtag++; } $nboftargetok++; @@ -319,714 +319,718 @@ foreach my $target (keys %CHOOSEDPUBLISH) { if ($nboftargetok) { - # Update CVS if required - #----------------------- - if ($nbofpublishneedtag) + # Update CVS if required + #----------------------- + if ($nbofpublishneedtag) { - print "Go to directory $SOURCE\n"; - $olddir=getcwd(); - chdir("$SOURCE"); - print 'Run git tag -a -m "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'" "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'"'."\n"; - $ret=`git tag -a -m "$MAJOR.$MINOR.$BUILD" "$MAJOR.$MINOR.$BUILD" 2>&1`; - if ($ret =~ /already exists/) - { - print "WARNING: Tag ".$MAJOR.'.'.$MINOR.'.'.$BUILD." already exists. Overwrite (y/N) ? "; - $QUESTIONOVERWRITETAG=; - chomp($QUESTIONOVERWRITETAG); - if ($QUESTIONOVERWRITETAG =~ /(o|y)/) - { - print 'Run git tag -a -f -m "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'" "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'"'."\n"; - $ret=`git tag -a -f -m "$MAJOR.$MINOR.$BUILD" "$MAJOR.$MINOR.$BUILD"`; - } - } - print 'Run git push --tags'."\n"; - $ret=`git push --tags`; - chdir("$olddir"); + print "Go to directory $SOURCE\n"; + $olddir=getcwd(); + chdir("$SOURCE"); + print 'Run git tag -a -m "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'" "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'"'."\n"; + $ret=`git tag -a -m "$MAJOR.$MINOR.$BUILD" "$MAJOR.$MINOR.$BUILD" 2>&1`; + if ($ret =~ /already exists/) + { + print "WARNING: Tag ".$MAJOR.'.'.$MINOR.'.'.$BUILD." already exists. Overwrite (y/N) ? "; + $QUESTIONOVERWRITETAG=; + chomp($QUESTIONOVERWRITETAG); + if ($QUESTIONOVERWRITETAG =~ /(o|y)/) + { + print 'Run git tag -a -f -m "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'" "'.$MAJOR.'.'.$MINOR.'.'.$BUILD.'"'."\n"; + $ret=`git tag -a -f -m "$MAJOR.$MINOR.$BUILD" "$MAJOR.$MINOR.$BUILD"`; + } + } + print 'Run git push --tags'."\n"; + $ret=`git push --tags`; + chdir("$olddir"); } - # Update buildroot if required - #----------------------------- - if ($nboftargetneedbuildroot) + # Update buildroot if required + #----------------------------- + if ($nboftargetneedbuildroot) { - if (! $copyalreadydone) { - print "Creation of a buildroot used for all packages\n"; + if (! $copyalreadydone) { + print "Creation of a buildroot used for all packages\n"; - print "Delete directory $BUILDROOT\n"; - $ret=`rm -fr "$BUILDROOT"`; - - mkdir "$BUILDROOT"; - mkdir "$BUILDROOT/$PROJECT"; - print "Copy $SOURCE into $BUILDROOT/$PROJECT\n"; - $ret=`cp -pr "$SOURCE" "$BUILDROOT/$PROJECT"`; + print "Delete directory $BUILDROOT\n"; + $ret=`rm -fr "$BUILDROOT"`; + + mkdir "$BUILDROOT"; + mkdir "$BUILDROOT/$PROJECT"; + print "Copy $SOURCE into $BUILDROOT/$PROJECT\n"; + $ret=`cp -pr "$SOURCE" "$BUILDROOT/$PROJECT"`; - #print "Copy $SOURCE/build/debian/apache/.htaccess into $BUILDROOT/$PROJECT/build/debian/apache/.htaccess\n"; - #$ret=`cp -pr "$SOURCE/build/debian/apache/.htaccess" "$BUILDROOT/$PROJECT/build/debian/apache/.htaccess"`; - } - print "Clean $BUILDROOT\n"; - $ret=`rm -f $BUILDROOT/$PROJECT/.buildpath`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.cache`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.externalToolBuilders`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.git*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.project`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.settings`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.scrutinizer.yml`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.travis.yml`; - $ret=`rm -fr $BUILDROOT/$PROJECT/.tx`; - $ret=`rm -f $BUILDROOT/$PROJECT/build.xml`; - $ret=`rm -f $BUILDROOT/$PROJECT/quickbuild.xml`; - $ret=`rm -f $BUILDROOT/$PROJECT/pom.xml`; - - $ret=`rm -fr $BUILDROOT/$PROJECT/build/html`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/Doli*-*`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.deb`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.dsc`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.tar.gz`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.deb`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.rpm`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tar`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tar.gz`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tgz`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.xz`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.zip`; - $ret=`rm -f $BUILDROOT/$PROJECT/build/doxygen/doxygen_warnings.log`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/cache.manifest`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.mysql`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.old`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.postgres`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf*sav*`; + #print "Copy $SOURCE/build/debian/apache/.htaccess into $BUILDROOT/$PROJECT/build/debian/apache/.htaccess\n"; + #$ret=`cp -pr "$SOURCE/build/debian/apache/.htaccess" "$BUILDROOT/$PROJECT/build/debian/apache/.htaccess"`; + } + print "Clean $BUILDROOT\n"; + $ret=`rm -f $BUILDROOT/$PROJECT/.buildpath`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.cache`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.externalToolBuilders`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.git*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.project`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.settings`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.scrutinizer.yml`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.travis.yml`; + $ret=`rm -fr $BUILDROOT/$PROJECT/.tx`; + $ret=`rm -f $BUILDROOT/$PROJECT/build.xml`; + $ret=`rm -f $BUILDROOT/$PROJECT/quickbuild.xml`; + $ret=`rm -f $BUILDROOT/$PROJECT/pom.xml`; + + $ret=`rm -fr $BUILDROOT/$PROJECT/build/html`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/Doli*-*`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.deb`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.dsc`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr_*.tar.gz`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.deb`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.rpm`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tar`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tar.gz`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.tgz`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.xz`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/dolibarr-*.zip`; + $ret=`rm -f $BUILDROOT/$PROJECT/build/doxygen/doxygen_warnings.log`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/cache.manifest`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.mysql`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.old`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf.php.postgres`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/conf/conf*sav*`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/mssql/README`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/mysql/README`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/pgsql/README`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/mssql/README`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/mysql/README`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/install/pgsql/README`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/install/mssql`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/install/mssql`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/codesniffer`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/codetemplates`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/dbmodel`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/initdata`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/iso-normes`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/ldap`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/licence`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/mail`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/phpcheckstyle`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/phpunit`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/security`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/spec`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/test`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/uml`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/vagrant`; - $ret=`rm -fr $BUILDROOT/$PROJECT/dev/xdebug`; - $ret=`rm -f $BUILDROOT/$PROJECT/dev/dolibarr_changes.txt`; - $ret=`rm -f $BUILDROOT/$PROJECT/dev/README`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot2.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot3.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot4.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot5.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot6.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot7.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot8.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot9.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot10.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot11.png`; - $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot12.png`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/codesniffer`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/codetemplates`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/dbmodel`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/initdata`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/iso-normes`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/ldap`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/licence`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/mail`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/phpcheckstyle`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/phpunit`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/security`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/spec`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/test`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/uml`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/vagrant`; + $ret=`rm -fr $BUILDROOT/$PROJECT/dev/xdebug`; + $ret=`rm -f $BUILDROOT/$PROJECT/dev/dolibarr_changes.txt`; + $ret=`rm -f $BUILDROOT/$PROJECT/dev/README`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot2.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot3.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot4.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot5.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot6.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot7.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot8.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot9.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot10.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot11.png`; + $ret=`rm -f $BUILDROOT/$PROJECT/doc/images/dolibarr_screenshot12.png`; - $ret=`rm -fr $BUILDROOT/$PROJECT/document`; - $ret=`rm -fr $BUILDROOT/$PROJECT/documents`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/document`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/documents`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/bootstrap*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/custom*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/multicompany*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/nltechno*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/pos*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/public/test`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/teclib*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/test`; - $ret=`rm -fr $BUILDROOT/$PROJECT/Thumbs.db $BUILDROOT/$PROJECT/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/*/*/Thumbs.db`; - $ret=`rm -f $BUILDROOT/$PROJECT/.cvsignore $BUILDROOT/$PROJECT/*/.cvsignore $BUILDROOT/$PROJECT/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/*/*/.cvsignore`; - $ret=`rm -f $BUILDROOT/$PROJECT/.gitignore $BUILDROOT/$PROJECT/*/.gitignore $BUILDROOT/$PROJECT/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/*/*/.gitignore`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/geoip/sample*.*`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/jqueryFileTree/connectors/jqueryFileTree.pl`; # Avoid errors into rpmlint - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/template`; # Package not valid for most linux distributions (errors reported into compile.js). Package should be embed by modules to avoid problems. - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpmailer`; # Package not valid for most linux distributions (errors reported into file LICENSE). Package should be embed by modules to avoid problems. - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/ckeditor/adapters`; # Keep this removal in case we embed libraries - #$ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/ckeditor/_source`; # _source must be kept into tarball - - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/datatables/extras/TableTools/swf`; # Source of this flash is not available - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/multiselect/MIT-LICENSE.txt`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/lib/Mail`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/samples`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/license.txt`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/PHPExcel/Shared/PDF`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/PHPExcel/Shared/PCLZip`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/dejavu-fonts-ttf-*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/freefont-*`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/utils`; - $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/LICENSE.TXT`; - $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/savant`; + $ret=`rm -fr $BUILDROOT/$PROJECT/document`; + $ret=`rm -fr $BUILDROOT/$PROJECT/documents`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/document`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/documents`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/ancotec*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/bootstrap*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/custom*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/factory*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/multicompany*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/nltechno*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/pos*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/public/test`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/teclib*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/themes/oblyon*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/themes/eldy/*.new`; + $ret=`rm -fr $BUILDROOT/$PROJECT/test`; + $ret=`rm -fr $BUILDROOT/$PROJECT/Thumbs.db $BUILDROOT/$PROJECT/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/*/Thumbs.db $BUILDROOT/$PROJECT/*/*/*/*/Thumbs.db`; + $ret=`rm -f $BUILDROOT/$PROJECT/.cvsignore $BUILDROOT/$PROJECT/*/.cvsignore $BUILDROOT/$PROJECT/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/*/.cvsignore $BUILDROOT/$PROJECT/*/*/*/*/*/*/.cvsignore`; + $ret=`rm -f $BUILDROOT/$PROJECT/.gitignore $BUILDROOT/$PROJECT/*/.gitignore $BUILDROOT/$PROJECT/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/*/.gitignore $BUILDROOT/$PROJECT/*/*/*/*/*/*/.gitignore`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/geoip/sample*.*`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/jqueryFileTree/connectors/jqueryFileTree.pl`; # Avoid errors into rpmlint + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/template`; # Package not valid for most linux distributions (errors reported into compile.js). Package should be embed by modules to avoid problems. + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpmailer`; # Package not valid for most linux distributions (errors reported into file LICENSE). Package should be embed by modules to avoid problems. + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/ckeditor/adapters`; # Keep this removal in case we embed libraries + #$ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/ckeditor/_source`; # _source must be kept into tarball due to debian policies + + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/datatables/extras/TableTools/swf`; # Source of this flash is not available + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/jquery/plugins/multiselect/MIT-LICENSE.txt`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/lib/Mail`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/nusoap/samples`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/license.txt`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/PHPExcel/Shared/PDF`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/phpexcel/PHPExcel/Shared/PCLZip`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/dejavu-fonts-ttf-*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/freefont-*`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/fonts/utils`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tcpdf/LICENSE.TXT`; + $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/savant`; } - # Build package for each target - #------------------------------ - foreach my $target (keys %CHOOSEDTARGET) - { - if ($CHOOSEDTARGET{$target} < 0) { next; } - - print "\nBuild package for target $target\n"; + # Build package for each target + #------------------------------ + foreach my $target (keys %CHOOSEDTARGET) + { + if ($CHOOSEDTARGET{$target} < 0) { next; } + + print "\nBuild package for target $target\n"; - if ($target eq 'SNAPSHOT') - { - $NEWDESTI=$DESTI; + if ($target eq 'SNAPSHOT') + { + $NEWDESTI=$DESTI; - print "Remove target $FILENAMESNAPSHOT.tgz...\n"; - unlink("$NEWDESTI/$FILENAMESNAPSHOT.tgz"); + print "Remove target $FILENAMESNAPSHOT.tgz...\n"; + unlink("$NEWDESTI/$FILENAMESNAPSHOT.tgz"); - #rmdir "$BUILDROOT/$FILENAMESNAPSHOT"; - $ret=`rm -fr $BUILDROOT/$FILENAMESNAPSHOT`; - print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMESNAPSHOT\n"; - $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMESNAPSHOT\""; - $ret=`$cmd`; + #rmdir "$BUILDROOT/$FILENAMESNAPSHOT"; + $ret=`rm -fr $BUILDROOT/$FILENAMESNAPSHOT`; + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMESNAPSHOT\n"; + $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMESNAPSHOT\""; + $ret=`$cmd`; - print "Compress $BUILDROOT into $FILENAMESNAPSHOT.tgz...\n"; - $cmd="tar --exclude doli*.tgz --exclude doli*.deb --exclude doli*.exe --exclude doli*.xz --exclude doli*.zip --exclude doli*.rpm --exclude .cache --exclude .settings --exclude conf.php --exclude conf.php.mysql --exclude conf.php.old --exclude conf.php.postgres --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$FILENAMESNAPSHOT.tgz\" $FILENAMESNAPSHOT"; + print "Compress $BUILDROOT into $FILENAMESNAPSHOT.tgz...\n"; + $cmd="tar --exclude doli*.tgz --exclude doli*.deb --exclude doli*.exe --exclude doli*.xz --exclude doli*.zip --exclude doli*.rpm --exclude .cache --exclude .settings --exclude conf.php --exclude conf.php.mysql --exclude conf.php.old --exclude conf.php.postgres --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$FILENAMESNAPSHOT.tgz\" $FILENAMESNAPSHOT"; print $cmd."\n"; $ret=`$cmd`; - # Move to final dir - print "Move $FILENAMESNAPSHOT.tgz to $NEWDESTI/$FILENAMESNAPSHOT.tgz\n"; - $ret=`mv "$FILENAMESNAPSHOT.tgz" "$NEWDESTI/$FILENAMESNAPSHOT.tgz"`; - next; - } + # Move to final dir + print "Move $FILENAMESNAPSHOT.tgz to $NEWDESTI/$FILENAMESNAPSHOT.tgz\n"; + $ret=`mv "$FILENAMESNAPSHOT.tgz" "$NEWDESTI/$FILENAMESNAPSHOT.tgz"`; + next; + } - if ($target eq 'TGZ') - { - $NEWDESTI=$DESTI; - mkdir($DESTI.'/standard'); + if ($target eq 'TGZ') + { + $NEWDESTI=$DESTI; + mkdir($DESTI.'/standard'); if (-d $DESTI.'/standard') { $NEWDESTI=$DESTI.'/standard'; } - print "Remove target $FILENAMETGZ.tgz...\n"; - unlink("$NEWDESTI/$FILENAMETGZ.tgz"); + print "Remove target $FILENAMETGZ.tgz...\n"; + unlink("$NEWDESTI/$FILENAMETGZ.tgz"); - #rmdir "$BUILDROOT/$FILENAMETGZ"; - $ret=`rm -fr $BUILDROOT/$FILENAMETGZ`; - print "Copy $BUILDROOT/$PROJECT/ to $BUILDROOT/$FILENAMETGZ\n"; - $cmd="cp -pr \"$BUILDROOT/$PROJECT/\" \"$BUILDROOT/$FILENAMETGZ\""; - $ret=`$cmd`; + #rmdir "$BUILDROOT/$FILENAMETGZ"; + $ret=`rm -fr $BUILDROOT/$FILENAMETGZ`; + print "Copy $BUILDROOT/$PROJECT/ to $BUILDROOT/$FILENAMETGZ\n"; + $cmd="cp -pr \"$BUILDROOT/$PROJECT/\" \"$BUILDROOT/$FILENAMETGZ\""; + $ret=`$cmd`; - $ret=`rm -fr $BUILDROOT/$FILENAMETGZ/build/exe`; + $ret=`rm -fr $BUILDROOT/$FILENAMETGZ/build/exe`; $ret=`rm -fr $BUILDROOT/$FILENAMETGZ/htdocs/includes/ckeditor/_source`; # We can't remove it with exclude file, we need it for some tarball packages - print "Compress $FILENAMETGZ into $FILENAMETGZ.tgz...\n"; - $cmd="tar --exclude-vcs --exclude-from \"$BUILDROOT/$PROJECT/build/tgz/tar_exclude.txt\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$BUILDROOT/$FILENAMETGZ.tgz\" $FILENAMETGZ"; - print "$cmd\n"; - $ret=`$cmd`; + print "Compress $FILENAMETGZ into $FILENAMETGZ.tgz...\n"; + $cmd="tar --exclude-vcs --exclude-from \"$BUILDROOT/$PROJECT/build/tgz/tar_exclude.txt\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$BUILDROOT/$FILENAMETGZ.tgz\" $FILENAMETGZ"; + print "$cmd\n"; + $ret=`$cmd`; - # Move to final dir - print "Move $BUILDROOT/$FILENAMETGZ.tgz to $NEWDESTI/$FILENAMETGZ.tgz\n"; - $ret=`mv "$BUILDROOT/$FILENAMETGZ.tgz" "$NEWDESTI/$FILENAMETGZ.tgz"`; - next; - } + # Move to final dir + print "Move $BUILDROOT/$FILENAMETGZ.tgz to $NEWDESTI/$FILENAMETGZ.tgz\n"; + $ret=`mv "$BUILDROOT/$FILENAMETGZ.tgz" "$NEWDESTI/$FILENAMETGZ.tgz"`; + next; + } - if ($target eq 'XZ') - { - $NEWDESTI=$DESTI; - mkdir($DESTI.'/standard'); + if ($target eq 'XZ') + { + $NEWDESTI=$DESTI; + mkdir($DESTI.'/standard'); if (-d $DESTI.'/standard') { $NEWDESTI=$DESTI.'/standard'; } - print "Remove target $FILENAMEXZ.xz...\n"; - unlink("$NEWDESTI/$FILENAMEXZ.xz"); + print "Remove target $FILENAMEXZ.xz...\n"; + unlink("$NEWDESTI/$FILENAMEXZ.xz"); - #rmdir "$BUILDROOT/$FILENAMEXZ"; - $ret=`rm -fr $BUILDROOT/$FILENAMEXZ`; - print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMEXZ\n"; - $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMEXZ\""; - $ret=`$cmd`; + #rmdir "$BUILDROOT/$FILENAMEXZ"; + $ret=`rm -fr $BUILDROOT/$FILENAMEXZ`; + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMEXZ\n"; + $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMEXZ\""; + $ret=`$cmd`; - $ret=`rm -fr $BUILDROOT/$FILENAMEXZ/build/exe`; + $ret=`rm -fr $BUILDROOT/$FILENAMEXZ/build/exe`; $ret=`rm -fr $BUILDROOT/$FILENAMEXZ/htdocs/includes/ckeditor/_source`; # We can't remove it with exclude file, we need it for some tarball packages - print "Compress $FILENAMEXZ into $FILENAMEXZ.xz...\n"; - - print "Go to directory $BUILDROOT\n"; - $olddir=getcwd(); - chdir("$BUILDROOT"); - $cmd= "xz -9 -r $BUILDROOT/$FILENAMEAPS.xz \*"; + print "Compress $FILENAMEXZ into $FILENAMEXZ.xz...\n"; + + print "Go to directory $BUILDROOT\n"; + $olddir=getcwd(); + chdir("$BUILDROOT"); + $cmd= "xz -9 -r $BUILDROOT/$FILENAMEAPS.xz \*"; print $cmd."\n"; $ret= `$cmd`; - chdir("$olddir"); + chdir("$olddir"); - # Move to final dir - print "Move $FILENAMEXZ.xz to $NEWDESTI/$FILENAMEXZ.xz\n"; - $ret=`mv "$BUILDROOT/$FILENAMEXZ.xz" "$NEWDESTI/$FILENAMEXZ.xz"`; - next; - } - - if ($target eq 'ZIP') - { - $NEWDESTI=$DESTI; - mkdir($DESTI.'/standard'); + # Move to final dir + print "Move $FILENAMEXZ.xz to $NEWDESTI/$FILENAMEXZ.xz\n"; + $ret=`mv "$BUILDROOT/$FILENAMEXZ.xz" "$NEWDESTI/$FILENAMEXZ.xz"`; + next; + } + + if ($target eq 'ZIP') + { + $NEWDESTI=$DESTI; + mkdir($DESTI.'/standard'); if (-d $DESTI.'/standard') { $NEWDESTI=$DESTI.'/standard'; } - print "Remove target $FILENAMEZIP.zip...\n"; - unlink("$NEWDESTI/$FILENAMEZIP.zip"); + print "Remove target $FILENAMEZIP.zip...\n"; + unlink("$NEWDESTI/$FILENAMEZIP.zip"); - #rmdir "$BUILDROOT/$FILENAMEZIP"; - $ret=`rm -fr $BUILDROOT/$FILENAMEZIP`; - print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMEZIP\n"; - $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMEZIP\""; - $ret=`$cmd`; + #rmdir "$BUILDROOT/$FILENAMEZIP"; + $ret=`rm -fr $BUILDROOT/$FILENAMEZIP`; + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMEZIP\n"; + $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$FILENAMEZIP\""; + $ret=`$cmd`; - $ret=`rm -fr $BUILDROOT/$FILENAMEZIP/build/exe`; + $ret=`rm -fr $BUILDROOT/$FILENAMEZIP/build/exe`; $ret=`rm -fr $BUILDROOT/$FILENAMEZIP/htdocs/includes/ckeditor/_source`; # We can't remove it with exclude file, we need it for some tarball packages - print "Compress $FILENAMEZIP into $FILENAMEZIP.zip...\n"; - - print "Go to directory $BUILDROOT\n"; - $olddir=getcwd(); - chdir("$BUILDROOT"); - $cmd= "7z a -r -tzip -xr\@\"$BUILDROOT\/$FILENAMEZIP\/build\/zip\/zip_exclude.txt\" -mx $BUILDROOT/$FILENAMEZIP.zip $FILENAMEZIP\/*"; + print "Compress $FILENAMEZIP into $FILENAMEZIP.zip...\n"; + + print "Go to directory $BUILDROOT\n"; + $olddir=getcwd(); + chdir("$BUILDROOT"); + $cmd= "7z a -r -tzip -xr\@\"$BUILDROOT\/$FILENAMEZIP\/build\/zip\/zip_exclude.txt\" -mx $BUILDROOT/$FILENAMEZIP.zip $FILENAMEZIP\/*"; print $cmd."\n"; $ret= `$cmd`; - chdir("$olddir"); - - # Move to final dir - print "Move $FILENAMEZIP.zip to $NEWDESTI/$FILENAMEZIP.zip\n"; - $ret=`mv "$BUILDROOT/$FILENAMEZIP.zip" "$NEWDESTI/$FILENAMEZIP.zip"`; - next; - } - - if ($target =~ /RPM/) # Linux only - { - $NEWDESTI=$DESTI; - $subdir="package_rpm_generic"; - if ($target =~ /FEDO/i) { $subdir="package_rpm_redhat-fedora"; } - if ($target =~ /MAND/i) { $subdir="package_rpm_mandriva"; } - if ($target =~ /OPEN/i) { $subdir="package_rpm_opensuse"; } - mkdir($DESTI.'/'.$subdir); + chdir("$olddir"); + + # Move to final dir + print "Move $FILENAMEZIP.zip to $NEWDESTI/$FILENAMEZIP.zip\n"; + $ret=`mv "$BUILDROOT/$FILENAMEZIP.zip" "$NEWDESTI/$FILENAMEZIP.zip"`; + next; + } + + if ($target =~ /RPM/) # Linux only + { + $NEWDESTI=$DESTI; + $subdir="package_rpm_generic"; + if ($target =~ /FEDO/i) { $subdir="package_rpm_redhat-fedora"; } + if ($target =~ /MAND/i) { $subdir="package_rpm_mandriva"; } + if ($target =~ /OPEN/i) { $subdir="package_rpm_opensuse"; } + mkdir($DESTI.'/'.$subdir); if (-d $DESTI.'/'.$subdir) { $NEWDESTI=$DESTI.'/'.$subdir; } if ($RPMDIR eq "") { $RPMDIR=$ENV{'HOME'}."/rpmbuild"; } - print "Version is $MAJOR.$MINOR.$REL1-$RPMSUBVERSION\n"; + print "Version is $MAJOR.$MINOR.$REL1-$RPMSUBVERSION\n"; - print "Remove target ".$FILENAMERPM."...\n"; - unlink("$NEWDESTI/".$FILENAMERPM); - print "Remove target ".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm...\n"; - unlink("$NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm"); + print "Remove target ".$FILENAMERPM."...\n"; + unlink("$NEWDESTI/".$FILENAMERPM); + print "Remove target ".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm...\n"; + unlink("$NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION.".src.rpm"); - print "Create directory $BUILDROOT/$FILENAMETGZ2\n"; - $ret=`rm -fr $BUILDROOT/$FILENAMETGZ2`; - - print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMETGZ2\n"; - $cmd="cp -pr '$BUILDROOT/$PROJECT' '$BUILDROOT/$FILENAMETGZ2'"; - $ret=`$cmd`; + print "Create directory $BUILDROOT/$FILENAMETGZ2\n"; + $ret=`rm -fr $BUILDROOT/$FILENAMETGZ2`; + + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$FILENAMETGZ2\n"; + $cmd="cp -pr '$BUILDROOT/$PROJECT' '$BUILDROOT/$FILENAMETGZ2'"; + $ret=`$cmd`; - # Removed files we don't need - $ret=`rm -fr $BUILDROOT/$FILENAMETGZ2/htdocs/includes/ckeditor/_source`; + # Removed files we don't need + $ret=`rm -fr $BUILDROOT/$FILENAMETGZ2/htdocs/includes/ckeditor/_source`; - print "Set permissions on files/dir\n"; - $ret=`chmod -R 755 $BUILDROOT/$FILENAMETGZ2`; - $cmd="find $BUILDROOT/$FILENAMETGZ2 -type f -exec chmod 644 {} \\; "; - $ret=`$cmd`; + print "Set permissions on files/dir\n"; + $ret=`chmod -R 755 $BUILDROOT/$FILENAMETGZ2`; + $cmd="find $BUILDROOT/$FILENAMETGZ2 -type f -exec chmod 644 {} \\; "; + $ret=`$cmd`; # Build tgz - print "Compress $FILENAMETGZ2 into $FILENAMETGZ2.tgz...\n"; - $ret=`tar --exclude-from "$SOURCE/build/tgz/tar_exclude.txt" --directory "$BUILDROOT" -czvf "$BUILDROOT/$FILENAMETGZ2.tgz" $FILENAMETGZ2`; + print "Compress $FILENAMETGZ2 into $FILENAMETGZ2.tgz...\n"; + $ret=`tar --exclude-from "$SOURCE/build/tgz/tar_exclude.txt" --directory "$BUILDROOT" -czvf "$BUILDROOT/$FILENAMETGZ2.tgz" $FILENAMETGZ2`; - print "Move $BUILDROOT/$FILENAMETGZ2.tgz to $RPMDIR/SOURCES/$FILENAMETGZ2.tgz\n"; - $cmd="mv $BUILDROOT/$FILENAMETGZ2.tgz $RPMDIR/SOURCES/$FILENAMETGZ2.tgz"; - $ret=`$cmd`; + print "Move $BUILDROOT/$FILENAMETGZ2.tgz to $RPMDIR/SOURCES/$FILENAMETGZ2.tgz\n"; + $cmd="mv $BUILDROOT/$FILENAMETGZ2.tgz $RPMDIR/SOURCES/$FILENAMETGZ2.tgz"; + $ret=`$cmd`; - $BUILDFIC="${FILENAME}.spec"; - $BUILDFICSRC="${FILENAME}_generic.spec"; - if ($target =~ /FEDO/i) { $BUILDFICSRC="${FILENAME}_fedora.spec"; } - if ($target =~ /MAND/i) { $BUILDFICSRC="${FILENAME}_mandriva.spec"; } - if ($target =~ /OPEN/i) { $BUILDFICSRC="${FILENAME}_opensuse.spec"; } - - print "Generate file $BUILDROOT/$BUILDFIC from $SOURCE/build/rpm/${BUILDFICSRC}\n"; - open (SPECFROM,"<$SOURCE/build/rpm/${BUILDFICSRC}") || die "Error"; - open (SPECTO,">$BUILDROOT/$BUILDFIC") || die "Error"; - while () { - $_ =~ s/__FILENAMETGZ__/$FILENAMETGZ/; - $_ =~ s/__VERSION__/$MAJOR.$MINOR.$REL1/; - $_ =~ s/__RELEASE__/$RPMSUBVERSION/; - print SPECTO $_; - } - close SPECFROM; - close SPECTO; - - print "Copy patch file to $RPMDIR/SOURCES\n"; - $ret=`cp "$SOURCE/build/rpm/dolibarr-forrpm.patch" "$RPMDIR/SOURCES"`; - $ret=`chmod 644 $RPMDIR/SOURCES/dolibarr-forrpm.patch`; + $BUILDFIC="${FILENAME}.spec"; + $BUILDFICSRC="${FILENAME}_generic.spec"; + if ($target =~ /FEDO/i) { $BUILDFICSRC="${FILENAME}_fedora.spec"; } + if ($target =~ /MAND/i) { $BUILDFICSRC="${FILENAME}_mandriva.spec"; } + if ($target =~ /OPEN/i) { $BUILDFICSRC="${FILENAME}_opensuse.spec"; } + + print "Generate file $BUILDROOT/$BUILDFIC from $SOURCE/build/rpm/${BUILDFICSRC}\n"; + open (SPECFROM,"<$SOURCE/build/rpm/${BUILDFICSRC}") || die "Error"; + open (SPECTO,">$BUILDROOT/$BUILDFIC") || die "Error"; + while () { + $_ =~ s/__FILENAMETGZ__/$FILENAMETGZ/; + $_ =~ s/__VERSION__/$MAJOR.$MINOR.$REL1/; + $_ =~ s/__RELEASE__/$RPMSUBVERSION/; + print SPECTO $_; + } + close SPECFROM; + close SPECTO; + + print "Copy patch file to $RPMDIR/SOURCES\n"; + $ret=`cp "$SOURCE/build/rpm/dolibarr-forrpm.patch" "$RPMDIR/SOURCES"`; + $ret=`chmod 644 $RPMDIR/SOURCES/dolibarr-forrpm.patch`; - print "Launch RPM build (rpmbuild --clean -ba $BUILDROOT/${BUILDFIC})\n"; - #$ret=`rpmbuild -vvvv --clean -ba $BUILDROOT/${BUILDFIC}`; - $ret=`rpmbuild --clean -ba $BUILDROOT/${BUILDFIC}`; + print "Launch RPM build (rpmbuild --clean -ba $BUILDROOT/${BUILDFIC})\n"; + #$ret=`rpmbuild -vvvv --clean -ba $BUILDROOT/${BUILDFIC}`; + $ret=`rpmbuild --clean -ba $BUILDROOT/${BUILDFIC}`; - # Move to final dir - print "Move $RPMDIR/RPMS/".$ARCH."/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm into $NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm\n"; - $cmd="mv $RPMDIR/RPMS/".$ARCH."/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm \"$NEWDESTI/\""; - $ret=`$cmd`; - print "Move $RPMDIR/SRPMS/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm into $NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm\n"; - $cmd="mv $RPMDIR/SRPMS/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm \"$NEWDESTI/\""; - $ret=`$cmd`; - print "Move $RPMDIR/SOURCES/".$FILENAMETGZ2.".tgz into $NEWDESTI/".$FILENAMETGZ2.".tgz\n"; - $cmd="mv \"$RPMDIR/SOURCES/".$FILENAMETGZ2.".tgz\" \"$NEWDESTI/".$FILENAMETGZ2.".tgz\""; - $ret=`$cmd`; - next; - } + # Move to final dir + print "Move $RPMDIR/RPMS/".$ARCH."/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm into $NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm\n"; + $cmd="mv $RPMDIR/RPMS/".$ARCH."/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.".$ARCH.".rpm \"$NEWDESTI/\""; + $ret=`$cmd`; + print "Move $RPMDIR/SRPMS/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm into $NEWDESTI/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm\n"; + $cmd="mv $RPMDIR/SRPMS/".$FILENAMETGZ2."-".$RPMSUBVERSION."*.src.rpm \"$NEWDESTI/\""; + $ret=`$cmd`; + print "Move $RPMDIR/SOURCES/".$FILENAMETGZ2.".tgz into $NEWDESTI/".$FILENAMETGZ2.".tgz\n"; + $cmd="mv \"$RPMDIR/SOURCES/".$FILENAMETGZ2.".tgz\" \"$NEWDESTI/".$FILENAMETGZ2.".tgz\""; + $ret=`$cmd`; + next; + } - if ($target eq 'DEB') - { - $NEWDESTI=$DESTI; - mkdir($DESTI.'/package_debian-ubuntu'); + if ($target eq 'DEB') + { + $NEWDESTI=$DESTI; + mkdir($DESTI.'/package_debian-ubuntu'); if (-d $DESTI.'/package_debian-ubuntu') { $NEWDESTI=$DESTI.'/package_debian-ubuntu'; } - $olddir=getcwd(); + $olddir=getcwd(); - print "Remove target ${FILENAMEDEB}_all.deb...\n"; - unlink("$NEWDESTI/${FILENAMEDEB}_all.deb"); - print "Remove target ${FILENAMEDEB}.dsc...\n"; - unlink("$NEWDESTI/${FILENAMEDEB}.dsc"); - print "Remove target ${FILENAMEDEB}.tar.gz...\n"; - unlink("$NEWDESTI/${FILENAMEDEB}.tar.gz"); - print "Remove target ${FILENAMEDEB}.changes...\n"; - unlink("$NEWDESTI/${FILENAMEDEB}.changes"); - print "Remove target ${FILENAMEDEB}.debian.tar.gz...\n"; - unlink("$NEWDESTI/${FILENAMEDEB}.debian.tar.gz"); - print "Remove target ${FILENAMEDEBNATIVE}.orig.tar.gz...\n"; - unlink("$NEWDESTI/${FILENAMEDEBNATIVE}.orig.tar.gz"); + print "Remove target ${FILENAMEDEB}_all.deb...\n"; + unlink("$NEWDESTI/${FILENAMEDEB}_all.deb"); + print "Remove target ${FILENAMEDEB}.dsc...\n"; + unlink("$NEWDESTI/${FILENAMEDEB}.dsc"); + print "Remove target ${FILENAMEDEB}.tar.gz...\n"; + unlink("$NEWDESTI/${FILENAMEDEB}.tar.gz"); + print "Remove target ${FILENAMEDEB}.changes...\n"; + unlink("$NEWDESTI/${FILENAMEDEB}.changes"); + print "Remove target ${FILENAMEDEB}.debian.tar.gz...\n"; + unlink("$NEWDESTI/${FILENAMEDEB}.debian.tar.gz"); + print "Remove target ${FILENAMEDEBNATIVE}.orig.tar.gz...\n"; + unlink("$NEWDESTI/${FILENAMEDEBNATIVE}.orig.tar.gz"); - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp`; - $ret=`rm -fr $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build`; - + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp`; + $ret=`rm -fr $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build`; + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$PROJECT.tmp\n"; $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$PROJECT.tmp\""; $ret=`$cmd`; $cmd="cp -pr \"$BUILDROOT/$PROJECT/build/debian/apache/.htaccess\" \"$BUILDROOT/$PROJECT.tmp/build/debian/apache/.htaccess\""; $ret=`$cmd`; - print "Remove other files\n"; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/README-FR`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/README`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/README-FR`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/aps`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/dmg`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/pad/README`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/tgz/README`; - #$ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian/po`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian/source`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/changelog`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/compat`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/control*`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/copyright`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.config`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.desktop`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.docs`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.install`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.lintian-overrides`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.postrm`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.postinst`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.templates`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.templates.futur`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/rules`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/README.Debian`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/README.howto`; - $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/watch`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/doap`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/exe`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/launchpad`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/live`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/patch`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/perl`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/rpm`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/zip`; - # Removed duplicate license files - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/plugins/scayt/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/plugins/wsc/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/plugins/scayt/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/plugins/wsc/LICENSE.md`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/jquery/plugins/flot/LICENSE.txt`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/tcpdf/fonts/dejavu-fonts-ttf-2.34/LICENSE`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/tcpdf/fonts/freefont-20120503/COPYING`; - # Removed files we don't need - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source`; - - # Rename upstream changelog to match debian rules + print "Remove other files\n"; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/README-FR`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/README`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/README-FR`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/aps`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/dmg`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/pad/README`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/tgz/README`; + #$ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian/po`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/debian/source`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/changelog`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/compat`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/control*`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/copyright`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.config`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.desktop`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.docs`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.install`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.lintian-overrides`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.postrm`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.postinst`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.templates`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/dolibarr.templates.futur`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/rules`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/README.Debian`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/README.howto`; + $ret=`rm -f $BUILDROOT/$PROJECT.tmp/build/debian/watch`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/doap`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/exe`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/launchpad`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/live`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/patch`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/perl`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/rpm`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/build/zip`; + # Removed duplicate license files + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/plugins/scayt/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source/plugins/wsc/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/plugins/scayt/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/plugins/wsc/LICENSE.md`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/jquery/plugins/flot/LICENSE.txt`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/tcpdf/fonts/dejavu-fonts-ttf-2.34/LICENSE`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/tcpdf/fonts/freefont-20120503/COPYING`; + # Removed files we don't need + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/htdocs/includes/ckeditor/_source`; + + # Rename upstream changelog to match debian rules $ret=`mv $BUILDROOT/$PROJECT.tmp/ChangeLog $BUILDROOT/$PROJECT.tmp/changelog`; - # Prepare source package (init debian dir) - print "Create directory $BUILDROOT/$PROJECT.tmp/debian\n"; - $ret=`mkdir "$BUILDROOT/$PROJECT.tmp/debian"`; - print "Copy $SOURCE/build/debian/xxx to $BUILDROOT/$PROJECT.tmp/debian\n"; - # Add files for dpkg-source - $ret=`cp -f "$SOURCE/build/debian/changelog" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/compat" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/control" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/copyright" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.desktop" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.docs" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.install" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.lintian-overrides" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.xpm" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/rules" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/watch" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -fr "$SOURCE/build/debian/patches" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -fr "$SOURCE/build/debian/po" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -fr "$SOURCE/build/debian/source" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -fr "$SOURCE/build/debian/apache" "$BUILDROOT/$PROJECT.tmp/debian/apache"`; - $ret=`cp -f "$SOURCE/build/debian/apache/.htaccess" "$BUILDROOT/$PROJECT.tmp/debian/apache"`; - $ret=`cp -fr "$SOURCE/build/debian/lighttpd" "$BUILDROOT/$PROJECT.tmp/debian/lighttpd"`; - # Add files also required to build binary package - $ret=`cp -f "$SOURCE/build/debian/dolibarr.config" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.postinst" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.postrm" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/dolibarr.templates" "$BUILDROOT/$PROJECT.tmp/debian"`; - $ret=`cp -f "$SOURCE/build/debian/install.forced.php.install" "$BUILDROOT/$PROJECT.tmp/debian"`; - + # Prepare source package (init debian dir) + print "Create directory $BUILDROOT/$PROJECT.tmp/debian\n"; + $ret=`mkdir "$BUILDROOT/$PROJECT.tmp/debian"`; + print "Copy $SOURCE/build/debian/xxx to $BUILDROOT/$PROJECT.tmp/debian\n"; + # Add files for dpkg-source + $ret=`cp -f "$SOURCE/build/debian/changelog" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/compat" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/control" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/copyright" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.desktop" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.docs" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.install" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.lintian-overrides" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.xpm" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/rules" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/watch" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -fr "$SOURCE/build/debian/patches" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -fr "$SOURCE/build/debian/po" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -fr "$SOURCE/build/debian/source" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -fr "$SOURCE/build/debian/apache" "$BUILDROOT/$PROJECT.tmp/debian/apache"`; + $ret=`cp -f "$SOURCE/build/debian/apache/.htaccess" "$BUILDROOT/$PROJECT.tmp/debian/apache"`; + $ret=`cp -fr "$SOURCE/build/debian/lighttpd" "$BUILDROOT/$PROJECT.tmp/debian/lighttpd"`; + # Add files also required to build binary package + $ret=`cp -f "$SOURCE/build/debian/dolibarr.config" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.postinst" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.postrm" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/dolibarr.templates" "$BUILDROOT/$PROJECT.tmp/debian"`; + $ret=`cp -f "$SOURCE/build/debian/install.forced.php.install" "$BUILDROOT/$PROJECT.tmp/debian"`; + # Set owners and permissions - #print "Set owners on files/dir\n"; - #$ret=`chown -R root.root $BUILDROOT/$PROJECT.tmp`; + #print "Set owners on files/dir\n"; + #$ret=`chown -R root.root $BUILDROOT/$PROJECT.tmp`; - print "Set permissions on files/dir\n"; - $ret=`chmod -R 755 $BUILDROOT/$PROJECT.tmp`; - $cmd="find $BUILDROOT/$PROJECT.tmp -type f -exec chmod 644 {} \\; "; - $ret=`$cmd`; - $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.php' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.dpatch' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.pl' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - $cmd="find $BUILDROOT/$PROJECT.tmp/dev -name '*.php' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - $ret=`chmod 755 $BUILDROOT/$PROJECT.tmp/debian/rules`; - $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/translation/autotranslator.class.php`; - $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/modMyModule.class.php`; - $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_class.class.php`; - $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_page.php`; - $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_webservice_server.php`; - $cmd="find $BUILDROOT/$PROJECT.tmp/scripts -name '*.php' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - $cmd="find $BUILDROOT/$PROJECT.tmp/scripts -name '*.sh' -type f -exec chmod 755 {} \\; "; - $ret=`$cmd`; - - - print "Rename directory $BUILDROOT/$PROJECT.tmp into $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build\n"; - $cmd="mv $BUILDROOT/$PROJECT.tmp $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"; - $ret=`$cmd`; + print "Set permissions on files/dir\n"; + $ret=`chmod -R 755 $BUILDROOT/$PROJECT.tmp`; + $cmd="find $BUILDROOT/$PROJECT.tmp -type f -exec chmod 644 {} \\; "; + $ret=`$cmd`; + $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.php' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.dpatch' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + $cmd="find $BUILDROOT/$PROJECT.tmp/build -name '*.pl' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + $cmd="find $BUILDROOT/$PROJECT.tmp/dev -name '*.php' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + $ret=`chmod 755 $BUILDROOT/$PROJECT.tmp/debian/rules`; + $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/translation/autotranslator.class.php`; + $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/modMyModule.class.php`; + $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_class.class.php`; + $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_page.php`; + $ret=`chmod -R 644 $BUILDROOT/$PROJECT.tmp/dev/skeletons/skeleton_webservice_server.php`; + $cmd="find $BUILDROOT/$PROJECT.tmp/scripts -name '*.php' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + $cmd="find $BUILDROOT/$PROJECT.tmp/scripts -name '*.sh' -type f -exec chmod 755 {} \\; "; + $ret=`$cmd`; + + + print "Rename directory $BUILDROOT/$PROJECT.tmp into $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build\n"; + $cmd="mv $BUILDROOT/$PROJECT.tmp $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"; + $ret=`$cmd`; - print "Go into directory $BUILDROOT\n"; - chdir("$BUILDROOT"); + print "Go into directory $BUILDROOT\n"; + chdir("$BUILDROOT"); # We need a tarball to be able to build "quilt" debian package (not required for native but we need patch so it is not a native) - print "Compress $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build into $BUILDROOT/$FILENAMEDEBNATIVE.orig.tar.gz...\n"; - $cmd="tar --exclude-vcs --exclude-from \"$BUILDROOT/$PROJECT/build/tgz/tar_exclude.txt\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$BUILDROOT/$FILENAMEDEBNATIVE.orig.tar.gz\" $PROJECT-$MAJOR.$MINOR.$build"; - print $cmd."\n"; - $ret=`$cmd`; + print "Compress $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build into $BUILDROOT/$FILENAMEDEBNATIVE.orig.tar.gz...\n"; + $cmd="tar --exclude-vcs --exclude-from \"$BUILDROOT/$PROJECT/build/tgz/tar_exclude.txt\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$BUILDROOT/$FILENAMEDEBNATIVE.orig.tar.gz\" $PROJECT-$MAJOR.$MINOR.$build"; + print $cmd."\n"; + $ret=`$cmd`; # Creation of source package - print "Go into directory $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build\n"; - chdir("$BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"); - #$cmd="dpkg-source -b $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"; - $cmd="dpkg-buildpackage -us -uc"; - print "Launch DEB build ($cmd)\n"; - $ret=`$cmd 2>&1 3>&1`; - print $ret."\n"; + print "Go into directory $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build\n"; + chdir("$BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"); + #$cmd="dpkg-source -b $BUILDROOT/$PROJECT-$MAJOR.$MINOR.$build"; + $cmd="dpkg-buildpackage -us -uc"; + print "Launch DEB build ($cmd)\n"; + $ret=`$cmd 2>&1 3>&1`; + print $ret."\n"; - chdir("$olddir"); - - print "You can check bin package with lintian --pedantic -E -I \"$NEWDESTI/${FILENAMEDEB}_all.deb\"\n"; - print "You can check src package with lintian --pedantic -E -I \"$NEWDESTI/${FILENAMEDEB}.dsc\"\n"; - - # Move to final dir - print "Move *_all.deb *.dsc *.orig.tar.gz *.changes to $NEWDESTI\n"; - $ret=`mv $BUILDROOT/*_all.deb "$NEWDESTI/"`; - $ret=`mv $BUILDROOT/*.dsc "$NEWDESTI/"`; - $ret=`mv $BUILDROOT/*.orig.tar.gz "$NEWDESTI/"`; - $ret=`mv $BUILDROOT/*.debian.tar.gz "$NEWDESTI/"`; - $ret=`mv $BUILDROOT/*.changes "$NEWDESTI/"`; - next; - } - - if ($target eq 'APS') - { + chdir("$olddir"); + + print "You can check bin package with lintian --pedantic -E -I \"$NEWDESTI/${FILENAMEDEB}_all.deb\"\n"; + print "You can check src package with lintian --pedantic -E -I \"$NEWDESTI/${FILENAMEDEB}.dsc\"\n"; + + # Move to final dir + print "Move *_all.deb *.dsc *.orig.tar.gz *.changes to $NEWDESTI\n"; + $ret=`mv $BUILDROOT/*_all.deb "$NEWDESTI/"`; + $ret=`mv $BUILDROOT/*.dsc "$NEWDESTI/"`; + $ret=`mv $BUILDROOT/*.orig.tar.gz "$NEWDESTI/"`; + $ret=`mv $BUILDROOT/*.debian.tar.gz "$NEWDESTI/"`; + $ret=`mv $BUILDROOT/*.changes "$NEWDESTI/"`; + next; + } + + if ($target eq 'APS') + { $NEWDESTI=$DESTI; - mkdir($DESTI.'/package_aps'); + mkdir($DESTI.'/package_aps'); if (-d $DESTI.'/package_aps') { $NEWDESTI=$DESTI.'/package_aps'; } - $newbuild = $BUILD; - $newbuild =~ s/(dev|alpha)/0/gi; # dev - $newbuild =~ s/beta/1/gi; # beta - $newbuild =~ s/rc./2/gi; # rc - if ($newbuild !~ /-/) { $newbuild.='-3'; } # finale - # now newbuild is 0-0 or 0-3 for example - $REL1 = $newbuild; $REL1 =~ s/-.*$//gi; - if ($RPMSUBVERSION eq 'auto') { $RPMSUBVERSION = $newbuild; $RPMSUBVERSION =~ s/^.*-//gi; } - print "Version is $MAJOR.$MINOR.$REL1-$RPMSUBVERSION\n"; - - print "Remove target $FILENAMEAPS.zip...\n"; - unlink "$NEWDESTI/$FILENAMEAPS.zip"; - - #rmdir "$BUILDROOT/$PROJECT.tmp"; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp`; - print "Create directory $BUILDROOT/$PROJECT.tmp\n"; - $ret=`mkdir -p "$BUILDROOT/$PROJECT.tmp"`; - print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$PROJECT.tmp\n"; - $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$PROJECT.tmp\""; - $ret=`$cmd`; + $newbuild = $BUILD; + $newbuild =~ s/(dev|alpha)/0/gi; # dev + $newbuild =~ s/beta/1/gi; # beta + $newbuild =~ s/rc./2/gi; # rc + if ($newbuild !~ /-/) { $newbuild.='-3'; } # finale + # now newbuild is 0-0 or 0-3 for example + $REL1 = $newbuild; $REL1 =~ s/-.*$//gi; + if ($RPMSUBVERSION eq 'auto') { $RPMSUBVERSION = $newbuild; $RPMSUBVERSION =~ s/^.*-//gi; } + print "Version is $MAJOR.$MINOR.$REL1-$RPMSUBVERSION\n"; + + print "Remove target $FILENAMEAPS.zip...\n"; + unlink "$NEWDESTI/$FILENAMEAPS.zip"; - print "Remove other files\n"; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/deb`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/dmg`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/doap`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/exe`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/live`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/patch`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/rpm`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/zip`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/perl`; + #rmdir "$BUILDROOT/$PROJECT.tmp"; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp`; + print "Create directory $BUILDROOT/$PROJECT.tmp\n"; + $ret=`mkdir -p "$BUILDROOT/$PROJECT.tmp"`; + print "Copy $BUILDROOT/$PROJECT to $BUILDROOT/$PROJECT.tmp\n"; + $cmd="cp -pr \"$BUILDROOT/$PROJECT\" \"$BUILDROOT/$PROJECT.tmp\""; + $ret=`$cmd`; - $APSVERSION="1.2"; - print "Create APS files $BUILDROOT/$PROJECT.tmp/$PROJECT/APP-META.xml\n"; - open (SPECFROM,"<$BUILDROOT/$PROJECT/build/aps/APP-META-$APSVERSION.xml") || die "Error"; - open (SPECTO,">$BUILDROOT/$PROJECT.tmp/$PROJECT/APP-META.xml") || die "Error"; - while () { - $newbuild = $BUILD; - $newbuild =~ s/(dev|alpha)/0/gi; # dev - $newbuild =~ s/beta/1/gi; # beta - $newbuild =~ s/rc./2/gi; # rc - if ($newbuild !~ /-/) { $newbuild.='-3'; } # finale - # now newbuild is 0-0 or 0-3 for example - $_ =~ s/__VERSION__/$MAJOR.$MINOR.$REL1/; - $_ =~ s/__RELEASE__/$RPMSUBVERSION/; - print SPECTO $_; - } - close SPECFROM; - close SPECTO; - print "Version set to $MAJOR.$MINOR.$newbuild\n"; - #$cmd="cp -pr \"$BUILDROOT/$PROJECT/build/aps/configure\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/scripts/configure\""; - #$ret=`$cmd`; - $cmd="cp -pr \"$BUILDROOT/$PROJECT/build/aps/configure.php\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/scripts/configure.php\""; - $ret=`$cmd`; - $cmd="cp -pr \"$BUILDROOT/$PROJECT/doc/images\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/images\""; - $ret=`$cmd`; - - print "Remove other files\n"; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/dev`; - $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/doc`; - - print "Build APP-LIST.xml files\n"; - - print "Compress $BUILDROOT/$PROJECT.tmp/$PROJECT into $FILENAMEAPS.zip...\n"; - - print "Go to directory $BUILDROOT/$PROJECT.tmp\/$PROJECT\n"; - $olddir=getcwd(); - chdir("$BUILDROOT\/$PROJECT.tmp\/$PROJECT"); - $cmd= "zip -9 -r $BUILDROOT/$FILENAMEAPS.zip \*"; - print $cmd."\n"; - $ret= `$cmd`; - chdir("$olddir"); - - # Move to final dir - print "Move $BUILDROOT/$FILENAMEAPS.zip to $NEWDESTI/$FILENAMEAPS.zip\n"; - $ret=`mv "$BUILDROOT/$FILENAMEAPS.zip" "$NEWDESTI/$FILENAMEAPS.zip"`; - next; - } + print "Remove other files\n"; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/deb`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/dmg`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/doap`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/exe`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/live`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/patch`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/rpm`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/zip`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/build/perl`; - if ($target eq 'EXEDOLIWAMP') - { - $NEWDESTI=$DESTI; - mkdir($DESTI.'/package_windows'); + $APSVERSION="1.2"; + print "Create APS files $BUILDROOT/$PROJECT.tmp/$PROJECT/APP-META.xml\n"; + open (SPECFROM,"<$BUILDROOT/$PROJECT/build/aps/APP-META-$APSVERSION.xml") || die "Error"; + open (SPECTO,">$BUILDROOT/$PROJECT.tmp/$PROJECT/APP-META.xml") || die "Error"; + while () { + $newbuild = $BUILD; + $newbuild =~ s/(dev|alpha)/0/gi; # dev + $newbuild =~ s/beta/1/gi; # beta + $newbuild =~ s/rc./2/gi; # rc + if ($newbuild !~ /-/) { $newbuild.='-3'; } # finale + # now newbuild is 0-0 or 0-3 for example + $_ =~ s/__VERSION__/$MAJOR.$MINOR.$REL1/; + $_ =~ s/__RELEASE__/$RPMSUBVERSION/; + print SPECTO $_; + } + close SPECFROM; + close SPECTO; + print "Version set to $MAJOR.$MINOR.$newbuild\n"; + #$cmd="cp -pr \"$BUILDROOT/$PROJECT/build/aps/configure\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/scripts/configure\""; + #$ret=`$cmd`; + $cmd="cp -pr \"$BUILDROOT/$PROJECT/build/aps/configure.php\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/scripts/configure.php\""; + $ret=`$cmd`; + $cmd="cp -pr \"$BUILDROOT/$PROJECT/doc/images\" \"$BUILDROOT/$PROJECT.tmp/$PROJECT/images\""; + $ret=`$cmd`; + + print "Remove other files\n"; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/dev`; + $ret=`rm -fr $BUILDROOT/$PROJECT.tmp/$PROJECT/doc`; + + print "Build APP-LIST.xml files\n"; + + print "Compress $BUILDROOT/$PROJECT.tmp/$PROJECT into $FILENAMEAPS.zip...\n"; + + print "Go to directory $BUILDROOT/$PROJECT.tmp\/$PROJECT\n"; + $olddir=getcwd(); + chdir("$BUILDROOT\/$PROJECT.tmp\/$PROJECT"); + $cmd= "zip -9 -r $BUILDROOT/$FILENAMEAPS.zip \*"; + print $cmd."\n"; + $ret= `$cmd`; + chdir("$olddir"); + + # Move to final dir + print "Move $BUILDROOT/$FILENAMEAPS.zip to $NEWDESTI/$FILENAMEAPS.zip\n"; + $ret=`mv "$BUILDROOT/$FILENAMEAPS.zip" "$NEWDESTI/$FILENAMEAPS.zip"`; + next; + } + + if ($target eq 'EXEDOLIWAMP') + { + $NEWDESTI=$DESTI; + mkdir($DESTI.'/package_windows'); if (-d $DESTI.'/package_windows') { $NEWDESTI=$DESTI.'/package_windows'; } - - print "Remove target $FILENAMEEXEDOLIWAMP.exe...\n"; - unlink "$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"; - - $SOURCEBACK=$SOURCE; - $SOURCEBACK =~ s/\//\\/g; - print "Compil exe $FILENAMEEXEDOLIWAMP.exe file from iss file \"$SOURCEBACK\\build\\exe\\doliwamp\\doliwamp.iss\"\n"; - $cmd= "ISCC.exe \"$SOURCEBACK\\build\\exe\\doliwamp\\doliwamp.iss\""; + + print "Remove target $FILENAMEEXEDOLIWAMP.exe...\n"; + unlink "$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"; + + $SOURCEBACK=$SOURCE; + $SOURCEBACK =~ s/\//\\/g; + print "Compil exe $FILENAMEEXEDOLIWAMP.exe file from iss file \"$SOURCEBACK\\build\\exe\\doliwamp\\doliwamp.iss\"\n"; + $cmd= "ISCC.exe \"$SOURCEBACK\\build\\exe\\doliwamp\\doliwamp.iss\""; print "$cmd\n"; $ret= `$cmd`; #print "$ret\n"; - # Move to final dir + # Move to final dir print "Move \"$SOURCE\\build\\$FILENAMEEXEDOLIWAMP.exe\" to $NEWDESTI/$FILENAMEEXEDOLIWAMP.exe\n"; - rename("$SOURCE/build/$FILENAMEEXEDOLIWAMP.exe","$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"); - print "Move $SOURCE/build/$FILENAMEEXEDOLIWAMP.exe to $NEWDESTI/$FILENAMEEXEDOLIWAMP.exe\n"; - $ret=`mv "$SOURCE/build/$FILENAMEEXEDOLIWAMP.exe" "$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"`; - next; - } - } + rename("$SOURCE/build/$FILENAMEEXEDOLIWAMP.exe","$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"); + print "Move $SOURCE/build/$FILENAMEEXEDOLIWAMP.exe to $NEWDESTI/$FILENAMEEXEDOLIWAMP.exe\n"; + $ret=`mv "$SOURCE/build/$FILENAMEEXEDOLIWAMP.exe" "$NEWDESTI/$FILENAMEEXEDOLIWAMP.exe"`; + next; + } + } - # Build package for each target - #------------------------------ - foreach my $target (keys %CHOOSEDPUBLISH) - { - if ($CHOOSEDPUBLISH{$target} < 0) { next; } - + # Publish package for each target + #-------------------------------- + foreach my $target (keys %CHOOSEDPUBLISH) + { + if ($CHOOSEDPUBLISH{$target} < 0) { next; } + print "\nList of files to publish\n"; - %filestoscansf=( - "$DESTI/package_rpm_generic/$FILENAMERPM"=>'Dolibarr installer for Fedora-Redhat-Mandriva-Opensuse (DoliRpm)', - "$DESTI/package_debian-ubuntu/${FILENAMEDEB}_all.deb"=>'Dolibarr installer for Debian-Ubuntu (DoliDeb)', - "$DESTI/package_windows/$FILENAMEEXEDOLIWAMP.exe"=>'Dolibarr installer for Windows (DoliWamp)', - "$DESTI/standard/$FILENAMETGZ.tgz"=>'Dolibarr ERP-CRM', - "$DESTI/standard/$FILENAMETGZ.zip"=>'Dolibarr ERP-CRM' - ); - use POSIX qw/strftime/; - foreach my $file (sort keys %filestoscansf) - { - $found=0; - my $filesize = -s $file; - my $filedate = (stat $file)[9]; - print $file." ".($filesize?"(found)":"(not found)"); - print ($filesize?" - ".$filesize:""); - print ($filedate?" - ".strftime("%Y-%m-%d %H:%M:%S",localtime($filedate)):""); - print "\n"; - } + %filestoscansf=( + "$DESTI/package_rpm_generic/$FILENAMERPM"=>'Dolibarr installer for Fedora-Redhat-Mandriva-Opensuse (DoliRpm)', + "$DESTI/package_debian-ubuntu/${FILENAMEDEB}_all.deb"=>'Dolibarr installer for Debian-Ubuntu (DoliDeb)', + "$DESTI/package_windows/$FILENAMEEXEDOLIWAMP.exe"=>'Dolibarr installer for Windows (DoliWamp)', + "$DESTI/standard/$FILENAMETGZ.tgz"=>'Dolibarr ERP-CRM', + "$DESTI/standard/$FILENAMETGZ.zip"=>'Dolibarr ERP-CRM' + ); + use POSIX qw/strftime/; + foreach my $file (sort keys %filestoscansf) + { + $found=0; + my $filesize = -s $file; + my $filedate = (stat $file)[9]; + print $file." ".($filesize?"(found)":"(not found)"); + print ($filesize?" - ".$filesize:""); + print ($filedate?" - ".strftime("%Y-%m-%d %H:%M:%S",localtime($filedate)):""); + print "\n"; + } - if ($target eq 'SF' || $target eq 'ASSO') - { - print "\n"; - - if ($target eq 'SF') { $PUBLISH = $PUBLISHSTABLE; } + if ($target eq 'SF' || $target eq 'ASSO') + { + print "\n"; + + if ($target eq 'SF') { $PUBLISH = $PUBLISHSTABLE; } if ($target eq 'ASSO' && $BUILD =~ /[a-z]/i) { $PUBLISH = $PUBLISHBETARC.'/lastbuild'; } if ($target eq 'ASSO' && $BUILD =~ /^[0-9]+$/) { $PUBLISH = $PUBLISHBETARC.'/stable'; } - $NEWPUBLISH=$PUBLISH; - print "Publish to target $NEWPUBLISH. Click enter or CTRL+C...\n"; + $NEWPUBLISH=$PUBLISH; + print "Publish to target $NEWPUBLISH. Click enter or CTRL+C...\n"; - # Ask which target to build - $NUM_SCRIPT=; - chomp($NUM_SCRIPT); + # Ask which target to build + $NUM_SCRIPT=; + chomp($NUM_SCRIPT); print "Create empty dir /tmp/emptydir. We need it to create target dir using rsync.\n"; - $ret=`mkdir -p "/tmp/emptydir/"`; - - %filestoscan=%filestoscansf; - - foreach my $file (sort keys %filestoscan) - { - $found=0; - my $filesize = -s $file; - if (! $filesize) { next; } + $ret=`mkdir -p "/tmp/emptydir/"`; + + %filestoscan=%filestoscansf; + + foreach my $file (sort keys %filestoscan) + { + $found=0; + my $filesize = -s $file; + if (! $filesize) { next; } print "\n"; - print "Publish file ".$file." to ".$filestoscan{$file}."\n"; - - $destFolder="$NEWPUBLISH/$filestoscan{$file}/".$MAJOR.'.'.$MINOR.'.'.$BUILD; + print "Publish file ".$file." to ".$filestoscan{$file}."\n"; + + $destFolder="$NEWPUBLISH/$filestoscan{$file}/".$MAJOR.'.'.$MINOR.'.'.$BUILD; # mkdir #my $ssh = Net::SSH::Perl->new("frs.sourceforge.net"); #$ssh->login("$user","$pass"); - #use String::ShellQuote qw( shell_quote ); + #use String::ShellQuote qw( shell_quote ); #$ssh->cmd('mkdir '.shell_quote($destFolder).' && exit'); #use Net::SFTP::Foreign; @@ -1045,25 +1049,23 @@ if ($nboftargetok) { print "$command\n"; my $ret=`$command 2>&1`; print "$ret\n"; - - } - - } - } + } + } + } } print "\n----- Summary -----\n"; foreach my $target (keys %CHOOSEDTARGET) { - if ($CHOOSEDTARGET{$target} < 0) { - print "Package $target not built (bad requirement).\n"; - } else { - print "Package $target built successfully in $DESTI\n"; - } + if ($CHOOSEDTARGET{$target} < 0) { + print "Package $target not built (bad requirement).\n"; + } else { + print "Package $target built successfully in $DESTI\n"; + } } if (! $batch) { - print "\nPress key to finish..."; - my $WAITKEY=; + print "\nPress key to finish..."; + my $WAITKEY=; } 0; diff --git a/build/makepack-dolibarrlang.pl b/build/makepack-dolibarrlang.pl deleted file mode 100755 index 6066a678d7c..00000000000 --- a/build/makepack-dolibarrlang.pl +++ /dev/null @@ -1,300 +0,0 @@ -#!/usr/bin/perl -#---------------------------------------------------------------------------- -# \file build/makepack-dolibarrlang.pl -# \brief Package builder (tgz, zip, rpm, deb, exe) -# \author (c)2005 Laurent Destailleur -#---------------------------------------------------------------------------- - -use Cwd; - -$PROJECT = "dolibarr"; - -@LISTETARGET = ("TGZ"); # Possible packages -%REQUIREMENTTARGET = ( # Tool requirement for each package - "TGZ" => "tar", - "ZIP" => "7z", - "EXE" => "makensis.exe" -); -%ALTERNATEPATH = ( - "7z" => "7-ZIP", - "makensis.exe" => "NSIS" -); - -use vars qw/ $REVISION $VERSION /; -$REVISION = '1.10'; -$VERSION = "1.0 (build $REVISION)"; - -#------------------------------------------------------------------------------ -# MAIN -#------------------------------------------------------------------------------ -( $DIR = $0 ) =~ s/([^\/\\]+)$//; -( $PROG = $1 ) =~ s/\.([^\.]*)$//; -$Extension = $1; -$DIR ||= '.'; -$DIR =~ s/([^\/\\])[\\\/]+$/$1/; - -# Detect OS type -# -------------- -if ( "$^O" =~ /linux/i || ( -d "/etc" && -d "/var" && "$^O" !~ /cygwin/i ) ) { - $OS = 'linux'; - $CR = ''; -} -elsif ( -d "/etc" && -d "/Users" ) { $OS = 'macosx'; $CR = ''; } -elsif ( "$^O" =~ /cygwin/i || "$^O" =~ /win32/i ) { - $OS = 'windows'; - $CR = "\r"; -} -if ( !$OS ) { - print "$PROG.$Extension was not able to detect your OS.\n"; - print "Can't continue.\n"; - print "$PROG.$Extension aborted.\n"; - sleep 2; - exit 1; -} - -# Define buildroot -# ---------------- -if ( $OS =~ /linux/ ) { - $TEMP = $ENV{"TEMP"} || $ENV{"TMP"} || "/tmp"; -} -if ( $OS =~ /macos/ ) { - $TEMP = $ENV{"TEMP"} || $ENV{"TMP"} || "/tmp"; -} -if ( $OS =~ /windows/ ) { - $TEMP = $ENV{"TEMP"} || $ENV{"TMP"} || "c:/temp"; - $PROGPATH = $ENV{"ProgramFiles"}; -} -if ( !$TEMP || !-d $TEMP ) { - print "Error: A temporary directory can not be find.\n"; - print "Check that TEMP or TMP environment variable is set correctly.\n"; - print "makepack-dolibarrlang.pl aborted.\n"; - sleep 2; - exit 2; -} -$BUILDROOT = "$TEMP/dolibarr-buildroot"; - -my $copyalreadydone = 0; -my $batch = 0; - -print "Makepack langs version $VERSION\n"; -print "Enter language code to package (en_US, fr_FR, ...) : "; -$PROJECT = ; -chomp($PROJECT); - -# Ask and set version $MAJOR and $MINOR -print "Enter value for version: "; -$PROJVERSION = ; -chomp($PROJVERSION); -( $MAJOR, $MINOR ) = split( /\./, $PROJVERSION, 2 ); -if ( $MINOR eq '' ) { - print "Enter value for minor version: "; - $MINOR = ; - chomp($MINOR); -} - -$FILENAME = "$PROJECT"; -$FILENAMETGZ = "lang_$PROJECT-$MAJOR.$MINOR"; -if ( -d "/usr/src/redhat" ) { - - # redhat - $RPMDIR = "/usr/src/redhat"; -} -if ( -d "/usr/src/RPM" ) { - - # mandrake - $RPMDIR = "/usr/src/RPM"; -} - -$SOURCE = "$DIR/../../dolibarr"; -$DESTI = "$SOURCE/build"; - -# Choose package targets -#----------------------- -$target = "ZIP"; # Les langs sont au format zip -if ($target) { - $CHOOSEDTARGET{ uc($target) } = 1; -} -else { - my $found = 0; - my $NUM_SCRIPT; - while ( !$found ) { - my $cpt = 0; - printf( " %d - %3s (%s)\n", - $cpt, "All", "Need " . join( ",", values %REQUIREMENTTARGET ) ); - foreach my $target (@LISTETARGET) { - $cpt++; - printf( " %d - %3s (%s)\n", - $cpt, $target, "Need " . $REQUIREMENTTARGET{$target} ); - } - - # Are asked to select the file to move - print "Choose one package number or several separated with space: "; - $NUM_SCRIPT = ; - chomp($NUM_SCRIPT); - if ( $NUM_SCRIPT =~ s/-//g ) { - - # Do not do copy - $copyalreadydone = 1; - } - if ( $NUM_SCRIPT !~ /^[0-$cpt\s]+$/ ) { - print "This is not a valid package number list.\n"; - $found = 0; - } - else { - $found = 1; - } - } - print "\n"; - if ($NUM_SCRIPT) { - foreach my $num ( split( /\s+/, $NUM_SCRIPT ) ) { - $CHOOSEDTARGET{ $LISTETARGET[ $num - 1 ] } = 1; - } - } - else { - foreach my $key (@LISTETARGET) { - $CHOOSEDTARGET{$key} = 1; - } - } -} - -# Test if requirement is ok -#-------------------------- -foreach my $target ( keys %CHOOSEDTARGET ) { - foreach my $req ( split( /[,\s]/, $REQUIREMENTTARGET{$target} ) ) { - - # Test - print "Test requirement for target $target: Search '$req'... "; - $ret = `"$req" 2>&1`; - $coderetour = $?; - $coderetour2 = $coderetour >> 8; - if ( - $coderetour != 0 - && ( ( $coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i ) - || ( $coderetour2 == 127 && $OS !~ /windows/ ) ) - && $PROGPATH - ) - { - - # Not found error, we try in PROGPATH - $ret = `"$PROGPATH/$ALTERNATEPATH{$req}/$req\" 2>&1`; - $coderetour = $?; - $coderetour2 = $coderetour >> 8; - $REQUIREMENTTARGET{$target} = "$PROGPATH/$ALTERNATEPATH{$req}/$req"; - } - - if ( - $coderetour != 0 - && ( ( $coderetour2 == 1 && $OS =~ /windows/ && $ret !~ /Usage/i ) - || ( $coderetour2 == 127 && $OS !~ /windows/ ) ) - ) - { - - # Not found error - print -"Not found\nCan't build target $target. Requirement '$req' not found in PATH\n"; - $CHOOSEDTARGET{$target} = -1; - last; - } - else { - - # Pas erreur ou erreur autre que programme absent - print " Found " . $REQUIREMENTTARGET{$target} . "\n"; - } - } -} - -print "\n"; - -# Check if there is at least on target to build -#---------------------------------------------- -$nboftargetok = 0; -foreach my $target ( keys %CHOOSEDTARGET ) { - if ( $CHOOSEDTARGET{$target} < 0 ) { next; } - $nboftargetok++; -} - -if ($nboftargetok) { - - # Update buildroot - #----------------- - if ( !$copyalreadydone ) { - print "Delete directory $BUILDROOT\n"; - $ret = `rm -fr "$BUILDROOT"`; - mkdir "$BUILDROOT"; - mkdir "$BUILDROOT/htdocs"; - mkdir "$BUILDROOT/htdocs/langs"; - mkdir "$BUILDROOT/htdocs/langs/$PROJECT"; - - print "Copy $SOURCE into $BUILDROOT\n"; - mkdir "$BUILDROOT"; - $ret = - `cp -pr "$SOURCE/htdocs/langs/$PROJECT" "$BUILDROOT/htdocs/langs"`; - } - print "Clean $BUILDROOT\n"; - $ret = -`rm -fr $BUILDROOT/htdocs/langs/$PROJECT/Thumbs.db $BUILDROOT/htdocs/langs/$PROJECT/*/Thumbs.db $BUILDROOT/htdocs/langs/$PROJECT/*/*/Thumbs.db $BUILDROOT/htdocs/langs/$PROJECT/*/*/*/Thumbs.db`; - $ret = -`rm -fr $BUILDROOT/htdocs/langs/$PROJECT/CVS* $BUILDROOT/htdocs/langs/$PROJECT/*/CVS* $BUILDROOT/htdocs/langs/$PROJECT/*/*/CVS* $BUILDROOT/htdocs/langs/$PROJECT/*/*/*/CVS* $BUILDROOT/htdocs/langs/$PROJECT/*/*/*/*/CVS* $BUILDROOT/htdocs/langs/$PROJECT/*/*/*/*/*/CVS*`; - - # Build package for each target - #------------------------------ - foreach my $target ( keys %CHOOSEDTARGET ) - { - if ( $CHOOSEDTARGET{$target} < 0 ) { next; } - - print "\nBuild package for target $target\n"; - - if ( $target eq 'TGZ' ) - { - unlink $FILENAMETGZ . tgz; - - # unlink $BUILDROOT/$FILENAMETGZ.tgz; - print "Compress $BUILDROOT/htdocs into $FILENAMETGZ.tgz...\n"; - $cmd = -"tar --exclude-vcs --exclude-from \"$DESTI/tgz/tar.exclude\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$FILENAMETGZ.tgz\" htdocs"; - $ret = `$cmd`; - -# $cmd="tar --exclude-vcs --exclude-from \"$DESTI/tgz/tar.exclude\" --directory \"$BUILDROOT\" --mode=go-w --group=500 --owner=500 -czvf \"$BUILDROOT/$FILENAMETGZ.tgz\" htdocs\n"; -# $ret=`$cmd`; - if ( $OS =~ /windows/i ) { - print "Move $FILENAMETGZ.tgz to $DESTI/$FILENAMETGZ.tgz\n"; - $ret = `mv "$FILENAMETGZ.tgz" "$DESTI/$FILENAMETGZ.tgz"`; - - # $ret=`mv "$BUILDROOT/$FILENAMETGZ.tgz" "$DESTI/$FILENAMETGZ.tgz"`; - } - next; - } - - if ( $target eq 'ZIP' ) - { - unlink $FILENAMEZIP . zip; - print "Compress $FILENAMETGZ into $FILENAMEZIP.zip...\n"; - chdir("$BUILDROOT"); - -#print "cd $BUILDROOTNT & 7z a -r -tzip -mx $BUILDROOT/$FILENAMEZIP.zip $FILENAMETGZ\\*.*\n"; -#$ret=`cd $BUILDROOTNT & 7z a -r -tzip -mx $BUILDROOT/$FILENAMEZIP.zip $FILENAMETGZ\\*.*`; - $ret = - `7z a -r -tzip -mx $BUILDROOT/$FILENAMEZIP.zip $FILENAMETGZ\\*.*`; - print "Move $FILENAMEZIP.zip to $DESTI\n"; - rename( "$BUILDROOT/$FILENAMEZIP.zip", "$DESTI/$FILENAMEZIP.zip" ); - next; - } - } -} - -print "\n----- Summary -----\n"; -foreach my $target ( keys %CHOOSEDTARGET ) { - if ( $CHOOSEDTARGET{$target} < 0 ) { - print "Package $target not built (bad requirement).\n"; - } - else { - print "Package $target built succeessfully in $DESTI\n"; - } -} - -if ( !$btach ) { - print "\nPress key to finish..."; - my $WAITKEY = ; -} - -0; diff --git a/build/obs/README b/build/obs/README index 8fc4c27d9b2..fefe6dbd91d 100644 --- a/build/obs/README +++ b/build/obs/README @@ -29,12 +29,18 @@ To submit a snapshot for building, we should have a service file with content How to have such a service file created automatically ? -Click on "Add file", then select mode "Upload From: Remote URL" -Enter the Remote URL that should looks like this: http://www.dolibarr.org/files/stable/package_rpm_generic/dolibarr-x.y.v-3.src.rpm -Then add into advanded - attributes +Go into project you want to update. It mught 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.3.src.rpm + +Then add into Advanded - Attributes OBS:Screenshots http://www.dolibarr.org/images/dolibarr_screenshot1.png -OBS:QualityCategory Testing +OBS:QualityCategory Stable|Testing|Development|Private # Move project into official directory diff --git a/build/rpm/conf.php b/build/rpm/conf.php index 2e8bd46cf0f..406ba3145c1 100755 --- a/build/rpm/conf.php +++ b/build/rpm/conf.php @@ -5,4 +5,3 @@ // // This file will be filled by installer // -?> \ No newline at end of file diff --git a/build/rpm/dolibarr_fedora.spec b/build/rpm/dolibarr_fedora.spec index 7dc332f0432..37bcdf8e96b 100755 --- a/build/rpm/dolibarr_fedora.spec +++ b/build/rpm/dolibarr_fedora.spec @@ -162,7 +162,6 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/bookmarks -%_datadir/dolibarr/htdocs/boutique %_datadir/dolibarr/htdocs/cashdesk %_datadir/dolibarr/htdocs/categories %_datadir/dolibarr/htdocs/comm @@ -333,6 +332,9 @@ fi # version x.y.z-0.1.a for alpha, x.y.z-0.2.b for beta, x.y.z-0.3 for release %changelog +* Wed Oct 29 2014 Laurent Destailleur 3.7.0-0.3 +- Upstream release + * Wed Sep 24 2014 Laurent Destailleur 3.6.1-0.3 - Upstream release diff --git a/build/rpm/dolibarr_generic.spec b/build/rpm/dolibarr_generic.spec index 1949398ecc2..812e0d3a1c0 100755 --- a/build/rpm/dolibarr_generic.spec +++ b/build/rpm/dolibarr_generic.spec @@ -242,7 +242,6 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/bookmarks -%_datadir/dolibarr/htdocs/boutique %_datadir/dolibarr/htdocs/cashdesk %_datadir/dolibarr/htdocs/categories %_datadir/dolibarr/htdocs/comm @@ -569,6 +568,9 @@ fi # version x.y.z-0.1.a for alpha, x.y.z-0.2.b for beta, x.y.z-0.3 for release %changelog +* Wed Oct 29 2014 Laurent Destailleur 3.7.0-0.3 +- Upstream release + * Wed Sep 24 2014 Laurent Destailleur 3.6.1-0.3 - Upstream release diff --git a/build/rpm/dolibarr_mandriva.spec b/build/rpm/dolibarr_mandriva.spec index 0331a0a9cc3..5a81827f5fa 100755 --- a/build/rpm/dolibarr_mandriva.spec +++ b/build/rpm/dolibarr_mandriva.spec @@ -159,7 +159,6 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/bookmarks -%_datadir/dolibarr/htdocs/boutique %_datadir/dolibarr/htdocs/cashdesk %_datadir/dolibarr/htdocs/categories %_datadir/dolibarr/htdocs/comm @@ -338,6 +337,9 @@ fi # version x.y.z-0.1.a for alpha, x.y.z-0.2.b for beta, x.y.z-0.3 for release %changelog +* Wed Oct 29 2014 Laurent Destailleur 3.7.0-0.3 +- Upstream release + * Wed Sep 24 2014 Laurent Destailleur 3.6.1-0.3 - Upstream release diff --git a/build/rpm/dolibarr_opensuse.spec b/build/rpm/dolibarr_opensuse.spec index f85cc0fa7a0..5d1e1e19765 100755 --- a/build/rpm/dolibarr_opensuse.spec +++ b/build/rpm/dolibarr_opensuse.spec @@ -170,7 +170,6 @@ done >>%{name}.lang %_datadir/dolibarr/htdocs/asterisk %_datadir/dolibarr/htdocs/barcode %_datadir/dolibarr/htdocs/bookmarks -%_datadir/dolibarr/htdocs/boutique %_datadir/dolibarr/htdocs/cashdesk %_datadir/dolibarr/htdocs/categories %_datadir/dolibarr/htdocs/comm @@ -349,6 +348,9 @@ fi # version x.y.z-0.1.a for alpha, x.y.z-0.2.b for beta, x.y.z-0.3 for release %changelog +* Wed Oct 29 2014 Laurent Destailleur 3.7.0-0.3 +- Upstream release + * Wed Sep 24 2014 Laurent Destailleur 3.6.1-0.3 - Upstream release diff --git a/composer.json b/composer.json index 4463efcfc74..f0de86ce7ea 100644 --- a/composer.json +++ b/composer.json @@ -24,6 +24,8 @@ "ext-mcrypt": "*", "ext-openssl": "*", "ext-mbstring": "*", - "ext-soap": "*" + "ext-soap": "*", + "ext-zip": "*", + "ext-xml": "*" } } diff --git a/dev/codesniffer/ruleset.xml b/dev/codesniffer/ruleset.xml index 38ea1310d22..ffbc1bace39 100755 --- a/dev/codesniffer/ruleset.xml +++ b/dev/codesniffer/ruleset.xml @@ -6,15 +6,22 @@ */conf.php */includes/* */documents/* + */dev/vagrant/* */custom/* */nltechno* + + + 0 + + + @@ -24,9 +31,6 @@ 0 - - - @@ -105,7 +109,7 @@ - + @@ -153,6 +157,10 @@ + + + + @@ -162,6 +170,40 @@ 0 + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + diff --git a/dev/detectduplicatelangkey.sh b/dev/detectduplicatelangkey.sh deleted file mode 100755 index 06d9cd8a69e..00000000000 --- a/dev/detectduplicatelangkey.sh +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -# Helps find duplicate translation keys in language files -# -# Copyright (C) 2014 Raphaël Doursenaud - rdoursenaud@gpcsolutions.fr - -for file in `find . -type f` -do - dupes=$( - sed "s/^\s*//" "$file" | # Remove any leading whitespace - sed "s/\s*\=/=/" | # Remove any whitespace before = - grep -Po "(^.*?)=" | # Non greedeely match everything before = - sed "s/\=//" | # Remove trailing = so we get the key - sort | uniq -d # Find duplicates - ) - - if [ -n "$dupes" ] - then - echo "Duplicates found in $file" - echo "$dupes" - fi -done diff --git a/dev/fixnotabfiles.sh b/dev/detectnotabfiles.sh similarity index 91% rename from dev/fixnotabfiles.sh rename to dev/detectnotabfiles.sh index 3e5d28966c9..c89b999b03d 100755 --- a/dev/fixnotabfiles.sh +++ b/dev/detectnotabfiles.sh @@ -1,6 +1,6 @@ #!/bin/sh #------------------------------------------------------ -# Script to find files that are not Unix encoded +# Detect files that does not contains any tab inside # # Laurent Destailleur - eldy@users.sourceforge.net #------------------------------------------------------ diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 7f3490da165..f63969ea170 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -44,6 +44,8 @@ In htdocs/includes/tcpdf/tcpdf.php - protected $default_monospaced_font = 'courier'; + protected $default_monospaced_font = 'freemono'; +* Renamed getmypid into dol_getmypid(). + JSGANTT: -------- diff --git a/dev/fixduplicatelangkey.sh b/dev/fixduplicatelangkey.sh new file mode 100755 index 00000000000..2d9cb7f7a85 --- /dev/null +++ b/dev/fixduplicatelangkey.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Helps find duplicate translation keys in language files +# +# Copyright (C) 2014 Raphaël Doursenaud - rdoursenaud@gpcsolutions.fr + + +# Syntax +if [ "x$1" != "xlist" -a "x$1" != "xfix" ] +then + echo "Usage: detectduplicatelangkey.sh (list|fix)" +fi + + +if [ "x$1" = "xlist" ] +then + for file in `find htdocs/langs/en_US -name *.lang -type f` + do + dupes=$( + sed "s/^\s*//" "$file" | # Remove any leading whitespace + sed "s/\s*\=/=/" | # Remove any whitespace before = + grep -Po "(^.*?)=" | # Non greedeely match everything before = + sed "s/\=//" | # Remove trailing = so we get the key + sort | uniq -d # Find duplicates + ) + + if [ -n "$dupes" ] + then + echo "Duplicates found in $file" + echo "$dupes" + fi + done +fi + +# To convert +if [ "x$1" = "xfix" ] +then + echo Feature not implemented. Please fix files manually. +fi diff --git a/dev/fixperms.sh b/dev/fixperms.sh index 731e45cf703..5844e8b2916 100755 --- a/dev/fixperms.sh +++ b/dev/fixperms.sh @@ -25,4 +25,6 @@ then find ./htdocs -type f -iname "*.php" -exec chmod a-x {} \; chmod a+x ./scripts/*/*.php chmod a+x ./scripts/*/*.sh + chmod g-w ./scripts/*/*.php + chmod g-w ./scripts/*/*.sh fi diff --git a/dev/initdata/generate-facture.php b/dev/initdata/generate-facture.php index 0316671d62b..5c630454ba7 100755 --- a/dev/initdata/generate-facture.php +++ b/dev/initdata/generate-facture.php @@ -94,7 +94,7 @@ while ($i < GEN_NUMBER_FACTURE && $result >= 0) print "Invoice ".$i." for socid ".$socid; - $facture = new Facture($db, $socids[$socid]); + $facture = new Facture($db); $facture->date = time(); $facture->cond_reglement_id = 3; $facture->mode_reglement_id = 3; diff --git a/dev/initdata/generate-propale.php b/dev/initdata/generate-propale.php index a62df516481..2efd2af2f08 100755 --- a/dev/initdata/generate-propale.php +++ b/dev/initdata/generate-propale.php @@ -122,7 +122,7 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0) $soc = new Societe($db); - $propal = new Propal($db, $socids[$socid]); + $propal = new Propal($db); $obj = $conf->global->PROPALE_ADDON; $modPropale = new $obj; @@ -130,6 +130,7 @@ while ($i < GEN_NUMBER_PROPAL && $result >= 0) $propal->ref = $numpr; $propal->contactid = $contids[$socids[$socid]][0]; + $propal->socid = $socids[$socid]; $propal->datep = time(); $propal->cond_reglement_id = 3; $propal->mode_reglement_id = 3; diff --git a/dev/initdata/mysqldump_dolibarr_3.6.0.sql b/dev/initdata/mysqldump_dolibarr_3.6.0.sql index 77cbbcc511f..b1b8d77aa3c 100644 --- a/dev/initdata/mysqldump_dolibarr_3.6.0.sql +++ b/dev/initdata/mysqldump_dolibarr_3.6.0.sql @@ -4867,7 +4867,7 @@ CREATE TABLE `llx_opensurvey_sondage` ( `mailsonde` tinyint(4) NOT NULL DEFAULT '0', `survey_link_visible` int(11) DEFAULT '1', `origin` varchar(64) DEFAULT NULL, - `tms` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', + `tms` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id_sondage`), KEY `idx_id_sondage_admin` (`id_sondage_admin`), KEY `idx_date_fin` (`date_fin`) diff --git a/dev/optimize_images.sh b/dev/optimize_images.sh new file mode 100755 index 00000000000..0d532d054ad --- /dev/null +++ b/dev/optimize_images.sh @@ -0,0 +1,233 @@ +#!/bin/bash +# Borrowed from https://gist.github.com/lgiraudel/6065155 +# Inplace mode added by Raphaël Doursenaud + +PROGNAME=${0##*/} +INPUT='' +QUIET='0' +NOSTATS='0' +INPLACE='0' +max_input_size=0 +max_output_size=0 + + +usage() +{ + cat </dev/null + rm -fr $2.firstpass + fi + if [ "${1##*.}" = "jpg" -o "${1##*.}" = "jpeg" ]; then + jpegtran -copy none -progressive $1 > $2 + fi + + output_file_size=$(stat -c%s "$2") + max_output_size=$(expr $max_output_size + $output_file_size) +} + +get_max_file_length() +{ + local maxlength=0 + + IMAGES=$(find $INPUT -regextype posix-extended -regex '.*\.(jpg|jpeg|png)' | grep -v $OUTPUT) + + for CURRENT_IMAGE in $IMAGES; do + filename=$(basename "$CURRENT_IMAGE") + if [[ ${#filename} -gt $maxlength ]]; then + maxlength=${#filename} + fi + done + + echo "$maxlength" +} + +main() +{ + test=`type pngcrush >/dev/null 2>&1` + result=$? + if [ "x$result" == "x1" ]; then + echo "Tool pngcrush not found" && exit + fi + + test=`type optipng >/dev/null 2>&1` + result=$? + if [ "x$result" == "x1" ]; then + echo "Tool optipng not found" && exit + fi + + test=`type jpegtran >/dev/null 2>&1` + result=$? + if [ "x$result" == "x1" ]; then + echo "Tool jpegtran not found" && exit + fi + + + # If $INPUT is empty, then we use current directory + if [[ "$INPUT" == "" ]]; then + INPUT=$(pwd) + fi + + # If $OUTPUT is empty, then we use the directory "output" in the current directory + if [[ "$OUTPUT" == "" ]]; then + OUTPUT=$(pwd)/output + fi + # If inplace, we use /tmp for output + if [[ "$INPLACE" == "1" ]]; then + OUTPUT='/tmp/optimize' + fi + + echo "Mode is $INPLACE (1=Images are replaced, 0=New images are stored into $OUTPUT)" + + # We create the output directory + mkdir -p $OUTPUT + + # To avoid some troubles with filename with spaces, we store the current IFS (Internal File Separator)... + SAVEIFS=$IFS + # ...and we set a new one + IFS=$(echo -en "\n\b") + + max_filelength=`get_max_file_length` + pad=$(printf '%0.1s' "."{1..600}) + sDone=' [ DONE ]' + linelength=$(expr $max_filelength + ${#sDone} + 5) + + # Search of all jpg/jpeg/png in $INPUT + # We remove images from $OUTPUT if $OUTPUT is a subdirectory of $INPUT + echo "Scan $INPUT to find images" + IMAGES=$(find $INPUT -regextype posix-extended -regex '.*\.(jpg|jpeg|png)' | grep -v $OUTPUT) + + if [ "$QUIET" == "0" ]; then + echo --- Optimizing $INPUT --- + echo + fi + for CURRENT_IMAGE in $IMAGES; do + echo "Process $CURRENT_IMAGE" + filename=$(basename $CURRENT_IMAGE) + if [ "$QUIET" == "0" ]; then + printf '%s ' "$filename" + printf '%*.*s' 0 $((linelength - ${#filename} - ${#sDone} )) "$pad" + fi + + optimize_image $CURRENT_IMAGE $OUTPUT/$filename + + # Replace file + if [[ "$INPLACE" == "1" ]]; then + mv $OUTPUT/$filename $CURRENT_IMAGE + fi + + if [ "$QUIET" == "0" ]; then + printf '%s\n' "$sDone" + fi + done + + # Cleanup + if [[ "$INPLACE" == "1" ]]; then + rm -rf $OUTPUT + fi + + # we restore the saved IFS + IFS=$SAVEIFS + + if [ "$NOSTATS" == "0" -a "$QUIET" == "0" ]; then + echo + echo "Input: " $(human_readable_filesize $max_input_size) + echo "Output: " $(human_readable_filesize $max_output_size) + space_saved=$(expr $max_input_size - $max_output_size) + echo "Space save: " $(human_readable_filesize $space_saved) + fi +} + +human_readable_filesize() +{ +echo -n $1 | awk 'function human(x) { + s=" b Kb Mb Gb Tb" + while (x>=1024 && length(s)>1) + {x/=1024; s=substr(s,4)} + s=substr(s,1,4) + xf=(s==" b ")?"%5d ":"%.2f" + return sprintf( xf"%s", x, s) + } + {gsub(/^[0-9]+/, human($1)); print}' +} + +SHORTOPTS="h,i:,o:,q,s,p" +LONGOPTS="help,input:,output:,quiet,no-stats,inplace" +ARGS=$(getopt -s bash --options $SHORTOPTS --longoptions $LONGOPTS --name $PROGNAME -- "$@") + +# Syntax +if [ "x$1" != "xlist" -a "x$1" != "xfix" ] +then + echo "Usage: optimize_images.sh (list|fix) -i dirtoscan" + exit +fi + +eval set -- "$ARGS" +while true; do + case $1 in + -h|--help) + usage + exit 0 + ;; + -i|--input) + shift + INPUT=$1 + ;; + -o|--output) + shift + OUTPUT=$1 + ;; + -q|--quiet) + QUIET='1' + ;; + -s|--no-stats) + NOSTATS='1' + ;; + -p|--inplace) + INPLACE='1' + ;; + --) + shift + break + ;; + *) + shift + break + ;; + esac + shift +done + +# To convert +if [ "x$1" = "xlist" ] +then + INPLACE=0 +fi + +main + diff --git a/dev/skeletons/build_class_from_table.php b/dev/skeletons/build_class_from_table.php index 6acbc1feb35..0b2e96daaac 100755 --- a/dev/skeletons/build_class_from_table.php +++ b/dev/skeletons/build_class_from_table.php @@ -254,11 +254,11 @@ foreach($property as $key => $prop) $varprop.="\t\t\$sql.= \" "; if ($prop['istime']) { - $varprop.='".(! isset($this->'.$prop['field'].') || dol_strlen($this->'.$prop['field'].')==0?\'NULL\':$this->db->idate('; + $varprop.='".(! isset($this->'.$prop['field'].') || dol_strlen($this->'.$prop['field'].')==0?\'NULL\':"\'".$this->db->idate('; $varprop.="\$this->".$prop['field'].""; - $varprop.='))."'; + $varprop.=')."\'")."'; if ($i < count($property)) $varprop.=","; - $varprop.="\";"; + $varprop.='";'; } elseif ($prop['ischar']) { diff --git a/dev/skeletons/modMyModule.class.php b/dev/skeletons/modMyModule.class.php index bdeb61a7821..4c09e379d9b 100644 --- a/dev/skeletons/modMyModule.class.php +++ b/dev/skeletons/modMyModule.class.php @@ -173,7 +173,7 @@ class modMyModule extends DolibarrModules // Add here list of permission defined by an id, a label, a boolean and two constant strings. // Example: - // $this->rights[$r][0] = 2000; // Permission id (must not be already used) + // $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) // $this->rights[$r][1] = 'Permision label'; // Permission label // $this->rights[$r][3] = 1; // Permission by default for new user (0/1) // $this->rights[$r][4] = 'level1'; // In php code, permission will be checked by test if ($user->rights->permkey->level1->level2) diff --git a/dev/skeletons/skeleton_class.class.php b/dev/skeletons/skeleton_class.class.php index c36dad4b4b5..4dddc5a8c80 100644 --- a/dev/skeletons/skeleton_class.class.php +++ b/dev/skeletons/skeleton_class.class.php @@ -1,5 +1,6 @@ + * Copyright (C) 2014 Juanjo Menent * Copyright (C) ---Put here your own copyright and developer email--- * * This program is free software; you can redistribute it and/or modify @@ -79,7 +80,7 @@ class Skeleton_Class extends CommonObject // Put here code to add control on parameters values // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."mytable("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."("; $sql.= " field1,"; $sql.= " field2"; //... @@ -91,13 +92,13 @@ class Skeleton_Class extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } if (! $error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."mytable"); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); if (! $notrigger) { @@ -105,10 +106,8 @@ class Skeleton_Class extends CommonObject // want this action calls a trigger. //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //$result=$this->call_trigger('MYOBJECT_CREATE',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} //// End call triggers } } @@ -118,7 +117,7 @@ class Skeleton_Class extends CommonObject { foreach($this->errors as $errmsg) { - dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); @@ -135,10 +134,11 @@ class Skeleton_Class extends CommonObject /** * Load object in memory from the database * - * @param int $id Id object + * @param int $id Id object + * @param string $ref Ref * @return int <0 if KO, >0 if OK */ - function fetch($id) + function fetch($id,$ref='') { global $langs; $sql = "SELECT"; @@ -146,10 +146,11 @@ class Skeleton_Class extends CommonObject $sql.= " t.field1,"; $sql.= " t.field2"; //... - $sql.= " FROM ".MAIN_DB_PREFIX."mytable as t"; - $sql.= " WHERE t.rowid = ".$id; + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + if ($ref) $sql.= " WHERE t.ref = '".$ref."'"; + else $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch"); $resql=$this->db->query($sql); if ($resql) { @@ -169,7 +170,6 @@ class Skeleton_Class extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -182,7 +182,7 @@ class Skeleton_Class extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user, $notrigger=0) { global $conf, $langs; $error=0; @@ -196,7 +196,7 @@ class Skeleton_Class extends CommonObject // Put here code to add a control on parameters values // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."mytable SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET"; $sql.= " field1=".(isset($this->field1)?"'".$this->db->escape($this->field1)."'":"null").","; $sql.= " field2=".(isset($this->field2)?"'".$this->db->escape($this->field2)."'":"null").""; //... @@ -204,7 +204,7 @@ class Skeleton_Class extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(__METHOD__); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -216,12 +216,10 @@ class Skeleton_Class extends CommonObject // want this action calls a trigger. //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } + //$result=$this->call_trigger('MYOBJECT_MODIFY',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} //// End call triggers - } + } } // Commit or rollback @@ -229,7 +227,7 @@ class Skeleton_Class extends CommonObject { foreach($this->errors as $errmsg) { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); @@ -264,21 +262,19 @@ class Skeleton_Class extends CommonObject // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. - //// Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } - //// End call triggers + //// Call triggers + //$result=$this->call_trigger('MYOBJECT_DELETE',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} + //// End call triggers } } if (! $error) { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."mytable"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(__METHOD__); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } @@ -288,7 +284,7 @@ class Skeleton_Class extends CommonObject { foreach($this->errors as $errmsg) { - dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); + dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error.=($this->error?', '.$errmsg:$errmsg); } $this->db->rollback(); diff --git a/dev/skeletons/skeleton_page.php b/dev/skeletons/skeleton_page.php index bf63a769af7..deaecd95526 100644 --- a/dev/skeletons/skeleton_page.php +++ b/dev/skeletons/skeleton_page.php @@ -43,6 +43,7 @@ if (! $res && file_exists("../../../dolibarr/htdocs/main.inc.php")) $res=@includ if (! $res && file_exists("../../../../dolibarr/htdocs/main.inc.php")) $res=@include '../../../../dolibarr/htdocs/main.inc.php'; // Used on dev env only if (! $res) die("Include of main fails"); // Change this following line to use the correct relative path from htdocs +include_once(DOL_DOCUMENT_ROOT.'/core/class/formcompany.class.php'); dol_include_once('/module/class/skeleton_class.class.php'); // Load traductions files requiredby by page @@ -52,6 +53,7 @@ $langs->load("other"); // Get parameters $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); +$backtopage = GETPOST('backtopage'); $myparam = GETPOST('myparam','alpha'); // Protection if external user @@ -60,6 +62,16 @@ if ($user->societe_id > 0) //accessforbidden(); } +if (empty($action) && empty($id) && empty($ref)) $action='create'; + +// Load object if id or ref is provided as parameter +$object=new Skeleton_Class($db); +if (($id > 0 || ! empty($ref)) && $action != 'add') +{ + $result=$object->fetch($id,$ref); + if ($result < 0) dol_print_error($db); +} + /******************************************************************* @@ -68,19 +80,104 @@ if ($user->societe_id > 0) * Put here all code to do according to value of "action" parameter ********************************************************************/ +// Action to add record if ($action == 'add') { - $object=new Skeleton_Class($db); - $object->prop1=$_POST["field1"]; - $object->prop2=$_POST["field2"]; - $result=$object->create($user); + if (GETPOST('cancel')) + { + $urltogo=$backtopage?$backtopage:dol_buildpath('/buildingmanagement/list.php',1); + header("Location: ".$urltogo); + exit; + } + + $error=0; + + /* object_prop_getpost_prop */ + $object->prop1=GETPOST("field1"); + $object->prop2=GETPOST("field2"); + + if (empty($object->ref)) + { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")),'errors'); + } + + if (! $error) + { + $result=$object->create($user); + if ($result > 0) + { + // Creation OK + $urltogo=$backtopage?$backtopage:dol_buildpath('/mymodule/list.php',1); + header("Location: ".$urltogo); + exit; + } + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='create'; + } + } + else + { + $action='create'; + } +} + +// Cancel +if ($action == 'update' && GETPOST('cancel')) $action='view'; + +// Action to update record +if ($action == 'update' && ! GETPOST('cancel')) +{ + $error=0; + + $object->prop1=GETPOST("field1"); + $object->prop2=GETPOST("field2"); + + if (empty($object->ref)) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref")),null,'errors'); + } + + if (! $error) + { + $result=$object->update($user); + if ($result > 0) + { + $action='view'; + } + else + { + // Creation KO + if (! empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); + else setEventMessages($object->error, null, 'errors'); + $action='edit'; + } + } + else + { + $action='edit'; + } +} + +// Action to delete +if ($action == 'confirm_delete') +{ + $result=$object->delete($user); if ($result > 0) { - // Creation OK + // Delete OK + setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); + header("Location: ".dol_buildpath('/buildingmanagement/list.php',1)); + exit; } + else { - // Creation KO - $mesg=$object->error; + if (! empty($object->errors)) setEventMessages(null,$object->errors,'errors'); + else setEventMessages($object->error,null,'errors'); } } @@ -101,7 +198,7 @@ $form=new Form($db); // Put here content of your page -// Example 1 : Adding jquery code +// Example : Adding jquery code print ''; -// Example 2 : Adding links to objects -// The class must extends CommonObject class to have this method available -//$somethingshown=$object->showLinkedObjectBlock(); - - -// Example 3 : List of data -if ($action == 'list') +// Part to show a list +if ($action == 'list' || empty($id)) { $sql = "SELECT"; $sql.= " t.rowid,"; @@ -139,27 +231,24 @@ if ($action == 'list') print_liste_field_titre($langs->trans('field2'),$_SERVER['PHP_SELF'],'t.field2','',$param,'',$sortfield,$sortorder); print ''; - dol_syslog($script_file." sql=".$sql, LOG_DEBUG); + dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) + while ($i < $num) { - while ($i < $num) + $obj = $db->fetch_object($resql); + if ($obj) { - $obj = $db->fetch_object($resql); - if ($obj) - { - // You can use here results - print ''; - print $obj->field1; - print $obj->field2; - print ''; - } - $i++; + // You can use here results + print ''; + print $obj->field1; + print $obj->field2; + print ''; } + $i++; } } else @@ -173,6 +262,102 @@ if ($action == 'list') +// Part to create +if ($action == 'create') +{ + print_fiche_titre($langs->trans("NewResidence")); + + dol_fiche_head(); + + print '
'; + print ''; + print ''; + + print ''."\n"; + print ''; + + print '
'.$langs->trans("Label").''; + print ''; + print '
'."\n"; + + print '
'; + + print '
 
'; + + print '
'; + + dol_fiche_end(); +} + + + +// Part to edit record +if (($id || $ref) && $action == 'edit') +{ + dol_fiche_head(); + + print '
'; + print ''; + print ''; + print ''; + + + print '
'; + + print '
'; + + print '
'; + + dol_fiche_end(); +} + + + +// Part to show record +if ($id && (empty($action) || $action == 'view')) +{ + dol_fiche_head(); + + + + dol_fiche_end(); + + + // Buttons + print '
'."\n"; + $parameters=array(); + $reshook=$hookmanager->executeHooks('addMoreActionsButtons',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + if (empty($reshook)) + { + if ($user->rights->mymodule->write) + { + print ''."\n"; + } + + if ($user->rights->mymodule->delete) + { + if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile)) // We can't use preloaded confirm form with jmobile + { + print '
'.$langs->trans('Delete').'
'."\n"; + } + else + { + print ''."\n"; + } + } + } + print '
'."\n"; + + + // Example 2 : Adding links to objects + // The class must extends CommonObject class to have this method available + //$somethingshown=$object->showLinkedObjectBlock(); + +} + + // End of page llxFooter(); $db->close(); diff --git a/dev/skeletons/skeleton_script.php b/dev/skeletons/skeleton_script.php index b10b57a730a..35904c9bfd3 100644 --- a/dev/skeletons/skeleton_script.php +++ b/dev/skeletons/skeleton_script.php @@ -57,7 +57,7 @@ if (! $result > 0) { dol_print_error('',$user->error); exit; } $user->getrights(); -print "***** ".$script_file." (".$version.") pid=".getmypid()." *****\n"; +print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; if (! isset($argv[1])) { // Check parameters print "Usage: ".$script_file." param1 param2 ...\n"; exit(-1); @@ -119,7 +119,7 @@ $sql.= " FROM ".MAIN_DB_PREFIX."skeleton"; $sql.= " WHERE field3 = 'xxx'"; $sql.= " ORDER BY field1 ASC"; -dol_syslog($script_file." sql=".$sql, LOG_DEBUG); +dol_syslog($script_file, LOG_DEBUG); $resql=$db->query($sql); if ($resql) { diff --git a/dev/skeletons/skeleton_webservice_server.php b/dev/skeletons/skeleton_webservice_server.php index 278057fd4f6..52bb46455cb 100644 --- a/dev/skeletons/skeleton_webservice_server.php +++ b/dev/skeletons/skeleton_webservice_server.php @@ -269,5 +269,4 @@ function createSkeleton($authentication,$skeleton) } // Return the results. -$server->service($HTTP_RAW_POST_DATA); - +$server->service(file_get_contents("php://input")); diff --git a/dev/translation/strip_language_file.php b/dev/translation/strip_language_file.php index fc778770bb9..42a70c8c1a6 100755 --- a/dev/translation/strip_language_file.php +++ b/dev/translation/strip_language_file.php @@ -1,9 +1,22 @@ #!/usr/bin/php * - * (c) 2014 by FromDual GmbH, licensed under GPL v2 + * 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 2 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 . + * + * ----- * * Compares a secondary language translation file with its primary * language file and strips redundant translations. @@ -12,11 +25,10 @@ * * Usage: * cd htdocs/langs - * ../../dev/translation/strip_language_file.php + * ../../dev/translation/strip_language_file.php [file.lang|all] * - * Parameters: - * 1 - Primary Language - * 2 - Secondary Language + * To rename all .delta files, you can do + * for fic in `ls *.delta`; do f=`echo $fic | sed -e 's/\.delta//'`; echo $f; mv $f.delta $f; done * * Rules: * secondary string == primary string -> strip @@ -24,9 +36,6 @@ * secondary string not in primary -> strip and warning * secondary string has no value -> strip and warning * secondary string != primary string -> secondary.lang.delta - * - * To rename all .delta fils, you can do - * for fic in `ls *.delta`; do f=`echo $fic | sed -e 's/\.delta//'`; echo $f; mv $f.delta $f; done */ /** @@ -260,6 +269,9 @@ foreach($filesToProcess as $fileToProcess) } print "Output can be found at $output.\n"; + + print "To rename all .delta files, you can do\n"; + print 'for fic in `ls *.delta`; do f=`echo $fic | sed -e \'s/\.delta//\'`; echo $f; mv $f.delta $f; done'."\n"; } diff --git a/dev/vagrant/README.md b/dev/vagrant/README.md index 8056643520e..dc0bc4234e2 100644 --- a/dev/vagrant/README.md +++ b/dev/vagrant/README.md @@ -23,7 +23,7 @@ Usage `cd` into the vagrant box directory and simply type `vagrant up`. -That's all you need to do. It will build a brand new VirtalBox machine for you with everything you need to develop on Dolibarr. +That's all you need to do. It will build a brand new VirtualBox machine for you with everything you need to develop on Dolibarr. ### Name resolution For easy access to the VM you need to setup name resolution to the machines IP. @@ -45,9 +45,16 @@ Somewhat bleeding edge vagrant box for develop branch related work. - IP: 192.168.42.101 - Vhost: dev.dolibarr.org -- OS: Debian Wheezy 7.5 +- OS: Debian Wheezy 7.5 x64 - Webserver: Apache 2.2.22 -- PHP: mod_php 5.5.13-1~dotdeb.1 +- PHP: mod_php 5.5.14-1~dotdeb.1 + Installed modules: + - cli + - curl + - gd + - imagick + - intl + - mcrypt - Database: MySQL 5.5 - Root user: root - Root password: root @@ -55,7 +62,13 @@ Somewhat bleeding edge vagrant box for develop branch related work. - Database user: user - Database password: user - Initial data: dev/initdata/mysqldump_dolibarr-3.5.0.sql +- Database: PostgreSQL 9.3 +- Adminer: lightweight database management. Access through http://192.168.42.101/adminer - Debugger: XDebug -- Profiler: Xhprof +- Profiler: Xhprof. Access through http://192.168.42.101/xhprof/xhprof_html You can access MailCatcher to read all outgoing emails at http://192.168.42.101:1080 + +To access the machine you must use the following private keys: +- User root: located at puphpet/files/dot/ssh/root_rsa +- User vagrant: located at puphpet/files/dot/ssh/id_rsa diff --git a/dev/vagrant/dolibarrdev/Vagrantfile b/dev/vagrant/dolibarrdev/Vagrantfile index f73476207d0..a0bcc88ced6 100644 --- a/dev/vagrant/dolibarrdev/Vagrantfile +++ b/dev/vagrant/dolibarrdev/Vagrantfile @@ -23,13 +23,62 @@ Vagrant.configure("2") do |config| end end + if Vagrant.has_plugin?('vagrant-hostsupdater') + hosts = Array.new() + + if !configValues['apache']['install'].nil? && + configValues['apache']['install'].to_i == 1 && + configValues['apache']['vhosts'].is_a?(Hash) + configValues['apache']['vhosts'].each do |i, vhost| + hosts.push(vhost['servername']) + + if vhost['serveraliases'].is_a?(Array) + vhost['serveraliases'].each do |vhost_alias| + hosts.push(vhost_alias) + end + end + end + elsif !configValues['nginx']['install'].nil? && + configValues['nginx']['install'].to_i == 1 && + configValues['nginx']['vhosts'].is_a?(Hash) + configValues['nginx']['vhosts'].each do |i, vhost| + hosts.push(vhost['server_name']) + + if vhost['server_aliases'].is_a?(Array) + vhost['server_aliases'].each do |x, vhost_alias| + hosts.push(vhost_alias) + end + end + end + end + + if hosts.any? + contents = File.open("#{dir}/puphpet/shell/hostsupdater-notice.txt", 'r'){ |file| file.read } + puts "\n\033[34m#{contents}\033[0m\n" + + if config.vm.hostname.to_s.strip.length == 0 + config.vm.hostname = 'puphpet-dev-machine' + end + + config.hostsupdater.aliases = hosts + end + end + data['vm']['synced_folder'].each do |i, folder| if folder['source'] != '' && folder['target'] != '' - nfs = (folder['nfs'] == "true") ? "nfs" : nil - if nfs == "nfs" - config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: nfs + if folder['sync_type'] == 'nfs' + config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: "nfs" + elsif folder['sync_type'] == 'smb' + config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: "smb" + elsif folder['sync_type'] == 'rsync' + rsync_args = !folder['rsync']['args'].nil? ? folder['rsync']['args'] : ["--verbose", "--archive", "--delete", "-z"] + rsync_auto = !folder['rsync']['auto'].nil? ? folder['rsync']['auto'] : true + rsync_exclude = !folder['rsync']['exclude'].nil? ? folder['rsync']['exclude'] : [".vagrant/"] + + config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", + rsync__args: rsync_args, rsync__exclude: rsync_exclude, rsync__auto: rsync_auto, type: "rsync" else - config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", type: nfs, + config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", id: "#{i}", group: 'www-data', owner: 'www-data', mount_options: ["dmode=775", "fmode=764"] end end @@ -45,6 +94,9 @@ Vagrant.configure("2") do |config| if key == "memory" next end + if key == "cpus" + next + end if key == "natdnshostresolver1" value = value ? "on" : "off" @@ -54,6 +106,7 @@ Vagrant.configure("2") do |config| end virtualbox.customize ["modifyvm", :id, "--memory", "#{data['vm']['memory']}"] + virtualbox.customize ["modifyvm", :id, "--cpus", "#{data['vm']['cpus']}"] if data['vm']['hostname'].to_s.strip.length != 0 virtualbox.customize ["modifyvm", :id, "--name", config.vm.hostname] @@ -69,11 +122,15 @@ Vagrant.configure("2") do |config| if key == "memsize" next end + if key == "cpus" + next + end v.vmx["#{key}"] = "#{value}" end v.vmx["memsize"] = "#{data['vm']['memory']}" + v.vmx["numvcpus"] = "#{data['vm']['cpus']}" if data['vm']['hostname'].to_s.strip.length != 0 v.vmx["displayName"] = config.vm.hostname @@ -89,11 +146,15 @@ Vagrant.configure("2") do |config| if key == "memsize" next end + if key == "cpus" + next + end v.customize ["set", :id, "--#{key}", "#{value}"] end v.memory = "#{data['vm']['memory']}" + v.cpus = "#{data['vm']['cpus']}" if data['vm']['hostname'].to_s.strip.length != 0 v.name = config.vm.hostname @@ -111,7 +172,8 @@ Vagrant.configure("2") do |config| kg.path = "puphpet/shell/ssh-keygen.sh" kg.args = "#{ssh_username}" end - config.vm.provision :shell, :path => "puphpet/shell/update-puppet.sh" + config.vm.provision :shell, :path => "puphpet/shell/install-ruby.sh" + config.vm.provision :shell, :path => "puphpet/shell/install-puppet.sh" config.vm.provision :puppet do |puppet| puppet.facter = { @@ -128,7 +190,14 @@ Vagrant.configure("2") do |config| end end - config.vm.provision :shell, :path => "puphpet/shell/execute-files.sh" + config.vm.provision :shell do |s| + s.path = "puphpet/shell/execute-files.sh" + s.args = ["exec-once", "exec-always"] + end + config.vm.provision :shell, run: "always" do |s| + s.path = "puphpet/shell/execute-files.sh" + s.args = ["startup-once", "startup-always"] + end config.vm.provision :shell, :path => "puphpet/shell/important-notices.sh" if File.file?("#{dir}/puphpet/files/dot/ssh/id_rsa") @@ -168,3 +237,4 @@ Vagrant.configure("2") do |config| end + diff --git a/dev/vagrant/dolibarrdev/puphpet/.gitattributes b/dev/vagrant/dolibarrdev/puphpet/.gitattributes index 93f9975f88e..5bb817f8e45 100644 --- a/dev/vagrant/dolibarrdev/puphpet/.gitattributes +++ b/dev/vagrant/dolibarrdev/puphpet/.gitattributes @@ -2,9 +2,4 @@ * text=auto # Force the following filetypes to have unix eols, so Windows does not break them -*.pp text eol=lf -*.sh text eol=lf -*.yaml text eol=lf -Puppetfile text eol=lf -.bash_aliases text eol=lf -.vimrc text eol=lf +*.* text eol=lf diff --git a/dev/vagrant/dolibarrdev/puphpet/config.yaml b/dev/vagrant/dolibarrdev/puphpet/config.yaml index 5cfb2601f21..e88a3e13003 100644 --- a/dev/vagrant/dolibarrdev/puphpet/config.yaml +++ b/dev/vagrant/dolibarrdev/puphpet/config.yaml @@ -5,6 +5,7 @@ vagrantfile-local: box_url: puphpet/debian75-x64 hostname: null memory: '512' + cpus: '1' chosen_provider: virtualbox network: private_network: 192.168.42.101 @@ -29,10 +30,12 @@ vagrantfile-local: - '--hiera_config /vagrant/puphpet/puppet/hiera.yaml' - '--parser future' synced_folder: - PL1BkioqqvGY: + w6GqzzS2a7lu: source: ../../../ - target: /var/www - nfs: 'false' + target: /var/www/dolibarr + sync_type: default + rsync: + auto: 'false' usable_port_range: 2200..2250 ssh: host: null @@ -61,8 +64,7 @@ mailcatcher: smtp_port: 1025 http_ip: 0.0.0.0 http_port: '1080' - mailcatcher_path: /usr/local/bin - log_path: /var/log/mailcatcher/mailcatcher.log + mailcatcher_path: /usr/local/rvm/wrappers/default firewall: install: '1' rules: null @@ -71,7 +73,7 @@ apache: settings: user: www-data group: www-data - default_vhost: false + default_vhost: true manage_user: false manage_group: false sendfile: 0 @@ -79,9 +81,9 @@ apache: - php - rewrite vhosts: - CGyWQB0fx4x0: + syTi8VestVdG: servername: dev.dolibarr.org - docroot: /var/www/htdocs + docroot: /var/www/dolibarr/htdocs port: '80' setenv: - 'APP_ENV dev' @@ -96,8 +98,12 @@ apache: mod_spdy: 0 nginx: install: 0 + settings: + default_vhost: 1 + proxy_buffer_size: 128k + proxy_buffers: '4 256k' vhosts: - jeF1sybIJ3V2: + kZiLLcLAIVAF: server_name: awesome.dev server_aliases: - www.awesome.dev @@ -152,7 +158,7 @@ mysql: root_password: root adminer: 0 databases: - 2OfuuapoIqsl: + HHTBm64g1siG: grant: - ALTER - CREATE @@ -166,16 +172,16 @@ mysql: host: localhost user: user password: user - sql_file: /var/www/dev/initdata/mysqldump_dolibarr_3.5.0.sql + sql_file: /var/www/dolibarr/dev/initdata/mysqldump_dolibarr_3.5.0.sql postgresql: - install: 0 + install: '1' settings: - root_password: '123' + root_password: root user_group: postgres encoding: UTF8 version: '9.3' databases: { } - adminer: 0 + adminer: '1' mariadb: install: 0 root_password: '123' diff --git a/dev/vagrant/dolibarrdev/puphpet/files/dot/.gitignore b/dev/vagrant/dolibarrdev/puphpet/files/dot/.gitignore index dcf60545594..e9b023ea6a6 100644 --- a/dev/vagrant/dolibarrdev/puphpet/files/dot/.gitignore +++ b/dev/vagrant/dolibarrdev/puphpet/files/dot/.gitignore @@ -1,4 +1 @@ -ssh/id_rsa -ssh/id_rsa.pub -ssh/insecure_private_key -ssh/id_rsa.ppk \ No newline at end of file +ssh/* \ No newline at end of file diff --git a/htdocs/includes/phpexcel/PHPExcel/Shared/PDF/fonts/.noencode b/dev/vagrant/dolibarrdev/puphpet/files/startup-always/empty similarity index 100% rename from htdocs/includes/phpexcel/PHPExcel/Shared/PDF/fonts/.noencode rename to dev/vagrant/dolibarrdev/puphpet/files/startup-always/empty diff --git a/dev/vagrant/dolibarrdev/puphpet/files/startup-once/empty b/dev/vagrant/dolibarrdev/puphpet/files/startup-once/empty new file mode 100644 index 00000000000..e69de29bb2d diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/manifest.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/manifest.pp index 57f759e5531..ea27564f8c9 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/manifest.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/manifest.pp @@ -197,8 +197,8 @@ if is_array($server_values['packages']) and count($server_values['packages']) > } define add_dotdeb ($release){ - apt::source { $name: - location => 'http://packages.dotdeb.org', + apt::source { "${name}-repo.puphpet": + location => 'http://repo.puphpet.com/dotdeb/', release => $release, repos => 'all', required_packages => 'debian-keyring debian-archive-keyring', @@ -270,7 +270,7 @@ if hash_key_equals($mailcatcher_values, 'install', 1) { create_resources('class', { 'mailcatcher' => $mailcatcher_values['settings'] }) - if ! defined(Firewall["100 tcp/${mailcatcher_values['settings']['smtp_port']},${mailcatcher_values['settings']['http_port']}"]) { + if ! defined(Firewall["100 tcp/${mailcatcher_values['settings']['smtp_port']}, ${mailcatcher_values['settings']['http_port']}"]) { firewall { "100 tcp/${mailcatcher_values['settings']['smtp_port']}, ${mailcatcher_values['settings']['http_port']}": port => [$mailcatcher_values['settings']['smtp_port'], $mailcatcher_values['settings']['http_port']], proto => tcp, @@ -279,30 +279,39 @@ if hash_key_equals($mailcatcher_values, 'install', 1) { } if ! defined(Class['supervisord']) { + class{ 'puphpet::python::pip': } + class { 'supervisord': - install_pip => true, + install_pip => false, + require => [ + Class['my_fw::post'], + Class['Puphpet::Python::Pip'], + ], } } - $supervisord_mailcatcher_options = sort(join_keys_to_values({ + $mailcatcher_path = $mailcatcher_values['settings']['mailcatcher_path'] + + $mailcatcher_options = sort(join_keys_to_values({ ' --smtp-ip' => $mailcatcher_values['settings']['smtp_ip'], ' --smtp-port' => $mailcatcher_values['settings']['smtp_port'], ' --http-ip' => $mailcatcher_values['settings']['http_ip'], ' --http-port' => $mailcatcher_values['settings']['http_port'] }, ' ')) - $supervisord_mailcatcher_cmd = "mailcatcher ${supervisord_mailcatcher_options} -f >> ${mailcatcher_values['settings']['log']}" - supervisord::program { 'mailcatcher': - command => $supervisord_mailcatcher_cmd, + command => "${mailcatcher_path}/mailcatcher ${mailcatcher_options} -f", priority => '100', user => 'mailcatcher', autostart => true, autorestart => 'true', environment => { - 'PATH' => "/bin:/sbin:/usr/bin:/usr/sbin:${mailcatcher_values['settings']['path']}" + 'PATH' => "/bin:/sbin:/usr/bin:/usr/sbin:${mailcatcher_path}" }, - require => Package['mailcatcher'] + require => [ + Class['mailcatcher::config'], + File['/var/log/mailcatcher'] + ], } } @@ -312,10 +321,6 @@ if $firewall_values == undef { $firewall_values = hiera('firewall', false) } -resources { 'firewall': - purge => true -} - Firewall { before => Class['my_fw::post'], require => Class['my_fw::pre'], @@ -383,16 +388,15 @@ if hash_key_equals($apache_values, 'install', 1) { include puphpet::params include apache::params - $webroot_location = $puphpet::params::apache_webroot_location + $webroot_location = $puphpet::params::apache_webroot_location + $apache_provider_types = ['virtualbox', 'vmware_fusion', 'vmware_desktop', 'parallels'] exec { "exec mkdir -p ${webroot_location}": command => "mkdir -p ${webroot_location}", creates => $webroot_location, } - if (downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) - and ! defined(File[$webroot_location]) - { + if (downcase($::provisioner_type) in $apache_provider_types) and ! defined(File[$webroot_location]) { file { $webroot_location: ensure => directory, mode => 0775, @@ -401,11 +405,7 @@ if hash_key_equals($apache_values, 'install', 1) { Group['www-data'] ] } - } - - if !(downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) - and ! defined(File[$webroot_location]) - { + } elsif ! (downcase($::provisioner_type) in $apache_provider_types) and ! defined(File[$webroot_location]) { file { $webroot_location: ensure => directory, group => 'www-data', @@ -435,8 +435,8 @@ if hash_key_equals($apache_values, 'install', 1) { } if $::operatingsystem == 'ubuntu' - and hash_key_equals($php_values, 'install', 1) - and hash_key_equals($php_values, 'version', 55) + and hash_key_equals($php_values, 'install', 1) + and hash_key_equals($php_values, 'version', 55) { $apache_version = '2.4' } else { @@ -467,15 +467,16 @@ if hash_key_equals($apache_values, 'install', 1) { $apache_vhosts = merge($apache_values['vhosts'], { 'default_vhost_80' => { 'servername' => 'default', - 'serveraliases' => ['*'], 'docroot' => '/var/www/default', 'port' => 80, + 'default_vhost' => true, }, 'default_vhost_443' => { 'servername' => 'default', - 'serveraliases' => ['*'], 'docroot' => '/var/www/default', 'port' => 443, + 'default_vhost' => true, + 'ssl' => 1, }, }) } else { @@ -489,7 +490,7 @@ if hash_key_equals($apache_values, 'install', 1) { creates => $vhost['docroot'], } - if (downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) + if (downcase($::provisioner_type) in $apache_provider_types) and ! defined(File[$vhost['docroot']]) { file { $vhost['docroot']: @@ -497,9 +498,7 @@ if hash_key_equals($apache_values, 'install', 1) { mode => 0765, require => Exec["exec mkdir -p ${vhost['docroot']} @ key ${key}"] } - } - - if !(downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) + } elsif !(downcase($::provisioner_type) in $apache_provider_types) and ! defined(File[$vhost['docroot']]) { file { $vhost['docroot']: @@ -515,11 +514,11 @@ if hash_key_equals($apache_values, 'install', 1) { create_resources(apache::vhost, { "${key}" => merge($vhost, { 'custom_fragment' => template('puphpet/apache/custom_fragment.erb'), - 'ssl' => 'ssl' in $vhost and str2bool($vhost['ssl']) ? { true => true, default => false }, - 'ssl_cert' => 'ssl_cert' in $vhost and $vhost['ssl_cert'] ? { undef => undef, '' => undef, default => $vhost['ssl_cert'] }, - 'ssl_key' => 'ssl_key' in $vhost and $vhost['ssl_key'] ? { undef => undef, '' => undef, default => $vhost['ssl_key'] }, - 'ssl_chain' => 'ssl_chain' in $vhost and $vhost['ssl_chain'] ? { undef => undef, '' => undef, default => $vhost['ssl_chain'] }, - 'ssl_certs_dir' => 'ssl_certs_dir' in $vhost and $vhost['ssl_certs_dir'] ? { undef => undef, '' => undef, default => $vhost['ssl_certs_dir'] } + 'ssl' => 'ssl' in $vhost and str2bool($vhost['ssl']) ? { true => true, default => false }, + 'ssl_cert' => hash_key_true($vhost, 'ssl_cert') ? { true => $vhost['ssl_cert'], default => undef }, + 'ssl_key' => hash_key_true($vhost, 'ssl_key') ? { true => $vhost['ssl_key'], default => undef }, + 'ssl_chain' => hash_key_true($vhost, 'ssl_chain') ? { true => $vhost['ssl_chain'], default => undef }, + 'ssl_certs_dir' => hash_key_true($vhost, 'ssl_certs_dir') ? { true => $vhost['ssl_certs_dir'], default => undef } }) }) @@ -578,33 +577,25 @@ if hash_key_equals($nginx_values, 'install', 1) { } } - $webroot_location = $puphpet::params::nginx_webroot_location + $webroot_location = $puphpet::params::nginx_webroot_location + $nginx_provider_types = ['virtualbox', 'vmware_fusion', 'vmware_desktop', 'parallels'] exec { "exec mkdir -p ${webroot_location}": command => "mkdir -p ${webroot_location}", creates => $webroot_location, } - if (downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) - and ! defined(File[$webroot_location]) - { + if (downcase($::provisioner_type) in $nginx_provider_types) and ! defined(File[$webroot_location]) { file { $webroot_location: ensure => directory, mode => 0775, - require => [ - Exec["exec mkdir -p ${webroot_location}"], - Group['www-data'] - ] + require => Exec["exec mkdir -p ${webroot_location}"], } - } - - if !(downcase($::provisioner_type) in ['virtualbox', 'vmware_fusion']) - and ! defined(File[$webroot_location]) - { + } elsif ! (downcase($::provisioner_type) in $nginx_provider_types) and ! defined(File[$webroot_location]) { file { $webroot_location: ensure => directory, - group => 'www-data', mode => 0775, + group => 'www-data', require => [ Exec["exec mkdir -p ${webroot_location}"], Group['www-data'] @@ -626,12 +617,10 @@ if hash_key_equals($nginx_values, 'install', 1) { if hash_key_equals($php_values, 'install', 1) { $php5_fpm_sock = '/var/run/php5-fpm.sock' - if $php_values['version'] == undef { - $fastcgi_pass = null - } elsif $php_values['version'] == '53' { - $fastcgi_pass = '127.0.0.1:9000' - } else { - $fastcgi_pass = "unix:${php5_fpm_sock}" + $fastcgi_pass = $php_values['version'] ? { + '53' => '127.0.0.1:9000', + undef => null, + default => "unix:${php5_fpm_sock}" } if $::osfamily == 'redhat' and $fastcgi_pass == "unix:${php5_fpm_sock}" { @@ -641,7 +630,7 @@ if hash_key_equals($nginx_values, 'install', 1) { require => Package['nginx'], } - exec { "listen = 127.0.0.1:9000 => listen = ${php5_fpm_sock}": + exec { "'listen = 127.0.0.1:9000' => 'listen = ${php5_fpm_sock}'": command => "perl -p -i -e 's#listen = 127.0.0.1:9000#listen = ${php5_fpm_sock}#gi' /etc/php-fpm.d/www.conf", unless => "grep -c 'listen = 127.0.0.1:9000' '${php5_fpm_sock}'", notify => [ @@ -651,29 +640,51 @@ if hash_key_equals($nginx_values, 'install', 1) { require => Exec["create ${php5_fpm_sock} file"] } - set_php5_fpm_sock_group_and_user { 'php_rhel': + set_nginx_php5_fpm_sock_group_and_user { 'php_rhel': require => Exec["create ${php5_fpm_sock} file"], } } else { - set_php5_fpm_sock_group_and_user { 'php': + set_nginx_php5_fpm_sock_group_and_user { 'php': require => Package['nginx'], subscribe => Service['php5-fpm'], } } } elsif hash_key_equals($hhvm_values, 'install', 1) { - $fastcgi_pass = '127.0.0.1:9000' - - set_php5_fpm_sock_group_and_user { 'hhvm': - require => Package['nginx'], - } + $fastcgi_pass = '127.0.0.1:9000' } else { - $fastcgi_pass = '' + $fastcgi_pass = null } class { 'nginx': } - if count($nginx_values['vhosts']) > 0 { - each( $nginx_values['vhosts'] ) |$key, $vhost| { + if hash_key_equals($nginx_values['settings'], 'default_vhost', 1) { + $nginx_vhosts = merge($nginx_values['vhosts'], { + 'default' => { + 'server_name' => '_', + 'server_aliases' => [], + 'www_root' => '/var/www/html', + 'listen_port' => 80, + 'index_files' => ['index', 'index.html', 'index.htm', 'index.php'], + 'envvars' => [], + 'ssl' => '0', + 'ssl_cert' => '', + 'ssl_key' => '', + }, + }) + + if ! defined(File[$puphpet::params::nginx_default_conf_location]) { + file { $puphpet::params::nginx_default_conf_location: + ensure => absent, + require => Package['nginx'], + notify => Class['nginx::service'], + } + } + } else { + $nginx_vhosts = $nginx_values['vhosts'] + } + + if count($nginx_vhosts) > 0 { + each( $nginx_vhosts ) |$key, $vhost| { exec { "exec mkdir -p ${vhost['www_root']} @ key ${key}": command => "mkdir -p ${vhost['www_root']}", creates => $vhost['www_root'], @@ -695,7 +706,7 @@ if hash_key_equals($nginx_values, 'install', 1) { } } - create_resources(nginx_vhost, $nginx_values['vhosts']) + create_resources(nginx_vhost, $nginx_vhosts) } if ! defined(Firewall['100 tcp/443']) { @@ -743,41 +754,12 @@ define nginx_vhost ( $fastcgi_param_parts = [] } - if $ssl == 0 or $ssl == false or $ssl == '' { - $ssl_set = false - } else { - $ssl_set = true - } - - if $ssl_cert == 0 or $ssl_cert == false or $ssl_cert == '' { - $ssl_cert_set = $puphpet::params::ssl_cert_location - } else { - $ssl_cert_set = $ssl_cert - } - - if $ssl_key == 0 or $ssl_key == false or $ssl_key == '' { - $ssl_key_set = $puphpet::params::ssl_key_location - } else { - $ssl_key_set = $ssl_key - } - - if $ssl_port == 0 or $ssl_port == false or $ssl_port == '' { - $ssl_port_set = '443' - } else { - $ssl_port_set = $ssl_port - } - - if $rewrite_to_https == 0 or $rewrite_to_https == false or $rewrite_to_https == '' { - $rewrite_to_https_set = false - } else { - $rewrite_to_https_set = true - } - - if $spdy == off or $spdy == 0 or $spdy == false or $spdy == '' { - $spdy_set = off - } else { - $spdy_set = on - } + $ssl_set = value_true($ssl) ? { true => true, default => false, } + $ssl_cert_set = value_true($ssl_cert) ? { true => $ssl_cert, default => $puphpet::params::ssl_cert_location, } + $ssl_key_set = value_true($ssl_key) ? { true => $ssl_key, default => $puphpet::params::ssl_key_location, } + $ssl_port_set = value_true($ssl_port) ? { true => $ssl_port, default => '443', } + $rewrite_to_https_set = value_true($rewrite_to_https) ? { true => true, default => false, } + $spdy_set = value_true($spdy) ? { true => on, default => off, } nginx::resource::vhost { $server_name: server_name => $merged_server_name, @@ -798,6 +780,19 @@ define nginx_vhost ( $fastcgi_param = concat($fastcgi_param_parts, $envvars) + $fastcgi_pass_hash = fastcgi_pass ? { + null => {}, + '' => {}, + default => {'fastcgi_pass' => $fastcgi_pass}, + } + + $location_cfg_append = merge({ + 'fastcgi_split_path_info' => '^(.+\.php)(/.+)$', + 'fastcgi_param' => $fastcgi_param, + 'fastcgi_index' => 'index.php', + 'include' => 'fastcgi_params' + }, $fastcgi_pass_hash) + nginx::resource::location { "${server_name}-php": ensure => present, vhost => $server_name, @@ -806,20 +801,17 @@ define nginx_vhost ( try_files => ['$uri', '$uri/', "/${try_files}?\$args"], ssl => $ssl_set, www_root => $www_root, - location_cfg_append => { - 'fastcgi_split_path_info' => '^(.+\.php)(/.+)$', - 'fastcgi_param' => $fastcgi_param, - 'fastcgi_pass' => $fastcgi_pass, - 'fastcgi_index' => 'index.php', - 'include' => 'fastcgi_params' - }, + location_cfg_append => $location_cfg_append, notify => Class['nginx::service'], } } -define set_php5_fpm_sock_group_and_user (){ +define set_nginx_php5_fpm_sock_group_and_user () { exec { 'set php5_fpm_sock group and user': - command => "chmod 660 ${php5_fpm_sock} && chown www-data ${php5_fpm_sock} && chgrp www-data ${php5_fpm_sock} && touch /.puphpet-stuff/php5_fpm_sock", + command => "chmod 660 ${php5_fpm_sock} && \ + chown www-data ${php5_fpm_sock} && \ + chgrp www-data ${php5_fpm_sock} && \ + touch /.puphpet-stuff/php5_fpm_sock", creates => '/.puphpet-stuff/php5_fpm_sock', } } @@ -998,7 +990,7 @@ if hash_key_equals($php_values, 'install', 1) { { puphpet::ini { 'sendmail_path': entry => 'CUSTOM/sendmail_path', - value => '/usr/bin/env catchmail', + value => "${mailcatcher_values['settings']['mailcatcher_path']}/catchmail -f", php_version => $php_values['version'], webserver => $php_webserver_service_ini } @@ -1096,7 +1088,7 @@ if hash_key_equals($xhprof_values, 'install', 1) } if hash_key_equals($apache_values, 'install', 1) { - $xhprof_webroot_location = $puphpet::params::apache_webroot_location + $xhprof_webroot_location = '/var/www/default' $xhprof_webserver_service = 'httpd' } elsif hash_key_equals($nginx_values, 'install', 1) { $xhprof_webroot_location = $puphpet::params::nginx_webroot_location @@ -1216,11 +1208,11 @@ if hash_key_equals($mysql_values, 'install', 1) { if hash_key_equals($mysql_values, 'adminer', 1) and $mysql_php_installed { if hash_key_equals($apache_values, 'install', 1) { - $mysql_adminer_webroot_location = $puphpet::params::apache_webroot_location + $mysql_adminer_webroot_location = '/var/www/default' } elsif hash_key_equals($nginx_values, 'install', 1) { $mysql_adminer_webroot_location = $puphpet::params::nginx_webroot_location } else { - $mysql_adminer_webroot_location = $puphpet::params::apache_webroot_location + $mysql_adminer_webroot_location = '/var/www/default' } class { 'puphpet::adminer': @@ -1329,11 +1321,11 @@ if hash_key_equals($postgresql_values, 'install', 1) { if hash_key_equals($postgresql_values, 'adminer', 1) and $postgresql_php_installed { if hash_key_equals($apache_values, 'install', 1) { - $postgresql_adminer_webroot_location = $puphpet::params::apache_webroot_location + $postgresql_adminer_webroot_location = '/var/www/default' } elsif hash_key_equals($nginx_values, 'install', 1) { $postgresql_adminer_webroot_location = $puphpet::params::nginx_webroot_location } else { - $postgresql_adminer_webroot_location = $puphpet::params::apache_webroot_location + $postgresql_adminer_webroot_location = '/var/www/default' } class { 'puphpet::adminer': @@ -1364,7 +1356,7 @@ define postgresql_db ( $table = "${name}.*" exec{ "${name}-import": - command => "psql ${name} < ${sql_file}", + command => "sudo -u postgres psql ${name} < ${sql_file}", logoutput => true, refreshonly => $refresh, require => Postgresql::Server::Db[$name], @@ -1491,11 +1483,11 @@ if hash_key_equals($mariadb_values, 'install', 1) { if hash_key_equals($mariadb_values, 'adminer', 1) and $mariadb_php_installed { if hash_key_equals($apache_values, 'install', 1) { - $mariadb_adminer_webroot_location = $puphpet::params::apache_webroot_location + $mariadb_adminer_webroot_location = '/var/www/default' } elsif hash_key_equals($nginx_values, 'install', 1) { $mariadb_adminer_webroot_location = $puphpet::params::nginx_webroot_location } else { - $mariadb_adminer_webroot_location = $puphpet::params::apache_webroot_location + $mariadb_adminer_webroot_location = '/var/www/default' } class { 'puphpet::adminer': @@ -1662,7 +1654,7 @@ if $beanstalkd_values == undef { } if hash_key_equals($apache_values, 'install', 1) { - $beanstalk_console_webroot_location = "${puphpet::params::apache_webroot_location}/beanstalk_console" + $beanstalk_console_webroot_location = '/var/www/default/beanstalk_console' } elsif hash_key_equals($nginx_values, 'install', 1) { $beanstalk_console_webroot_location = "${puphpet::params::nginx_webroot_location}/beanstalk_console" } else { @@ -1724,6 +1716,11 @@ if hash_key_equals($apache_values, 'install', 1) } if hash_key_equals($rabbitmq_values, 'install', 1) { + if $::osfamily == 'redhat' { + Class['erlang'] -> Class['rabbitmq'] + include 'erlang' + } + create_resources('class', { 'rabbitmq' => $rabbitmq_values['settings'] }) if hash_key_equals($php_values, 'install', 1) and ! defined(Php::Pecl::Module['amqp']) { diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Gemfile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Gemfile new file mode 100644 index 00000000000..95c7a5dd0b0 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Gemfile @@ -0,0 +1,15 @@ +source 'https://rubygems.org' + +group :development, :test do + gem 'rake', :require => false + gem 'rspec-puppet', :require => false + gem 'puppetlabs_spec_helper', :require => false + gem 'puppet-lint', :require => false + gem 'rspec-system-puppet', '~>2.0.0' +end + +if puppetversion = ENV['PUPPET_GEM_VERSION'] + gem 'puppet', puppetversion, :require => false +else + gem 'puppet', :require => false +end \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/LICENSE b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/LICENSE new file mode 100644 index 00000000000..009b66b6cc2 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/LICENSE @@ -0,0 +1,13 @@ +Copyright 2012-2014 Michael Stahnke + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Modulefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Modulefile new file mode 100644 index 00000000000..237d164011a --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Modulefile @@ -0,0 +1,8 @@ +name 'stahnma-epel' +version '0.1.0' +source 'http://github.com/stahnma/puppet-module-epel' +author 'stahnma' +license 'Apache License, Version 2.0' +summary 'Setup the EPEL package repo' +description 'Setup the EPEL package repo on Centos/RHEL et all' +project_page 'http://github.com/stahnma/puppet-module-epel' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/README.md b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/README.md new file mode 100644 index 00000000000..33b87278574 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/README.md @@ -0,0 +1,90 @@ +# Configure EPEL (Extra Repository for Enterprise Linux) + +# About +This module basically just mimics the epel-release rpm. The same repos are +enabled/disabled and the GPG key is imported. In the end you will end up with +the EPEL repos configured. + +The following Repos will be setup and enabled by default: + + * epel + +Other repositories that will setup but disabled (as per the epel-release setup) + + * epel-debuginfo + * epel-source + * epel-testing + * epel-testing-debuginfo + * epel-testing-source + +# Proxy +If you have an http proxy required to access the internet, you can use either +a class parameter in the _epel_ class, or edit the $proxy variable in the +params.pp file. By default no proxy is assumed. + +# Why? +I am a big fan of EPEL. I actually was one of the people who helped get it +going. I am also the owner of the epel-release package, so in general this +module should stay fairly up to date with the official upstream package. + +I just got sick of coding Puppet modules and basically having an assumption +that EPEL was setup or installed. I can now depend on this module instead. + +I realize it is fairly trivial to get EPEL setup. Every now-and-then however +the path to epel-release changes because something changes in the package (mass +rebuild, rpm build macros updates, etc). This module will bypass the changing +URL and just setup the package mirrors. + +This does mean that if you are looking for RPM macros that are normally +included with EPEL release, this will not have them. + +# Futher Information + +* [EPEL Wiki](http://fedoraproject.org/wiki/EPEL) +* [epel-release package information](http://mirrors.servercentral.net/fedora/epel/6/i386/repoview/epel-release.html) + +# Testing + +* This is commonly used on Puppet Enterprise 3.x +* This was tested using Puppet 3.3.0 on Centos5/6 +* This was tested using Puppet 3.1.1 on Amazon's AWS Linux +* I assume it will work on any RHEL variant (Amazon Linux is debatable as a variant) + +# Lifecycle +* No functionality has been introduced that should break Puppet 2.6 or 2.7, but I am no longer testing these versions of Puppet as they are end-of-lifed from Puppet Labs. + +## Unit tests + +Install the necessary gems + + bundle install + +Run the RSpec and puppet-lint tests + + bundle exec rake ci + +## System tests + +If you have Vagrant >=1.1.0 you can also run system tests: + + RSPEC_SET=centos-64-x64 bundle exec rake spec:system + +Available RSPEC_SET options are in .nodeset.yml + +# License +Apache Software License 2.0 + +# Author/Contributors + * Chad Metcalf + * Joseph Swick + * Matthaus Owens + * Michael Stahnke + * Michael Stahnke + * Pro Cabales + * Proletaryo Cabales + * Stefan Goethals + * Tim Rupp + * Trey Dockendorf + * Troy Bollinger + * Vlastimil Holer + * Ewoud Kohl van Wijngaarden diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Rakefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Rakefile new file mode 100644 index 00000000000..5a71d17767d --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/Rakefile @@ -0,0 +1,17 @@ +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' +require 'rspec-system/rake_task' + +task :default do + sh %{rake -T} +end + +# Disable specific puppet-lint checks +PuppetLint.configuration.send("disable_80chars") +PuppetLint.configuration.send("disable_class_inherits_from_params_class") + +desc "Run rspec-puppet and puppet-lint tasks" +task :ci => [ + :lint, + :spec, +] diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-5 b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-5 new file mode 100644 index 00000000000..5a13bb4f9f9 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-5 @@ -0,0 +1,30 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.2.6 (GNU/Linux) + +mQGiBEXopTIRBACZDBMOoFOakAjaxw1LXjeSvh/kmE35fU1rXfM7T0AV31NATCLF +l5CQiNDA4oWreDThg2Bf6+LIVTsGQb1V+XXuLak4Em5yTYwMTVB//4/nMxQEbpl/ +QB2XwlJ7EQ0vW+kiPDz/7pHJz1p1jADzd9sQQicMtzysS4qT2i5A23j0VwCg1PB/ +lpYqo0ZhWTrevxKMa1n34FcD/REavj0hSLQFTaKNLHRotRTF8V0BajjSaTkUT4uk +/RTaZ8Kr1mTosVtosqmdIAA2XHxi8ZLiVPPSezJjfElsSqOAxEKPL0djfpp2wrTm +l/1iVnX+PZH5DRKCbjdCMLDJhYap7YUhcPsMGSeUKrwmBCBJUPc6DhjFvyhA9IMl +1T0+A/9SKTv94ToP/JYoCTHTgnG5MoVNafisfe0wojP2mWU4gRk8X4dNGKMj6lic +vM6gne3hESyjcqZSmr7yELPPGhI9MNauJ6Ob8cTR2T12Fmv9w03DD3MnBstR6vhP +QcqZKhc5SJYYY7oVfxlSOfF4xfwcHQKoD5TOKwIAQ6T8jyFpKbQkRmVkb3JhIEVQ +RUwgPGVwZWxAZmVkb3JhcHJvamVjdC5vcmc+iGQEExECACQFAkXopTICGwMFCRLM +AwAGCwkIBwMCAxUCAwMWAgECHgECF4AACgkQEZzANiF1IfabmQCgzvE60MnHSOBa +ZXXF7uU2Vzu8EOkAoKg9h+j0NuNom6WUYZyJQt4zc5seuQINBEXopTYQCADapnR/ +blrJ8FhlgNPl0X9S3JE/kygPbNXIqne4XBVYisVp0uzNCRUxNZq30MpY027JCs2J +nL2fMpwvx33f0phU029vrIZKA3CmnnwVsjcWfMJOVPBmVN7m5bGU68F+PdRIcDsl +PMOWRLkTBZOGolLgIbM4719fqA8etewILrX6uPvRDwywV7/sPCFpRcfNNBUY+Zx3 +5bf4fnkaCKxgXgQS3AT+hGYhlzIqQVTkGNveHTnt4SSzgAqR9sSwQwqvEfVtYNeS +w5rDguLG41HQm1Hojv59HNYjH6F/S1rClZi21bLgZbKpCFX76qPt8CTw+iQLBPPd +yoOGHfzyp7nsfhUrAAMFB/9/H9Gpk822ZpBexQW4y3LGFo9ZSnmu+ueOZPU3SqDA +DW1ovZdYzGuJTGGM9oMl6bL8eZrcUBBOFaWge5wZczIE3hx2exEOkDdvq+MUDVD1 +axmN45q/7h1NYRp5GQL2ZsoV4g9U2gMdzHOFtZCER6PP9ErVlfJpgBUCdSL93V4H +Sgpkk7znmTOklbCM6l/G/A6q4sCRqfzHwVSTiruyTBiU9lfROsAl8fjIq2OzWJ2T +P9sadBe1llUYaow7txYSUxssW+89avct35gIyrBbof5M+CBXyAOUaSWmpM2eub24 +0qbqiSr/Y6Om0t6vSzR8gRk7g+1H6IE0Tt1IJCvCAMimiE8EGBECAA8FAkXopTYC +GwwFCRLMAwAACgkQEZzANiF1IfZQYgCgiZHCv4xb+sTHCn/otc1Ovvi/OgMAnRXY +bbsLFWOfmzAnNIGvFRWy+YHi +=MMNL +-----END PGP PUBLIC KEY BLOCK----- diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-6 b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-6 new file mode 100644 index 00000000000..7a2030489d2 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-6 @@ -0,0 +1,29 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.4.5 (GNU/Linux) + +mQINBEvSKUIBEADLGnUj24ZVKW7liFN/JA5CgtzlNnKs7sBg7fVbNWryiE3URbn1 +JXvrdwHtkKyY96/ifZ1Ld3lE2gOF61bGZ2CWwJNee76Sp9Z+isP8RQXbG5jwj/4B +M9HK7phktqFVJ8VbY2jfTjcfxRvGM8YBwXF8hx0CDZURAjvf1xRSQJ7iAo58qcHn +XtxOAvQmAbR9z6Q/h/D+Y/PhoIJp1OV4VNHCbCs9M7HUVBpgC53PDcTUQuwcgeY6 +pQgo9eT1eLNSZVrJ5Bctivl1UcD6P6CIGkkeT2gNhqindRPngUXGXW7Qzoefe+fV +QqJSm7Tq2q9oqVZ46J964waCRItRySpuW5dxZO34WM6wsw2BP2MlACbH4l3luqtp +Xo3Bvfnk+HAFH3HcMuwdaulxv7zYKXCfNoSfgrpEfo2Ex4Im/I3WdtwME/Gbnwdq +3VJzgAxLVFhczDHwNkjmIdPAlNJ9/ixRjip4dgZtW8VcBCrNoL+LhDrIfjvnLdRu +vBHy9P3sCF7FZycaHlMWP6RiLtHnEMGcbZ8QpQHi2dReU1wyr9QgguGU+jqSXYar +1yEcsdRGasppNIZ8+Qawbm/a4doT10TEtPArhSoHlwbvqTDYjtfV92lC/2iwgO6g +YgG9XrO4V8dV39Ffm7oLFfvTbg5mv4Q/E6AWo/gkjmtxkculbyAvjFtYAQARAQAB +tCFFUEVMICg2KSA8ZXBlbEBmZWRvcmFwcm9qZWN0Lm9yZz6JAjYEEwECACAFAkvS +KUICGw8GCwkIBwMCBBUCCAMEFgIDAQIeAQIXgAAKCRA7Sd8qBgi4lR/GD/wLGPv9 +qO39eyb9NlrwfKdUEo1tHxKdrhNz+XYrO4yVDTBZRPSuvL2yaoeSIhQOKhNPfEgT +9mdsbsgcfmoHxmGVcn+lbheWsSvcgrXuz0gLt8TGGKGGROAoLXpuUsb1HNtKEOwP +Q4z1uQ2nOz5hLRyDOV0I2LwYV8BjGIjBKUMFEUxFTsL7XOZkrAg/WbTH2PW3hrfS +WtcRA7EYonI3B80d39ffws7SmyKbS5PmZjqOPuTvV2F0tMhKIhncBwoojWZPExft +HpKhzKVh8fdDO/3P1y1Fk3Cin8UbCO9MWMFNR27fVzCANlEPljsHA+3Ez4F7uboF +p0OOEov4Yyi4BEbgqZnthTG4ub9nyiupIZ3ckPHr3nVcDUGcL6lQD/nkmNVIeLYP +x1uHPOSlWfuojAYgzRH6LL7Idg4FHHBA0to7FW8dQXFIOyNiJFAOT2j8P5+tVdq8 +wB0PDSH8yRpn4HdJ9RYquau4OkjluxOWf0uRaS//SUcCZh+1/KBEOmcvBHYRZA5J +l/nakCgxGb2paQOzqqpOcHKvlyLuzO5uybMXaipLExTGJXBlXrbbASfXa/yGYSAG +iVrGz9CE6676dMlm8F+s3XXE13QZrXmjloc6jwOljnfAkjTGXjiB7OULESed96MR +XtfLk0W5Ab9pd7tKDR6QHI7rgHXfCopRnZ2VVQ== +=V/6I +-----END PGP PUBLIC KEY BLOCK----- diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-7 b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-7 new file mode 100644 index 00000000000..f205ede4637 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/files/RPM-GPG-KEY-EPEL-7 @@ -0,0 +1,29 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- +Version: GnuPG v1.4.11 (GNU/Linux) + +mQINBFKuaIQBEAC1UphXwMqCAarPUH/ZsOFslabeTVO2pDk5YnO96f+rgZB7xArB +OSeQk7B90iqSJ85/c72OAn4OXYvT63gfCeXpJs5M7emXkPsNQWWSju99lW+AqSNm +jYWhmRlLRGl0OO7gIwj776dIXvcMNFlzSPj00N2xAqjMbjlnV2n2abAE5gq6VpqP +vFXVyfrVa/ualogDVmf6h2t4Rdpifq8qTHsHFU3xpCz+T6/dGWKGQ42ZQfTaLnDM +jToAsmY0AyevkIbX6iZVtzGvanYpPcWW4X0RDPcpqfFNZk643xI4lsZ+Y2Er9Yu5 +S/8x0ly+tmmIokaE0wwbdUu740YTZjCesroYWiRg5zuQ2xfKxJoV5E+Eh+tYwGDJ +n6HfWhRgnudRRwvuJ45ztYVtKulKw8QQpd2STWrcQQDJaRWmnMooX/PATTjCBExB +9dkz38Druvk7IkHMtsIqlkAOQMdsX1d3Tov6BE2XDjIG0zFxLduJGbVwc/6rIc95 +T055j36Ez0HrjxdpTGOOHxRqMK5m9flFbaxxtDnS7w77WqzW7HjFrD0VeTx2vnjj +GqchHEQpfDpFOzb8LTFhgYidyRNUflQY35WLOzLNV+pV3eQ3Jg11UFwelSNLqfQf +uFRGc+zcwkNjHh5yPvm9odR1BIfqJ6sKGPGbtPNXo7ERMRypWyRz0zi0twARAQAB +tChGZWRvcmEgRVBFTCAoNykgPGVwZWxAZmVkb3JhcHJvamVjdC5vcmc+iQI4BBMB +AgAiBQJSrmiEAhsPBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBqL66iNSxk +5cfGD/4spqpsTjtDM7qpytKLHKruZtvuWiqt5RfvT9ww9GUUFMZ4ZZGX4nUXg49q +ixDLayWR8ddG/s5kyOi3C0uX/6inzaYyRg+Bh70brqKUK14F1BrrPi29eaKfG+Gu +MFtXdBG2a7OtPmw3yuKmq9Epv6B0mP6E5KSdvSRSqJWtGcA6wRS/wDzXJENHp5re +9Ism3CYydpy0GLRA5wo4fPB5uLdUhLEUDvh2KK//fMjja3o0L+SNz8N0aDZyn5Ax +CU9RB3EHcTecFgoy5umRj99BZrebR1NO+4gBrivIfdvD4fJNfNBHXwhSH9ACGCNv +HnXVjHQF9iHWApKkRIeh8Fr2n5dtfJEF7SEX8GbX7FbsWo29kXMrVgNqHNyDnfAB +VoPubgQdtJZJkVZAkaHrMu8AytwT62Q4eNqmJI1aWbZQNI5jWYqc6RKuCK6/F99q +thFT9gJO17+yRuL6Uv2/vgzVR1RGdwVLKwlUjGPAjYflpCQwWMAASxiv9uPyYPHc +ErSrbRG0wjIfAR3vus1OSOx3xZHZpXFfmQTsDP7zVROLzV98R3JwFAxJ4/xqeON4 +vCPFU6OsT3lWQ8w7il5ohY95wmujfr6lk89kEzJdOTzcn7DBbUru33CQMGKZ3Evt +RjsC7FDbL017qxS+ZVA/HGkyfiu4cpgV8VUnbql5eAZ+1Ll6Dw== +=hdPa +-----END PGP PUBLIC KEY BLOCK----- diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/lib/facter/os_maj_version.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/lib/facter/os_maj_version.rb new file mode 100644 index 00000000000..ba5cb84043e --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/lib/facter/os_maj_version.rb @@ -0,0 +1,11 @@ +# This is a simple fact to get the Major version of an OS without having to +# have the entire LSB suite installed. LSB seems to pull in about 300 megs of +# stuff I often don't require. This fact is quick to load so it shouldn't be +# much of an issue. + +Facter.add(:os_maj_version) do + setcode do + v = Facter.value(:operatingsystemrelease) + v.split('.')[0].strip + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/init.pp new file mode 100644 index 00000000000..f9f4be114a6 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/init.pp @@ -0,0 +1,135 @@ +# Class epel +# +# Actions: +# Configure the proper repositories and import GPG keys +# +# Reqiures: +# You should probably be on an Enterprise Linux variant. (Centos, RHEL, +# Scientific, Oracle, Ascendos, et al) +# +# Sample Usage: +# include epel +# +class epel ( + $epel_mirrorlist = $epel::params::epel_mirrorlist, + $epel_baseurl = $epel::params::epel_baseurl, + $epel_failovermethod = $epel::params::epel_failovermethod, + $epel_proxy = $epel::params::epel_proxy, + $epel_enabled = $epel::params::epel_enabled, + $epel_gpgcheck = $epel::params::epel_gpgcheck, + $epel_testing_baseurl = $epel::params::epel_testing_baseurl, + $epel_testing_failovermethod = $epel::params::epel_testing_failovermethod, + $epel_testing_proxy = $epel::params::epel_testing_proxy, + $epel_testing_enabled = $epel::params::epel_testing_enabled, + $epel_testing_gpgcheck = $epel::params::epel_testing_gpgcheck, + $epel_source_mirrorlist = $epel::params::epel_source_mirrorlist, + $epel_source_baseurl = $epel::params::epel_source_baseurl, + $epel_source_failovermethod = $epel::params::epel_source_failovermethod, + $epel_source_proxy = $epel::params::epel_source_proxy, + $epel_source_enabled = $epel::params::epel_source_enabled, + $epel_source_gpgcheck = $epel::params::epel_source_gpgcheck, + $epel_debuginfo_mirrorlist = $epel::params::epel_debuginfo_mirrorlist, + $epel_debuginfo_baseurl = $epel::params::epel_debuginfo_baseurl, + $epel_debuginfo_failovermethod = $epel::params::epel_debuginfo_failovermethod, + $epel_debuginfo_proxy = $epel::params::epel_debuginfo_proxy, + $epel_debuginfo_enabled = $epel::params::epel_debuginfo_enabled, + $epel_debuginfo_gpgcheck = $epel::params::epel_debuginfo_gpgcheck, + $epel_testing_source_baseurl = $epel::params::epel_testing_source_baseurl, + $epel_testing_source_failovermethod = $epel::params::epel_testing_source_failovermethod, + $epel_testing_source_proxy = $epel::params::epel_testing_source_proxy, + $epel_testing_source_enabled = $epel::params::epel_testing_source_enabled, + $epel_testing_source_gpgcheck = $epel::params::epel_testing_source_gpgcheck, + $epel_testing_debuginfo_baseurl = $epel::params::epel_testing_debuginfo_baseurl, + $epel_testing_debuginfo_failovermethod = $epel::params::epel_testing_debuginfo_failovermethod, + $epel_testing_debuginfo_proxy = $epel::params::epel_testing_debuginfo_proxy, + $epel_testing_debuginfo_enabled = $epel::params::epel_testing_debuginfo_enabled, + $epel_testing_debuginfo_gpgcheck = $epel::params::epel_testing_debuginfo_gpgcheck +) inherits epel::params { + + if $::osfamily == 'RedHat' and $::operatingsystem !~ /Fedora|Amazon/ { + yumrepo { 'epel-testing': + baseurl => $epel_testing_baseurl, + failovermethod => $epel_testing_failovermethod, + proxy => $epel_testing_proxy, + enabled => $epel_testing_enabled, + gpgcheck => $epel_testing_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - Testing - \$basearch ", + } + + yumrepo { 'epel-testing-debuginfo': + baseurl => $epel_testing_debuginfo_baseurl, + failovermethod => $epel_testing_debuginfo_failovermethod, + proxy => $epel_testing_debuginfo_proxy, + enabled => $epel_testing_debuginfo_enabled, + gpgcheck => $epel_testing_debuginfo_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - Testing - \$basearch - Debug", + } + + yumrepo { 'epel-testing-source': + baseurl => $epel_testing_source_baseurl, + failovermethod => $epel_testing_source_failovermethod, + proxy => $epel_testing_source_proxy, + enabled => $epel_testing_source_enabled, + gpgcheck => $epel_testing_source_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - Testing - \$basearch - Source", + } + + yumrepo { 'epel': + mirrorlist => $epel_mirrorlist, + baseurl => $epel_baseurl, + failovermethod => $epel_failovermethod, + proxy => $epel_proxy, + enabled => $epel_enabled, + gpgcheck => $epel_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - \$basearch", + } + + yumrepo { 'epel-debuginfo': + mirrorlist => $epel_debuginfo_mirrorlist, + baseurl => $epel_debuginfo_baseurl, + failovermethod => $epel_debuginfo_failovermethod, + proxy => $epel_debuginfo_proxy, + enabled => $epel_debuginfo_enabled, + gpgcheck => $epel_debuginfo_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - \$basearch - Debug", + } + + yumrepo { 'epel-source': + mirrorlist => $epel_source_mirrorlist, + baseurl => $epel_source_baseurl, + failovermethod => $epel_source_failovermethod, + proxy => $epel_source_proxy, + enabled => $epel_source_enabled, + gpgcheck => $epel_source_gpgcheck, + gpgkey => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + descr => "Extra Packages for Enterprise Linux ${::os_maj_version} - \$basearch - Source", + } + + file { "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}": + ensure => present, + owner => 'root', + group => 'root', + mode => '0644', + source => "puppet:///modules/epel/RPM-GPG-KEY-EPEL-${::os_maj_version}", + } + + epel::rpm_gpg_key{ "EPEL-${::os_maj_version}": + path => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-${::os_maj_version}", + before => Yumrepo['epel','epel-source','epel-debuginfo','epel-testing','epel-testing-source','epel-testing-debuginfo'], + } + + } elsif $::osfamily == 'RedHat' and $::operatingsystem == 'Amazon' { + yumrepo { 'epel': + enabled => $epel_enabled, + gpgcheck => $epel_gpgcheck, + } + } else { + notice ("Your operating system ${::operatingsystem} will not have the EPEL repository applied") + } + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/params.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/params.pp new file mode 100644 index 00000000000..0939de9045a --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/params.pp @@ -0,0 +1,45 @@ +# Optional parameters in setting up EPEL +class epel::params { + # Setting to 'absent' will fall back to the yum.conf + # Setting proxy here will be the default for all repos. + # + # If you wish to set a proxy for an individual set of repos, + # you can declare $proxy in that class, and should scope to + # the most specific declaration of proxy. + $proxy = 'absent' + + $epel_mirrorlist = "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-${::os_maj_version}&arch=\$basearch" + $epel_baseurl = 'absent' + $epel_failovermethod = 'priority' + $epel_proxy = $proxy + $epel_enabled = '1' + $epel_gpgcheck = '1' + $epel_testing_baseurl = "http://download.fedoraproject.org/pub/epel/testing/${::os_maj_version}/\$basearch" + $epel_testing_failovermethod = 'priority' + $epel_testing_proxy = $proxy + $epel_testing_enabled = '0' + $epel_testing_gpgcheck = '1' + $epel_source_mirrorlist = "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-source-${::os_maj_version}&arch=\$basearch" + $epel_source_baseurl = 'absent' + $epel_source_failovermethod = 'priority' + $epel_source_proxy = $proxy + $epel_source_enabled = '0' + $epel_source_gpgcheck = '1' + $epel_debuginfo_mirrorlist = "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-debug-${::os_maj_version}&arch=\$basearch" + $epel_debuginfo_baseurl = 'absent' + $epel_debuginfo_failovermethod = 'priority' + $epel_debuginfo_proxy = $proxy + $epel_debuginfo_enabled = '0' + $epel_debuginfo_gpgcheck = '1' + $epel_testing_source_baseurl = "http://download.fedoraproject.org/pub/epel/testing/${::os_maj_version}/SRPMS" + $epel_testing_source_failovermethod = 'priority' + $epel_testing_source_proxy = $proxy + $epel_testing_source_enabled = '0' + $epel_testing_source_gpgcheck = '1' + $epel_testing_debuginfo_baseurl = "http://download.fedoraproject.org/pub/epel/testing/${::os_maj_version}/\$basearch/debug" + $epel_testing_debuginfo_failovermethod = 'priority' + $epel_testing_debuginfo_proxy = $proxy + $epel_testing_debuginfo_enabled = '0' + $epel_testing_debuginfo_gpgcheck = '1' + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/rpm_gpg_key.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/rpm_gpg_key.pp new file mode 100644 index 00000000000..ee0604dbbf9 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/manifests/rpm_gpg_key.pp @@ -0,0 +1,28 @@ +# Define epel::rpm_gpg_key +# +# Actions: +# Import a RPM gpg key +# +# Parameters: +# +# [*path*] +# Path of the RPM GPG key to import +# +# Reqiures: +# You should probably be on an Enterprise Linux variant. (Centos, RHEL, Scientific, Oracle, Ascendos, et al) +# +# Sample Usage: +# epel::rpm_gpg_key{ "EPEL-6": +# path => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6" +# } +# +define epel::rpm_gpg_key($path) { + # Given the path to a key, see if it is imported, if not, import it + exec { "import-${name}": + path => '/bin:/usr/bin:/sbin:/usr/sbin', + command => "rpm --import ${path}", + unless => "rpm -q gpg-pubkey-$(echo $(gpg --throw-keyids < ${path}) | cut --characters=11-18 | tr '[A-Z]' '[a-z]')", + require => File[$path], + logoutput => 'on_failure', + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/metadata.json b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/metadata.json new file mode 100644 index 00000000000..ba8770e8b69 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/metadata.json @@ -0,0 +1,45 @@ +{ + "name": "stahnma-epel", + "version": "0.1.0", + "source": "http://github.com/stahnma/puppet-module-epel", + "author": "stahnma", + "license": "Apache License, Version 2.0", + "summary": "Setup the EPEL package repo", + "description": "Setup the EPEL package repo on Centos/RHEL et all", + "project_page": "http://github.com/stahnma/puppet-module-epel", + "dependencies": [ + + ], + "types": [ + + ], + "checksums": { + "Gemfile": "3189476f30a99858b367d955298fe469", + "LICENSE": "94f0b1430ad7e59227ccabf8232f81d5", + "Modulefile": "250a4370b189d3f2e68ffd359ee02bb5", + "README.md": "6b4c4d2e7f0f9c1b6197529fa1120c88", + "Rakefile": "946eced163d7f8e0da85bda4baa7fa9c", + "files/RPM-GPG-KEY-EPEL-5": "0466c259781def56dafe0a2cdc9de0c5", + "files/RPM-GPG-KEY-EPEL-6": "d865e6b948a74cb03bc3401c0b01b785", + "files/RPM-GPG-KEY-EPEL-7": "58fa8ae27c89f37b08429f04fd4a88cc", + "lib/facter/os_maj_version.rb": "806fb856251b605df379e973c716a41c", + "manifests/init.pp": "61856de8db1eb00700e0a9a93aea506f", + "manifests/params.pp": "4fb2e283b4ba6e41abd7a914bdd001b8", + "manifests/rpm_gpg_key.pp": "69086f12752a14b200e462afaa59a93c", + "spec/classes/epel_spec.rb": "7e8e5973fdccb866e91ed00a3fd0af4c", + "spec/classes/shared_base.rb": "a6a46eb7225a1814b9343f32190ba75b", + "spec/classes/shared_debuginfo.rb": "1bd23934bc1f7d14d2491c7741f10299", + "spec/classes/shared_gpgkey.rb": "38a62fe24acfc9cc8d740d242c9f1c85", + "spec/classes/shared_source.rb": "6581989ed1ca2edd589ed98ecb08bdfa", + "spec/classes/shared_testing.rb": "50e936b9cf241c9849cf551961492532", + "spec/classes/shared_testing_debuginfo.rb": "41e8a2215d347246ff241f1b3a819c91", + "spec/classes/shared_testing_source.rb": "8cd827b2cb0b08b1633d70784417f946", + "spec/defines/rpm_gpg_key_spec.rb": "489fa716eaa2aba013089a6cf552c5a6", + "spec/spec_helper.rb": "a5ad64bd67aa3fe2512fa7ba505c8e8b", + "spec/spec_helper_system.rb": "d24a7ffdf4b67dbbd3ef5687292f51cf", + "spec/system/basic_spec.rb": "bc475b95f390134b31d905590bf8b039", + "spec/system/usage_spec.rb": "04506df5627ecbe975acd1fd0407ae40", + "spec/unit/facter/os_maj_version_spec.rb": "67ab2730991d4a8430f1115aad46bcea", + "tests/init.pp": "7c69b7adf2ba141cb62cfc9e0704d59e" + } +} \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/epel_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/epel_spec.rb new file mode 100644 index 00000000000..5d95a61a5f7 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/epel_spec.rb @@ -0,0 +1,80 @@ +require 'spec_helper' +require 'classes/shared_gpgkey' +require 'classes/shared_base' +require 'classes/shared_source' +require 'classes/shared_debuginfo' +require 'classes/shared_testing' +require 'classes/shared_testing_source' +require 'classes/shared_testing_debuginfo' + +describe 'epel' do + it { should create_class('epel') } + it { should contain_class('epel::params') } + + context "operatingsystem => #{default_facts[:operatingsystem]}" do + context 'os_maj_version => 6' do + include_context :base_6 + include_context :gpgkey_6 + include_context :epel_source_6 + include_context :epel_debuginfo_6 + include_context :epel_testing_6 + include_context :epel_testing_source_6 + include_context :epel_testing_debuginfo_6 + + let :facts do + default_facts.merge({ + :operatingsystemrelease => '6.4', + :os_maj_version => '6', + }) + end + + context 'epel_baseurl => http://example.com/epel/6/x86_64' do + let(:params) {{ :epel_baseurl => "http://example.com/epel/6/x86_64" }} + it { should contain_yumrepo('epel').with('baseurl' => 'http://example.com/epel/6/x86_64') } + end + + context 'epel_mirrorlist => absent' do + let(:params) {{ :epel_mirrorlist => 'absent' }} + it { should contain_yumrepo('epel').with('mirrorlist' => 'absent') } + end + end + + context 'os_maj_version => 5' do + include_context :base_5 + include_context :gpgkey_5 + include_context :epel_source_5 + include_context :epel_debuginfo_5 + include_context :epel_testing_5 + include_context :epel_testing_source_5 + include_context :epel_testing_debuginfo_5 + + let :facts do + default_facts.merge({ + :operatingsystemrelease => '5.9', + :os_maj_version => '5', + }) + end + end + end + + context 'operatingsystem => Amazon' do + let :facts do + default_facts.merge({ + :operatingsystem => 'Amazon', + }) + end + + it { should_not contain_yumrepo('epel-testing') } + it { should_not contain_yumrepo('epel-testing-debuginfo') } + it { should_not contain_yumrepo('epel-testing-source') } + it { should_not contain_yumrepo('epel-debuginfo') } + it { should_not contain_yumrepo('epel-source') } + + it do + should contain_yumrepo('epel').with({ + 'enabled' => '1', + 'gpgcheck' => '1', + }) + end + end +end \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_base.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_base.rb new file mode 100644 index 00000000000..89b3c58cca7 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_base.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :base do + it do + should contain_yumrepo('epel').with({ + 'failovermethod' => 'priority', + 'proxy' => 'absent', + 'enabled' => '1', + 'gpgcheck' => '1', + }) + end +end + +shared_context :base_6 do + include_context :base + + it do + should contain_yumrepo('epel').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-6&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - $basearch", + }) + end +end + +shared_context :base_5 do + include_context :base + + it do + should contain_yumrepo('epel').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-5&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - $basearch", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_debuginfo.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_debuginfo.rb new file mode 100644 index 00000000000..d47934d1425 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_debuginfo.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :epel_debuginfo do + it do + should contain_yumrepo('epel-debuginfo').with({ + 'proxy' => 'absent', + 'failovermethod' => 'priority', + 'enabled' => '0', + 'gpgcheck' => '1', + }) + end +end + +shared_context :epel_debuginfo_6 do + include_context :epel_debuginfo + + it do + should contain_yumrepo('epel-debuginfo').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-debug-6&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - $basearch - Debug", + }) + end +end + +shared_context :epel_debuginfo_5 do + include_context :epel_debuginfo + + it do + should contain_yumrepo('epel-debuginfo').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-debug-5&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - $basearch - Debug", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_gpgkey.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_gpgkey.rb new file mode 100644 index 00000000000..8b79c8cdd7f --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_gpgkey.rb @@ -0,0 +1,37 @@ +require 'spec_helper' + +shared_context :gpgkey_6 do + it do + should contain_file("/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6").with({ + 'ensure' => 'present', + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'source' => "puppet:///modules/epel/RPM-GPG-KEY-EPEL-6", + }) + end + + it do + should contain_epel__rpm_gpg_key("EPEL-6").with({ + 'path' => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6" + }) + end +end + +shared_context :gpgkey_5 do + it do + should contain_file("/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5").with({ + 'ensure' => 'present', + 'owner' => 'root', + 'group' => 'root', + 'mode' => '0644', + 'source' => "puppet:///modules/epel/RPM-GPG-KEY-EPEL-5", + }) + end + + it do + should contain_epel__rpm_gpg_key("EPEL-5").with({ + 'path' => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5" + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_source.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_source.rb new file mode 100644 index 00000000000..c371465ba91 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_source.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :epel_source do + it do + should contain_yumrepo('epel-source').with({ + 'proxy' => 'absent', + 'failovermethod' => 'priority', + 'enabled' => '0', + 'gpgcheck' => '1', + }) + end +end + +shared_context :epel_source_6 do + include_context :epel_source + + it do + should contain_yumrepo('epel-source').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-source-6&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - $basearch - Source", + }) + end +end + +shared_context :epel_source_5 do + include_context :epel_source + + it do + should contain_yumrepo('epel-source').with({ + 'mirrorlist' => "http://mirrors.fedoraproject.org/mirrorlist?repo=epel-source-5&arch=$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - $basearch - Source", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing.rb new file mode 100644 index 00000000000..d560edb6e0a --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :epel_testing do + it do + should contain_yumrepo('epel-testing').with({ + 'failovermethod' => 'priority', + 'proxy' => 'absent', + 'enabled' => '0', + 'gpgcheck' => '1', + }) + end +end + +shared_context :epel_testing_6 do + include_context :epel_testing + + it do + should contain_yumrepo('epel-testing').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/6/$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - Testing - $basearch ", + }) + end +end + +shared_context :epel_testing_5 do + include_context :epel_testing + + it do + should contain_yumrepo('epel-testing').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/5/$basearch", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - Testing - $basearch ", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_debuginfo.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_debuginfo.rb new file mode 100644 index 00000000000..62f647d3790 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_debuginfo.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :epel_testing_debuginfo do + it do + should contain_yumrepo('epel-testing-debuginfo').with({ + 'failovermethod' => 'priority', + 'proxy' => 'absent', + 'enabled' => '0', + 'gpgcheck' => '1', + }) + end +end + +shared_context :epel_testing_debuginfo_6 do + include_context :epel_testing_debuginfo + + it do + should contain_yumrepo('epel-testing-debuginfo').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/6/$basearch/debug", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - Testing - $basearch - Debug", + }) + end +end + +shared_context :epel_testing_debuginfo_5 do + include_context :epel_testing_debuginfo + + it do + should contain_yumrepo('epel-testing-debuginfo').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/5/$basearch/debug", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - Testing - $basearch - Debug", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_source.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_source.rb new file mode 100644 index 00000000000..1a7e0a6ae83 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/classes/shared_testing_source.rb @@ -0,0 +1,36 @@ +require 'spec_helper' + +shared_context :epel_testing_source do + it do + should contain_yumrepo('epel-testing-source').with({ + 'failovermethod' => 'priority', + 'proxy' => 'absent', + 'enabled' => '0', + 'gpgcheck' => '1', + }) + end +end + +shared_context :epel_testing_source_6 do + include_context :epel_testing_source + + it do + should contain_yumrepo('epel-testing-source').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/6/SRPMS", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6", + 'descr' => "Extra Packages for Enterprise Linux 6 - Testing - $basearch - Source", + }) + end +end + +shared_context :epel_testing_source_5 do + include_context :epel_testing_source + + it do + should contain_yumrepo('epel-testing-source').with({ + 'baseurl' => "http://download.fedoraproject.org/pub/epel/testing/5/SRPMS", + 'gpgkey' => "file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5", + 'descr' => "Extra Packages for Enterprise Linux 5 - Testing - $basearch - Source", + }) + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/defines/rpm_gpg_key_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/defines/rpm_gpg_key_spec.rb new file mode 100644 index 00000000000..63cfe08ff94 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/defines/rpm_gpg_key_spec.rb @@ -0,0 +1,57 @@ +require 'spec_helper' + +describe 'epel::rpm_gpg_key' do + context 'os_maj_version => 6' do + let :facts do + default_facts.merge({ + :operatingsystemrelease => '6.4', + :os_maj_version => '6', + }) + end + + let :title do + 'EPEL-6' + end + + let :params do + { :path => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6" } + end + + it do + should contain_exec("import-#{title}").with({ + 'path' => '/bin:/usr/bin:/sbin:/usr/sbin', + 'command' => "rpm --import #{params[:path]}", + 'unless' => "rpm -q gpg-pubkey-$(echo $(gpg --throw-keyids < #{params[:path]}) | cut --characters=11-18 | tr '[A-Z]' '[a-z]')", + 'require' => "File[#{params[:path]}]", + 'logoutput' => 'on_failure', + }) + end + end + + context 'os_maj_version => 5' do + let :facts do + default_facts.merge({ + :operatingsystemrelease => '5.9', + :os_maj_version => '5', + }) + end + + let :title do + 'EPEL-5' + end + + let :params do + { :path => "/etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-5" } + end + + it do + should contain_exec("import-#{title}").with({ + 'path' => '/bin:/usr/bin:/sbin:/usr/sbin', + 'command' => "rpm --import #{params[:path]}", + 'unless' => "rpm -q gpg-pubkey-$(echo $(gpg --throw-keyids < #{params[:path]}) | cut --characters=11-18 | tr '[A-Z]' '[a-z]')", + 'require' => "File[#{params[:path]}]", + 'logoutput' => 'on_failure', + }) + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper.rb new file mode 100644 index 00000000000..eafe6b60012 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper.rb @@ -0,0 +1,8 @@ +require 'puppetlabs_spec_helper/module_spec_helper' + +def default_facts + { + :osfamily => 'RedHat', + :operatingsystem => 'CentOS', + } +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_system.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper_system.rb similarity index 69% rename from dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_system.rb rename to dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper_system.rb index a790d7d526c..cf680367b94 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_system.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/spec_helper_system.rb @@ -4,22 +4,20 @@ require 'rspec-system-puppet/helpers' include RSpecSystemPuppet::Helpers RSpec.configure do |c| - # Project root + # Project root for the this module's code proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) - # Enable colour + # Enable colour in Jenkins c.tty = true + c.include RSpecSystemPuppet::Helpers + # This is where we 'setup' the nodes before running our tests c.before :suite do # Install puppet puppet_install puppet_master_install - # Replace mymodule with your module name - puppet_module_install(:source => proj_root, :module_name => 'supervisord') - shell('puppet module install puppetlabs/stdlib') - shell('puppet module install puppetlabs/concat') - + puppet_module_install(:source => proj_root, :module_name => 'epel') end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/basic_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/basic_spec.rb new file mode 100644 index 00000000000..569e12d3737 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/basic_spec.rb @@ -0,0 +1,36 @@ +require 'spec_helper_system' + +describe 'epel class:' do + context puppet_agent do + its(:stderr) { should be_empty } + its(:exit_code) { should_not == 1 } + end + + # Verify the os_maj_version fact is working + context shell 'facter --puppet os_maj_version' do + its(:stdout) { should_not be_empty } + its(:stderr) { should be_empty } + its(:exit_code) { should be_zero } + end + + pp = "class { 'epel': }" + + context puppet_apply pp do + its(:stderr) { should be_empty } + its(:exit_code) { should_not == 1 } + its(:refresh) { should be_nil } + its(:stderr) { should be_empty } + its(:exit_code) { should be_zero } + end + + context 'test EPEL repo presence' do + facts = node.facts + + # Only test for EPEL's presence if not Fedora + if facts['operatingsystem'] !~ /Fedora/ + context shell '/usr/bin/yum-config-manager epel | grep -q "\[epel\]"' do + its(:exit_code) { should be_zero } + end + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/usage_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/usage_spec.rb new file mode 100644 index 00000000000..2b0d8f36e28 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/system/usage_spec.rb @@ -0,0 +1,60 @@ +require 'spec_helper_system' + +describe 'standage usage tests:' do + context 'test epel baseurl and mirrorlist' do + facts = node.facts + os_maj_version = facts['operatingsystemrelease'].split('.')[0] + pp = <<-EOS + class { 'epel': + epel_baseurl => 'http://dl.fedoraproject.org/pub/epel/#{os_maj_version}/x86_64/', + epel_mirrorlist => 'absent', + } + EOS + + context puppet_apply pp do + its(:stderr) { should be_empty } + its(:exit_code) { should_not == 1 } + its(:refresh) { should be_nil } + its(:stderr) { should be_empty } + its(:exit_code) { should be_zero } + end + + # Only test for EPEL's presence if not Fedora + if facts['operatingsystem'] !~ /Fedora/ + # Test the yum config to ensure mirrorlist was emptied + context shell '/usr/bin/yum-config-manager epel | egrep "^mirrorlist ="' do + its(:stdout) { should =~ /mirrorlist =\s+/ } + end + + # Test the yum config to ensure baseurl was defined + context shell '/usr/bin/yum-config-manager epel | egrep "^baseurl ="' do + its(:stdout) { should =~ /baseurl = http:\/\/dl.fedoraproject.org\/pub\/epel\/#{os_maj_version}\/x86_64\// } + end + end + end + + context 'test epel-testing is enabled' do + facts = node.facts + pp = <<-EOS + class { 'epel': + epel_testing_enabled => '1', + } + EOS + + context puppet_apply pp do + its(:stderr) { should be_empty } + its(:exit_code) { should_not == 1 } + its(:refresh) { should be_nil } + its(:stderr) { should be_empty } + its(:exit_code) { should be_zero } + end + + # Only test for EPEL's presence if not Fedora + if facts['operatingsystem'] !~ /Fedora/ + # Test the yum config to ensure epel-testing was enabled + context shell '/usr/bin/yum-config-manager epel-testing | grep -q "enabled = True"' do + its(:exit_code) { should be_zero } + end + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/unit/facter/os_maj_version_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/unit/facter/os_maj_version_spec.rb new file mode 100644 index 00000000000..83bcdffd2c9 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/spec/unit/facter/os_maj_version_spec.rb @@ -0,0 +1,21 @@ +require 'spec_helper' + +describe 'os_maj_version fact' do + before :each do + Facter.clear + end + + context "on 5.9 operatingsystemrelease" do + it "should have os_maj_version => 5" do + Facter.fact(:operatingsystemrelease).stubs(:value).returns("5.9") + Facter.fact(:os_maj_version).value.should == "5" + end + end + + context "on 6.4 operatingsystemrelease" do + it "should have os_maj_version => 6" do + Facter.fact(:operatingsystemrelease).stubs(:value).returns("6.4") + Facter.fact(:os_maj_version).value.should == "6" + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/tests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/tests/init.pp new file mode 100644 index 00000000000..c2e61d42989 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/epel/tests/init.pp @@ -0,0 +1,3 @@ +# And by test, I mean, run this thing for me using Puppet apply and I'll check +# it out. +include 'epel' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.fixtures.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.fixtures.yml new file mode 100644 index 00000000000..8968df1f459 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.fixtures.yml @@ -0,0 +1,7 @@ +fixtures: + repositories: + apt: git://github.com/puppetlabs/puppetlabs-apt.git + stdlib: git://github.com/puppetlabs/puppetlabs-stdlib.git + epel: git://github.com/stahnma/puppet-module-epel.git + symlinks: + erlang: "#{source_dir}" diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.nodeset.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.nodeset.yml new file mode 100644 index 00000000000..cbd0d57b83d --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.nodeset.yml @@ -0,0 +1,35 @@ +--- +default_set: 'centos-64-x64' +sets: + 'centos-59-x64': + nodes: + "main.foo.vm": + prefab: 'centos-59-x64' + 'centos-64-x64': + nodes: + "main.foo.vm": + prefab: 'centos-64-x64' + 'fedora-18-x64': + nodes: + "main.foo.vm": + prefab: 'fedora-18-x64' + 'debian-607-x64': + nodes: + "main.foo.vm": + prefab: 'debian-607-x64' + 'debian-70rc1-x64': + nodes: + "main.foo.vm": + prefab: 'debian-70rc1-x64' + 'ubuntu-server-10044-x64': + nodes: + "main.foo.vm": + prefab: 'ubuntu-server-10044-x64' + 'ubuntu-server-12042-x64': + nodes: + "main.foo.vm": + prefab: 'ubuntu-server-12042-x64' + 'sles-11sp1-x64': + nodes: + "main.foo.vm": + prefab: 'sles-11sp1-x64' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.rspec b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.rspec new file mode 100644 index 00000000000..49d5710b3ef --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.rspec @@ -0,0 +1 @@ +--format documentation diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.travis.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.travis.yml new file mode 100644 index 00000000000..cd412bfd344 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/.travis.yml @@ -0,0 +1,23 @@ +--- +language: ruby +bundler_args: --without development +before_install: rm Gemfile.lock || true +rvm: + - 1.8.7 + - 1.9.3 + - 2.0.0 +script: bundle exec rake test +env: + - PUPPET_VERSION="~> 2.7.0" + - PUPPET_VERSION="~> 3.1.0" + - PUPPET_VERSION="~> 3.2.0" + - PUPPET_VERSION="~> 3.3.0" + - PUPPET_VERSION="~> 3.4.0" +matrix: + exclude: + - rvm: 2.0.0 + env: PUPPET_VERSION="~> 2.7.0" + - rvm: 2.0.0 + env: PUPPET_VERSION="~> 3.1.0" + - rvm: 1.9.3 + env: PUPPET_VERSION="~> 2.7.0" diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile new file mode 100644 index 00000000000..39ba7f9f63a --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile @@ -0,0 +1,15 @@ +source "http://rubygems.org" + + +gem "rake" +gem "puppet", ENV['PUPPET_VERSION'] || '~> 3.2.0' +gem "puppet-lint" +gem "rspec-puppet", '~> 1.0.0' +gem "puppetlabs_spec_helper" +gem "rspec-system-puppet" +gem "vagrant-wrapper" +gem "puppet-syntax" + +group :development do + gem "puppet-blacksmith" +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile.lock b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile.lock new file mode 100644 index 00000000000..d719aa97918 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Gemfile.lock @@ -0,0 +1,94 @@ +GEM + remote: http://rubygems.org/ + specs: + builder (3.2.2) + diff-lcs (1.2.5) + excon (0.31.0) + facter (1.7.5) + fog (1.20.0) + builder + excon (~> 0.31.0) + formatador (~> 0.2.0) + mime-types + multi_json (~> 1.0) + net-scp (~> 1.1) + net-ssh (>= 2.1.3) + nokogiri (>= 1.5.11) + formatador (0.2.4) + hiera (1.3.2) + json_pure + json_pure (1.8.1) + kwalify (0.7.2) + metaclass (0.0.4) + mime-types (1.25.1) + mocha (1.0.0) + metaclass (~> 0.0.1) + multi_json (1.8.4) + net-scp (1.1.2) + net-ssh (>= 2.6.5) + net-ssh (2.8.0) + nokogiri (1.5.11) + puppet (3.2.4) + facter (~> 1.6) + hiera (~> 1.0) + rgen (~> 0.6.5) + puppet-blacksmith (2.0.2) + nokogiri + puppet (>= 2.7.16) + rest-client + puppet-lint (0.3.2) + puppet-syntax (1.1.0) + puppet (>= 2.7.0) + rake + puppetlabs_spec_helper (0.4.1) + mocha (>= 0.10.5) + rake + rspec (>= 2.9.0) + rspec-puppet (>= 0.1.1) + rake (10.1.1) + rbvmomi (1.8.1) + builder + nokogiri (>= 1.4.1) + trollop + rest-client (1.6.7) + mime-types (>= 1.16) + rgen (0.6.6) + rspec (2.14.1) + rspec-core (~> 2.14.0) + rspec-expectations (~> 2.14.0) + rspec-mocks (~> 2.14.0) + rspec-core (2.14.8) + rspec-expectations (2.14.5) + diff-lcs (>= 1.1.3, < 2.0) + rspec-mocks (2.14.6) + rspec-puppet (1.0.1) + rspec + rspec-system (2.8.0) + fog (~> 1.18) + kwalify (~> 0.7.2) + mime-types (~> 1.16) + net-scp (~> 1.1) + net-ssh (~> 2.7) + nokogiri (~> 1.5.10) + rbvmomi (~> 1.6) + rspec (~> 2.14) + systemu (~> 2.5) + rspec-system-puppet (2.2.1) + rspec-system (~> 2.0) + systemu (2.6.3) + trollop (2.0) + vagrant-wrapper (1.2.1.1) + +PLATFORMS + ruby + +DEPENDENCIES + puppet (~> 3.2.0) + puppet-blacksmith + puppet-lint + puppet-syntax + puppetlabs_spec_helper + rake + rspec-puppet (~> 1.0.0) + rspec-system-puppet + vagrant-wrapper diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/LICENSE b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/LICENSE new file mode 100644 index 00000000000..bf023233a1f --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/LICENSE @@ -0,0 +1,207 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, and + distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by the + copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all other + entities that control, are controlled by, or are under common control with + that entity. For the purposes of this definition, "control" means (i) the + power, direct or indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (ii) ownership of + fifty percent (50%) or more of the outstanding shares, or (iii) beneficial + ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity exercising + permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation source, + and configuration files. + + "Object" form shall mean any form resulting from mechanical transformation + or translation of a Source form, including but not limited to compiled + object code, generated documentation, and conversions to + other media types. + + "Work" shall mean the work of authorship, whether in Source or Object + form, made available under the License, as indicated by a copyright notice + that is included in or attached to the work (an example is provided in the + Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object form, + that is based on (or derived from) the Work and for which the editorial + revisions, annotations, elaborations, or other modifications represent, + as a whole, an original work of authorship. For the purposes of this + License, Derivative Works shall not include works that remain separable + from, or merely link (or bind by name) to the interfaces of, the Work and + Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including the original + version of the Work and any modifications or additions to that Work or + Derivative Works thereof, that is intentionally submitted to Licensor for + inclusion in the Work by the copyright owner or by an individual or + Legal Entity authorized to submit on behalf of the copyright owner. + For the purposes of this definition, "submitted" means any form of + electronic, verbal, or written communication sent to the Licensor or its + representatives, including but not limited to communication on electronic + mailing lists, source code control systems, and issue tracking systems + that are managed by, or on behalf of, the Licensor for the purpose of + discussing and improving the Work, but excluding communication that is + conspicuously marked or otherwise designated in writing by the copyright + owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity on + behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. + + Subject to the terms and conditions of this License, each Contributor + hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable copyright license to reproduce, prepare + Derivative Works of, publicly display, publicly perform, sublicense, + and distribute the Work and such Derivative Works in + Source or Object form. + +3. Grant of Patent License. + + Subject to the terms and conditions of this License, each Contributor + hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, + royalty-free, irrevocable (except as stated in this section) patent + license to make, have made, use, offer to sell, sell, import, and + otherwise transfer the Work, where such license applies only to those + patent claims licensable by such Contributor that are necessarily + infringed by their Contribution(s) alone or by combination of their + Contribution(s) with the Work to which such Contribution(s) was submitted. + If You institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work or a + Contribution incorporated within the Work constitutes direct or + contributory patent infringement, then any patent licenses granted to + You under this License for that Work shall terminate as of the date such + litigation is filed. + +4. Redistribution. + + You may reproduce and distribute copies of the Work or Derivative Works + thereof in any medium, with or without modifications, and in Source or + Object form, provided that You meet the following conditions: + + 1. You must give any other recipients of the Work or Derivative Works a + copy of this License; and + + 2. You must cause any modified files to carry prominent notices stating + that You changed the files; and + + 3. You must retain, in the Source form of any Derivative Works that You + distribute, all copyright, patent, trademark, and attribution notices from + the Source form of the Work, excluding those notices that do not pertain + to any part of the Derivative Works; and + + 4. If the Work includes a "NOTICE" text file as part of its distribution, + then any Derivative Works that You distribute must include a readable copy + of the attribution notices contained within such NOTICE file, excluding + those notices that do not pertain to any part of the Derivative Works, + in at least one of the following places: within a NOTICE text file + distributed as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, within a + display generated by the Derivative Works, if and wherever such + third-party notices normally appear. The contents of the NOTICE file are + for informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative Works that You + distribute, alongside or as an addendum to the NOTICE text from the Work, + provided that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and may + provide additional or different license terms and conditions for use, + reproduction, or distribution of Your modifications, or for any such + Derivative Works as a whole, provided Your use, reproduction, and + distribution of the Work otherwise complies with the conditions + stated in this License. + +5. Submission of Contributions. + + Unless You explicitly state otherwise, any Contribution intentionally + submitted for inclusion in the Work by You to the Licensor shall be under + the terms and conditions of this License, without any additional + terms or conditions. Notwithstanding the above, nothing herein shall + supersede or modify the terms of any separate license agreement you may + have executed with Licensor regarding such Contributions. + +6. Trademarks. + + This License does not grant permission to use the trade names, trademarks, + service marks, or product names of the Licensor, except as required for + reasonable and customary use in describing the origin of the Work and + reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + + Unless required by applicable law or agreed to in writing, Licensor + provides the Work (and each Contributor provides its Contributions) + on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied, including, without limitation, any warranties + or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS + FOR A PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any risks + associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + + In no event and under no legal theory, whether in tort + (including negligence), contract, or otherwise, unless required by + applicable law (such as deliberate and grossly negligent acts) or agreed + to in writing, shall any Contributor be liable to You for damages, + including any direct, indirect, special, incidental, or consequential + damages of any character arising as a result of this License or out of + the use or inability to use the Work (including but not limited to damages + for loss of goodwill, work stoppage, computer failure or malfunction, + or any and all other commercial damages or losses), even if such + Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + + While redistributing the Work or Derivative Works thereof, You may choose + to offer, and charge a fee for, acceptance of support, warranty, + indemnity, or other liability obligations and/or rights consistent with + this License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf of any + other Contributor, and only if You agree to indemnify, defend, and hold + each Contributor harmless for any liability incurred by, or claims + asserted against, such Contributor by reason of your accepting any such + warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + + To apply the Apache License to your work, attach the following boilerplate + notice, with the fields enclosed by brackets "[]" replaced with your own + identifying information. (Don't include the brackets!) The text should be + enclosed in the appropriate comment syntax for the file format. We also + recommend that a file or class name and description of purpose be included + on the same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013 Gareth Rushgrove + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + or implied. See the License for the specific language governing + permissions and limitations under the License. diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Modulefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Modulefile new file mode 100644 index 00000000000..9ca1ef70427 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Modulefile @@ -0,0 +1,10 @@ +name 'garethr-erlang' +version '0.3.0' +source 'git://github.com/garethr/garethr-erlang.git' +author 'Gareth Rushgrove' +summary 'Module for installing erlang from official repos' +description 'Install one of the official erlang packages' +license 'Apache License, Version 2.0' +dependency 'puppetlabs/apt' +dependency 'puppetlabs/stdlib' +dependency 'stahnma/epel' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/README.md b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/README.md new file mode 100644 index 00000000000..a1959740bc6 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/README.md @@ -0,0 +1,28 @@ +Puppet module for installing Erlang from alternative repositories. + +On debian it will use the official repositories +mentioned on the [Erlang +docs](https://www.erlang-solutions.com/downloads/download-erlang-otp). + +On Redhat 5 it'll use an additional EPEL repository hosted by +[Redhat](http://repos.fedorapeople.org/repos/peter/erlang/epel-erlang.repo). + +On Redhat 6 it'll require EPEL. + +On SUSE it'll use the official repos. + +On Archlinux it'll use community repos. + +This module is also available on the [Puppet +Forge](https://forge.puppetlabs.com/garethr/erlang) + +[![Build +Status](https://secure.travis-ci.org/garethr/garethr-erlang.png)](http://travis-ci.org/garethr/garethr-erlang) + +## Usage + +The module includes a single class: + + include 'erlang' + +By default this sets up the repository and installs the erlang package. diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Rakefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Rakefile new file mode 100644 index 00000000000..d45aa3d5741 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/Rakefile @@ -0,0 +1,35 @@ +require 'puppetlabs_spec_helper/rake_tasks' +require 'puppet-lint/tasks/puppet-lint' +require 'puppet-syntax/tasks/puppet-syntax' +require 'rspec-system/rake_task' + +begin + require 'puppet_blacksmith/rake_tasks' +rescue LoadError +end + +PuppetLint.configuration.log_format = "%{path}:%{linenumber}:%{check}:%{KIND}:%{message}" +PuppetLint.configuration.fail_on_warnings = true + +# Forsake support for Puppet 2.6.2 for the benefit of cleaner code. +# http://puppet-lint.com/checks/class_parameter_defaults/ +PuppetLint.configuration.send('disable_class_parameter_defaults') +# http://puppet-lint.com/checks/class_inherits_from_params_class/ +PuppetLint.configuration.send('disable_class_inherits_from_params_class') +# http://puppet-lint.com/checks/80chars/ +PuppetLint.configuration.send("disable_80chars") + +exclude_paths = [ + "pkg/**/*", + "vendor/**/*", + "spec/**/*", +] +PuppetLint.configuration.ignore_paths = exclude_paths +PuppetSyntax.exclude_paths = exclude_paths + +desc "Run syntax, lint, and spec tests." +task :test => [ + :syntax, + :lint, + :spec, +] diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/init.pp new file mode 100644 index 00000000000..045bada9474 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/init.pp @@ -0,0 +1,45 @@ +# == Class: erlang +# +# Module to install an up-to-date version of Erlang from the +# official repositories +# +# === Parameters +# [*version*] +# The package version to install, passed to ensure. +# Defaults to present. +# +class erlang ( + $epel_enable = $erlang::params::epel_enable, + $key_signature = $erlang::params::key_signature, + $local_repo_location = $erlang::params::local_repo_location, + $package_name = $erlang::params::package_name, + $remote_repo_location = $erlang::params::remote_repo_location, + $remote_repo_key_location = $erlang::params::remote_repo_key_location, + $repos = $erlang::params::repos, + $version = 'present', +) inherits erlang::params { + validate_string($version) + + case $::osfamily { + 'Debian' : { + include '::apt' + include '::erlang::repo::apt' + } + 'RedHat' : { + if $epel_enable { + # Include epel as this is a requirement for erlang in RHEL6. + include '::epel' + Class['epel'] -> Package[$package_name] + } + + # This is only needed on RHEL5, RHEL6 has erlang in EPEL. + if $::operatingsystemrelease =~ /^5/ { + include '::erlang::repo::yum' + } + } + default : { + } + } + + package { $package_name: ensure => $version, } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/params.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/params.pp new file mode 100644 index 00000000000..9358326cd94 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/params.pp @@ -0,0 +1,29 @@ +# == Class: erlang::params +# +# Default paramaters setting repository details for different +# operating systems +# +class erlang::params { + $epel_enable = false + + case $::osfamily { + 'Debian' : { + $key_signature = 'D208507CA14F4FCA' + $package_name = 'erlang-nox' + $remote_repo_key_location = 'http://packages.erlang-solutions.com/debian/erlang_solutions.asc' + $remote_repo_location = 'http://packages.erlang-solutions.com/debian' + $repos = 'contrib' + } + 'RedHat', 'SUSE', 'Archlinux' : { + $package_name = 'erlang' + + if $::operatingsystemrelease =~ /^5/ { + $local_repo_location = '/etc/yum.repos.d/epel-erlang.repo' + $remote_repo_location = 'http://repos.fedorapeople.org/repos/peter/erlang/epel-erlang.repo' + } + } + default : { + fail("The ${module_name} module is not supported on an ${::osfamily} based system.") + } + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/apt.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/apt.pp new file mode 100644 index 00000000000..dc5dbc9c4fb --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/apt.pp @@ -0,0 +1,41 @@ +# == Class: erlang::repo::apt +# +# Install an apt package repository containing Erlang. +# All parameters have sane default values in erlang::params. +# +# === Parameters +# [*key_signature*] +# The signature for the key used to sign packages in the repository. +# +# [*package_name*] +# Name of the Erlang package in the specified repository. +# +# [*remote_repo_key_location*] +# URL of the public key for the remote repository. +# +# [*remote_repo_location*] +# URL of the remote debian repository. +# +# [*repos*] +# Which of the standard repositories to install from the +# remote repo. For instance main, contrib, restricted. +# +class erlang::repo::apt( + $key_signature = $erlang::key_signature, + $package_name = $erlang::package_name, + $remote_repo_key_location = $erlang::remote_repo_key_location, + $remote_repo_location = $erlang::remote_repo_location, + $repos = $erlang::repos, +) { + + Class['erlang::repo::apt'] -> Package<| title == $package_name |> + + apt::source { 'erlang': + include_src => false, + key => $key_signature, + key_source => $remote_repo_key_location, + location => $remote_repo_location, + repos => $repos, + } + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/yum.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/yum.pp new file mode 100644 index 00000000000..702e65220b9 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/manifests/repo/yum.pp @@ -0,0 +1,30 @@ +# == Class: erlang::repo::yum +# +# Install a yum package repository containing Erlang. +# All parameters have sane default values in erlang::params. +# +# === Parameters +# [*local_repo_location*] +# File system location to store the repository details +# +# [*package_name*] +# Name of the Erlang package in the specified repository +# +# [*remote_repo_location*] +# URL of the remote repository +# +class erlang::repo::yum ( + $local_repo_location = $erlang::local_repo_location, + $package_name = $erlang::package_name, + $remote_repo_location = $erlang::remote_repo_location, +) inherits erlang { + + Class['erlang::repo::yum'] -> Package<| title == $package_name |> + + exec { 'erlang-repo-download': + command => "curl -o ${local_repo_location} ${remote_repo_location}", + path => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', + creates => $local_repo_location, + } + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/classes/erlang_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/classes/erlang_spec.rb new file mode 100644 index 00000000000..8708eb1afe8 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/classes/erlang_spec.rb @@ -0,0 +1,138 @@ +require 'spec_helper' + +describe 'erlang', :type => :class do + + + context 'on Debian' do + let(:facts) { { + :osfamily => 'Debian', + :lsbdistid => 'debian', + :lsbdistcodename => 'squeeze' + }} + + context 'with no parameters' do + it { should compile.with_all_deps } + it { should contain_package('erlang-nox').with_ensure('present') } + it { should contain_apt__source('erlang').with( + 'key_source' => 'http://packages.erlang-solutions.com/debian/erlang_solutions.asc', + 'key' => 'D208507CA14F4FCA' + ) } + end + + context 'with a custom version' do + let(:params) { {'version' => 'absent' } } + it { should contain_package('erlang-nox').with_ensure('absent') } + end + + context 'with a custom package name' do + let(:params) { {'package_name' => 'not-erlang' } } + it { should contain_package('not-erlang').with_ensure('present') } + end + + context 'with custom repository details' do + let(:params) { { + 'key_signature' => '1234ABCD', + 'repos' => 'main', + 'remote_repo_location' => 'http://example.com/debian', + 'remote_repo_key_location' => 'http://example.com/debian/key.asc', + } } + it { should contain_apt__source('erlang').with( + 'location' => 'http://example.com/debian', + 'key_source' => 'http://example.com/debian/key.asc', + 'key' => '1234ABCD', + 'repos' => 'main' + ) } + end + + end + + context 'on RedHat 5' do + let(:facts) { {:osfamily => 'RedHat', :operatingsystemrelease => '5.9' } } + + context "epel enabled" do + let(:params) {{ :epel_enable => true }} + it { should contain_class('epel') } + end + + context "epel disabled" do + let(:params) {{ :epel_enable => false }} + it { should_not contain_class('epel') } + end + + context 'with no parameters' do + it { should contain_package('erlang').with_ensure('present') } + it { should contain_exec('erlang-repo-download').with( + 'command' => 'curl -o /etc/yum.repos.d/epel-erlang.repo http://repos.fedorapeople.org/repos/peter/erlang/epel-erlang.repo', + 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin' + ) + } + end + + context 'with a custom repository' do + let(:params) { { + 'local_repo_location' => '/tmp/yum.repos.d/tmp.repo', + 'remote_repo_location' => 'http://example.com/fake.repo', + } } + + it { should contain_exec('erlang-repo-download').with( + 'command' => 'curl -o /tmp/yum.repos.d/tmp.repo http://example.com/fake.repo' + ) + } + end + + context 'with a custom version' do + let(:params) { {'version' => 'absent' } } + it { should contain_package('erlang').with_ensure('absent') } + end + end + + context 'on RedHat 6' do + let(:facts) { {:osfamily => 'RedHat', :operatingsystemrelease => '6.4' } } + + context "epel enabled" do + let(:params) {{ :epel_enable => true }} + it { should contain_class('epel') } + end + + context "epel disabled" do + let(:params) {{ :epel_enable => false }} + it { should_not contain_class('epel') } + end + + context 'with no parameters' do + it { should contain_package('erlang').with_ensure('present') } + end + + context 'with a custom version' do + let(:params) { {'version' => 'absent' } } + it { should contain_package('erlang').with_ensure('absent') } + end + end + + context 'on SUSE' do + let(:facts) {{ :osfamily => 'SUSE', }} + + context 'with no parameters' do + it { should contain_package('erlang').with_ensure('present') } + end + + context 'with a custom version' do + let(:params) { {'version' => 'absent' } } + it { should contain_package('erlang').with_ensure('absent') } + end + end + + context 'on Archlinux' do + let(:facts) {{ :osfamily => 'Archlinux', }} + + context 'with no parameters' do + it { should contain_package('erlang').with_ensure('present') } + end + + context 'with a custom version' do + let(:params) { {'version' => 'absent' } } + it { should contain_package('erlang').with_ensure('absent') } + end + end + +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper.rb new file mode 100644 index 00000000000..2c6f56649ae --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper.rb @@ -0,0 +1 @@ +require 'puppetlabs_spec_helper/module_spec_helper' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper_system.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper_system.rb new file mode 100644 index 00000000000..5c370248560 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/spec_helper_system.rb @@ -0,0 +1,17 @@ +require 'rspec-system/spec_helper' +require 'rspec-system-puppet/helpers' + +include RSpecSystemPuppet::Helpers + +RSpec.configure do |c| + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + c.tty = true + c.include RSpecSystemPuppet::Helpers + + c.before :suite do + puppet_install + puppet_module_install(:source => proj_root, :module_name => 'erlang') + shell('puppet module install puppetlabs-apt') + shell('puppet module install stahnma-epel') + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/system/erlang_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/system/erlang_spec.rb new file mode 100644 index 00000000000..4d5772fa59a --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/erlang/spec/system/erlang_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper_system' + +describe 'The erlang puppet module' do + it 'should run without errors' do + pp = <<-EOS + class { 'erlang': + epel_enable => true + } + EOS + + puppet_apply(pp) do |r| + r.exit_code.should == 2 + r.refresh + r.exit_code.should be_zero + end + end + + it 'should install the erl binary into /usr/bin' do + shell 'which erl' do |r| + r.stdout.should =~ /\/usr\/bin\/erl/ + r.stderr.should be_empty + r.exit_code.should be_zero + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/hash_key_true.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/hash_key_true.rb new file mode 100644 index 00000000000..90401172eb7 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/hash_key_true.rb @@ -0,0 +1,46 @@ +# +# hash_key_true.rb +# + +module Puppet::Parser::Functions + + newfunction(:hash_key_true, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + + Returns true if the key within hash is truthy + ENDHEREDOC + + unless args.length == 2 + raise Puppet::ParseError, ("hash_key_true(): wrong number of arguments (#{args.length}; must be 2)") + end + + arr = args[0] + key = args[1] + + unless arr.is_a?(Hash) + return false + end + + unless arr.has_key?(key) + return false + end + + if arr[key].nil? + return false + end + + if arr[key] == false + return false + end + + if arr[key] == 'false' + return false + end + + if arr[key].empty? + return false + end + + return true + + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/value_true.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/value_true.rb new file mode 100644 index 00000000000..d50c2d8304b --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/lib/puppet/parser/functions/value_true.rb @@ -0,0 +1,45 @@ +# +# value_true.rb +# + +module Puppet::Parser::Functions + + newfunction(:value_true, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + + Returns true if value is truthy + ENDHEREDOC + + unless args.length == 1 + raise Puppet::ParseError, ("value_true(): wrong number of arguments (#{args.length}; must be 1)") + end + + value = args[0] + + if value.nil? + return false + end + + if value == false + return false + end + + if value == 0 + return false + end + + if value == '0' + return false + end + + if value == 'false' + return false + end + + if value.empty? + return false + end + + return true + + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/hhvm.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/hhvm.pp index 90083232cdc..7a35d19efe9 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/hhvm.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/hhvm.pp @@ -44,7 +44,11 @@ class puphpet::hhvm( 'deb http://security.debian.org/ wheezy/updates main', 'deb-src http://security.debian.org/ wheezy/updates main', 'deb http://http.us.debian.org/debian wheezy-updates main', - 'deb-src http://http.us.debian.org/debian wheezy-updates main' + 'deb-src http://http.us.debian.org/debian wheezy-updates main', + 'deb http://http.debian.net/debian wheezy main', + 'deb-src http://http.debian.net/debian wheezy main', + 'deb http://http.debian.net/debian wheezy-updates main', + 'deb-src http://http.debian.net/debian wheezy-updates main', ] each( $deb_srcs ) |$value| { @@ -69,17 +73,39 @@ class puphpet::hhvm( } } 'centos': { + $jemalloc_url = 'http://files.puphpet.com/centos6/jemalloc-3.6.0-1.el6.x86_64.rpm' + $jemalloc_download_location = '/.puphpet-stuff/jemalloc-3.6.0-1.el6.x86_64.rpm' + + $require = defined(Class['my_fw::post']) ? { + true => Class['my_fw::post'], + default => [], + } + + exec { "download jemalloc to ${download_location}": + creates => $download_location, + command => "wget --quiet --tries=5 --connect-timeout=10 -O '${jemalloc_download_location}' '${jemalloc_url}'", + timeout => 30, + path => '/usr/bin', + require => $require + } + + package { 'jemalloc': + ensure => latest, + provider => yum, + source => $download_location, + require => Exec["download jemalloc to ${download_location}"], + } + yum::managed_yumrepo { 'hop5': descr => 'hop5 repository', baseurl => 'http://www.hop5.in/yum/el6/', gpgkey => 'file:///etc/pki/rpm-gpg/RPM-GPG-KEY-HOP5', enabled => 1, gpgcheck => 0, - priority => 1 + priority => 1, } } } - if $real_webserver == 'apache2' { if ! defined(Class['apache::mod::mime']) { class { 'apache::mod::mime': } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/params.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/params.pp index 1a998e9271b..e266f862cdb 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/params.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/params.pp @@ -53,9 +53,14 @@ class puphpet::params { 'Redhat' => 'php-cgi' } + $nginx_default_conf_location = $::osfamily ? { + 'Debian' => '/etc/nginx/conf.d/default.conf', + 'Redhat' => '/etc/nginx/conf.d/default.conf' + } + $nginx_webroot_location = $::osfamily ? { 'Debian' => '/var/www/html', - 'Redhat' => '/usr/share/nginx/html' + 'Redhat' => '/var/www/html' } $mariadb_package_client_name = $::osfamily ? { diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pear.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pear.pp index 4582e67a17a..f570dcd4fc4 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pear.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pear.pp @@ -3,7 +3,8 @@ */ define puphpet::php::pear ( - $service_autorestart + $service_name = '', + $service_autorestart, ){ $package = { @@ -15,7 +16,9 @@ define puphpet::php::pear ( 'pear_command_packaging' => 'alpha', 'pear_frontend_gtk2' => false, 'php_beautifier' => 'beta', + 'php_parser' => 'alpha', 'php_parser_docblockparser' => 'alpha', + 'soap' => 'beta', 'testing_selenium' => 'beta', 'versioncontrol_git' => 'alpha', 'versioncontrol_svn' => 'alpha', @@ -38,7 +41,8 @@ define puphpet::php::pear ( ::php::pear::module { $name: use_package => false, preferred_state => $preferred_state, - service_autorestart => $php_webserver_restart, + service => $service_name, + service_autorestart => $service_autorestart, } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pecl.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pecl.pp index 2dd2b817fec..dfa04232f42 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pecl.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/php/pecl.pp @@ -16,7 +16,10 @@ define puphpet::php::pecl ( $pecl = $::osfamily ? { 'Debian' => { - # + 'mongo' => $::lsbdistcodename ? { + 'precise' => 'mongo', + default => false, + }, }, 'Redhat' => { # @@ -63,24 +66,34 @@ define puphpet::php::pecl ( } } + $auto_answer_hash = { + 'mongo' => 'no\n' + } + $downcase_name = downcase($name) - if has_key($ignore, $downcase_name) { + if has_key($auto_answer_hash, $downcase_name) { + $auto_answer = $auto_answer_hash[$downcase_name] + } else { + $auto_answer = '\\n' + } + + if has_key($ignore, $downcase_name) and $ignore[$downcase_name] { $pecl_name = $pecl[$downcase_name] $package_name = false $preferred_state = 'stable' } - elsif has_key($pecl, $downcase_name) { - $pecl_name = false + elsif has_key($pecl, $downcase_name) and $pecl[$downcase_name] { + $pecl_name = $pecl[$downcase_name] $package_name = false - $preferred_state = false + $preferred_state = 'stable' } elsif has_key($pecl_beta, $downcase_name) and $pecl_beta[$downcase_name] { $pecl_name = $pecl_beta[$downcase_name] $package_name = false $preferred_state = 'beta' } - elsif has_key($package, $downcase_name) { + elsif has_key($package, $downcase_name) and $package[$downcase_name] { $pecl_name = false $package_name = $package[$downcase_name] } @@ -93,6 +106,7 @@ define puphpet::php::pecl ( ::php::pecl::module { $pecl_name: use_package => false, preferred_state => $preferred_state, + auto_answer => $auto_answer, service_autorestart => $service_autorestart, } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/python/pip.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/python/pip.pp new file mode 100644 index 00000000000..14b13fe08c6 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/python/pip.pp @@ -0,0 +1,22 @@ +class puphpet::python::pip { + + Exec { path => [ '/usr/bin/', '/usr/local/bin', '/bin', '/usr/local/sbin', '/usr/sbin', '/sbin' ] } + + if ! defined(Package['python-setuptools']) { + package { 'python-setuptools': } + } + + exec { 'easy_install pip': + unless => 'which pip', + require => Package['python-setuptools'], + } + + if $::osfamily == 'RedHat' { + exec { 'rhel pip_provider_name_fix': + command => 'alternatives --install /usr/bin/pip-python pip-python /usr/bin/pip 1', + subscribe => Exec['easy_install pip'], + unless => 'which pip-python', + } + } + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/supervisord.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/supervisord.pp new file mode 100644 index 00000000000..a13df08b30b --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/puphpet/manifests/supervisord.pp @@ -0,0 +1,18 @@ +# This depends on +# ajcrowe/supervisord: https://github.com/ajcrowe/puppet-supervisord + +class puphpet::supervisord { + + if ! defined(Class['::supervisord']) { + class{ 'puphpet::python::pip': } + + class { '::supervisord': + install_pip => false, + require => [ + Class['::my_fw::post'], + Class['puphpet::python::pip'], + ], + } + } + +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/README.md b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/README.md index c6750445516..d956bdedcff 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/README.md +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/README.md @@ -111,6 +111,23 @@ class { 'rabbitmq': } ``` +**NOTE:** If you are using a version of RabbitMQ less than 3.0, +you still need to use `x-ha-policy: all` in your client +applications for any particular queue to take advantage of H/A via +mirrored queues. + +If you are using a version of RabbitMQ >= 3.0 You should set the +'config_mirrored_queues' parameter if you plan +on using RabbitMQ Mirrored Queues within your cluster: + +```puppet +class { 'rabbitmq': + config_cluster => true, + config_mirrored_queues => true, + cluster_nodes => ['rabbit1', 'rabbit2'], +} +``` + ##Reference ##Classes @@ -234,6 +251,15 @@ Determines if the service is managed. The name of the service to manage. +####`ssl` + +Configures the service for using SSL. + +####`ssl_only` + +Configures the service to only use SSL. No cleartext TCP listeners will be created. +Requires that ssl => true also. + ####`stomp_port` The port to use for Stomp. @@ -262,6 +288,16 @@ rabbitmq_user { 'dan': password => 'bar', } ``` +Optional parameter tags will set further rabbitmq tags like monitoring, policymaker, etc. +To set the administrator tag use admin-flag. +```puppet +rabbitmq_user { 'dan': + admin => true, + password => 'bar', + tags => ['monitoring', 'tag1'], +} +``` + ### rabbitmq\_vhost @@ -317,8 +353,8 @@ The module has been tested on: Testing on other platforms has been light and cannot be guaranteed. -### RedHat module dependencies -To have a suitable erlang version installed on RedHat systems, +### Module dependencies +To have a suitable erlang version installed on RedHat and Debian systems, you have to install another puppet module from http://forge.puppetlabs.com/garethr/erlang with: puppet module install garethr-erlang @@ -326,9 +362,18 @@ you have to install another puppet module from http://forge.puppetlabs.com/garet This module handles the packages for erlang. To use the module, add the following snippet to your site.pp or an appropriate profile class: +For RedHat systems: + include 'erlang' class { 'erlang': epel_enable => true} +For Debian systems: + + include 'erlang' + package { 'erlang-base': + ensure => 'latest', + } + ##Development Puppet Labs modules on the Puppet Forge are open projects, and community diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/files/plugins/amqp_client-2.3.1.ez b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/files/plugins/amqp_client-2.3.1.ez index 6ef6d4ff148..125a89a7b79 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/files/plugins/amqp_client-2.3.1.ez and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/files/plugins/amqp_client-2.3.1.ez differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_exchange/rabbitmqadmin.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_exchange/rabbitmqadmin.rb index fcc3764fdd8..8e0d6ab862d 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_exchange/rabbitmqadmin.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_exchange/rabbitmqadmin.rb @@ -2,7 +2,9 @@ require 'puppet' Puppet::Type.type(:rabbitmq_exchange).provide(:rabbitmqadmin) do commands :rabbitmqctl => '/usr/sbin/rabbitmqctl' - commands :rabbitmqadmin => '/usr/local/bin/rabbitmqadmin' + has_command(:rabbitmqadmin, '/usr/local/bin/rabbitmqadmin') do + environment( { 'HOME' => '' }) + end defaultfor :feature => :posix def should_vhost diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_plugin/rabbitmqplugins.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_plugin/rabbitmqplugins.rb index e416cbe02b3..eefc9fb2541 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_plugin/rabbitmqplugins.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_plugin/rabbitmqplugins.rb @@ -1,10 +1,20 @@ Puppet::Type.type(:rabbitmq_plugin).provide(:rabbitmqplugins) do if Puppet::PUPPETVERSION.to_f < 3 - commands :rabbitmqplugins => 'rabbitmq-plugins' + if Facter.value(:osfamily) == 'RedHat' + commands :rabbitmqplugins => '/usr/lib/rabbitmq/bin/rabbitmq-plugins' + else + commands :rabbitmqplugins => 'rabbitmq-plugins' + end else - has_command(:rabbitmqplugins, 'rabbitmq-plugins') do - environment :HOME => "/tmp" + if Facter.value(:osfamily) == 'RedHat' + has_command(:rabbitmqplugins, '/usr/lib/rabbitmq/bin/rabbitmq-plugins') do + environment :HOME => "/tmp" + end + else + has_command(:rabbitmqplugins, 'rabbitmq-plugins') do + environment :HOME => "/tmp" + end end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_user/rabbitmqctl.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_user/rabbitmqctl.rb index 9cb2e41c293..ef284bdcdc6 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_user/rabbitmqctl.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/provider/rabbitmq_user/rabbitmqctl.rb @@ -27,6 +27,9 @@ Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do if resource[:admin] == :true make_user_admin() end + if !resource[:tags].nil? + set_user_tags(resource[:tags]) + end end def destroy @@ -39,8 +42,18 @@ Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do end end - # def password - # def password=() + + def tags + get_user_tags.entries.sort + end + + + def tags=(tags) + if ! tags.nil? + set_user_tags(tags) + end + end + def admin if usertags = get_user_tags (:true if usertags.include?('administrator')) || :false @@ -49,7 +62,6 @@ Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do end end - def admin=(state) if state == :true make_user_admin() @@ -60,6 +72,16 @@ Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do end end + def set_user_tags(tags) + is_admin = get_user_tags().member?("administrator") \ + || resource[:admin] == :true + usertags = Set.new(tags) + if is_admin + usertags.add("administrator") + end + rabbitmqctl('set_user_tags', resource[:name], usertags.entries.sort) + end + def make_user_admin usertags = get_user_tags usertags.add('administrator') @@ -73,5 +95,4 @@ Puppet::Type.type(:rabbitmq_user).provide(:rabbitmqctl) do end.compact.first Set.new(match[1].split(/, /)) if match end - end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/type/rabbitmq_user.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/type/rabbitmq_user.rb index 642710d1c07..be5219d5c90 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/type/rabbitmq_user.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/lib/puppet/type/rabbitmq_user.rb @@ -33,6 +33,10 @@ Puppet::Type.newtype(:rabbitmq_user) do defaultto :false end + newproperty(:tags, :array_matching => :all) do + desc 'additional tags for the user' + end + validate do if self[:ensure] == :present and ! self[:password] raise ArgumentError, 'must set password when creating user' unless self[:password] diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/config.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/config.pp index 96877f6a631..8894280f6de 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/config.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/config.pp @@ -17,11 +17,14 @@ class rabbitmq::config { $port = $rabbitmq::port $service_name = $rabbitmq::service_name $ssl = $rabbitmq::ssl + $ssl_only = $rabbitmq::ssl_only $ssl_cacert = $rabbitmq::ssl_cacert $ssl_cert = $rabbitmq::ssl_cert $ssl_key = $rabbitmq::ssl_key $ssl_management_port = $rabbitmq::ssl_management_port $ssl_stomp_port = $rabbitmq::ssl_stomp_port + $ssl_verify = $rabbitmq::ssl_verify + $ssl_fail_if_no_peer_cert = $rabbitmq::ssl_fail_if_no_peer_cert $stomp_port = $rabbitmq::stomp_port $wipe_db_on_cookie_change = $rabbitmq::wipe_db_on_cookie_change $config_variables = $rabbitmq::config_variables @@ -115,3 +118,4 @@ class rabbitmq::config { } + diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/init.pp index 6c14f0097d6..c96128a792e 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/init.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/init.pp @@ -6,6 +6,7 @@ class rabbitmq( $cluster_nodes = $rabbitmq::params::cluster_nodes, $config = $rabbitmq::params::config, $config_cluster = $rabbitmq::params::config_cluster, + $config_mirrored_queues = $rabbitmq::params::config_mirrored_queues, $config_path = $rabbitmq::params::config_path, $config_stomp = $rabbitmq::params::config_stomp, $default_user = $rabbitmq::params::default_user, @@ -29,6 +30,7 @@ class rabbitmq( $service_manage = $rabbitmq::params::service_manage, $service_name = $rabbitmq::params::service_name, $ssl = $rabbitmq::params::ssl, + $ssl_only = $rabbitmq::params::ssl_only, $ssl_cacert = $rabbitmq::params::ssl_cacert, $ssl_cert = $rabbitmq::params::ssl_cert, $ssl_key = $rabbitmq::params::ssl_key, @@ -59,7 +61,6 @@ class rabbitmq( validate_string($package_gpg_key) validate_string($package_name) validate_string($package_provider) - validate_string($package_source) validate_bool($manage_repos) validate_re($version, '^\d+\.\d+\.\d+(-\d+)*$') # Allow 3 digits and optional -n postfix. # Validate config parameters. @@ -69,6 +70,7 @@ class rabbitmq( validate_string($config) validate_absolute_path($config_path) validate_bool($config_cluster) + validate_bool($config_mirrored_queues) validate_bool($config_stomp) validate_string($default_user) validate_string($default_pass) @@ -87,6 +89,7 @@ class rabbitmq( validate_bool($service_manage) validate_string($service_name) validate_bool($ssl) + validate_bool($ssl_only) validate_string($ssl_cacert) validate_string($ssl_cert) validate_string($ssl_key) @@ -105,6 +108,10 @@ class rabbitmq( validate_hash($config_variables) validate_hash($config_kernel_variables) + if $ssl_only and ! $ssl { + fail('$ssl_only => true requires that $ssl => true') + } + include '::rabbitmq::install' include '::rabbitmq::config' include '::rabbitmq::service' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/management.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/management.pp index 481a7b4f931..078e9a95f00 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/management.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/management.pp @@ -10,4 +10,10 @@ class rabbitmq::management { } } + if $rabbitmq::config_mirrored_queues { + rabbitmq::policy { 'ha-all': + pattern => '.*', + definition => '{"ha-mode":"all","ha-sync-mode":"automatic"}' + } + } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/params.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/params.pp index 9018bb7b244..63e2e491ee1 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/params.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/params.pp @@ -61,6 +61,7 @@ class rabbitmq::params { $cluster_nodes = [] $config = 'rabbitmq/rabbitmq.config.erb' $config_cluster = false + $config_mirrored_queues = false $config_path = '/etc/rabbitmq/rabbitmq.config' $config_stomp = false $default_user = 'guest' @@ -73,6 +74,7 @@ class rabbitmq::params { $plugin_dir = "/usr/lib/rabbitmq/lib/rabbitmq_server-${version}/plugins" $port = '5672' $ssl = false + $ssl_only = false $ssl_cacert = 'UNSET' $ssl_cert = 'UNSET' $ssl_key = 'UNSET' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/policy.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/policy.pp new file mode 100644 index 00000000000..204fb36a9cf --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/policy.pp @@ -0,0 +1,15 @@ +define rabbitmq::policy ( + $pattern, + $definition, + $vhost = '/', + $priority = 0, +) { + + exec { "rabbitmq policy: ${title}": + command => "rabbitmqctl set_policy -p ${vhost} '${name}' '${pattern}' '${definition}' ${priority}", + unless => "rabbitmqctl list_policies | grep -qE '^${vhost}\\s+${name}\\s+${pattern}\\s+${definition}\\s+${priority}$'", + path => ['/bin','/sbin','/usr/bin','/usr/sbin'], + require => Class['rabbitmq::service'], + before => Anchor['rabbitmq::end'] + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/server.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/server.pp index 495ea2f2dfc..8ad26cb5bb6 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/server.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/manifests/server.pp @@ -66,7 +66,7 @@ class rabbitmq::server( } if $config_mirrored_queues != undef { - warning('The $config_mirrored_queues parameter is deprecated; it does not affect anything') + warning('The $config_mirrored_queues parameter is deprecated in this class, use the rabbitmq class') } anchor {'before::rabbimq::class': diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/classes/rabbitmq_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/classes/rabbitmq_spec.rb index 3e577843e8a..ff93fd4e3fc 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/classes/rabbitmq_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/classes/rabbitmq_spec.rb @@ -20,7 +20,7 @@ describe 'rabbitmq' do let(:facts) {{ :osfamily => 'Debian' }} it 'should add a repo with defaults values' do contain_file('/etc/apt/sources.list.d/rabbitmq.list')\ - .with_content(/deb http\:\/\/www\.rabbitmq.com\/debian\/ testing main/) + .with_content(%r|deb http\://www\.rabbitmq.com/debian/ testing main|) end end @@ -32,7 +32,7 @@ describe 'rabbitmq' do }} it 'should add a repo with custom new values' do contain_file('/etc/apt/sources.list.d/rabbitmq.list')\ - .with_content(/deb http\:\/\/www\.foorepo.com\/debian\/ unstable main/) + .with_content(%r|deb http\://www\.foorepo.com/debian/ unstable main|) end end end @@ -275,6 +275,30 @@ describe 'rabbitmq' do end end + describe 'configuring ldap authentication' do + let :params do + { :config_stomp => false, + :ldap_auth => true, + :ldap_server => 'ldap.example.com', + :ldap_user_dn_pattern => 'ou=users,dc=example,dc=com', + :ldap_use_ssl => false, + :ldap_port => '389', + :ldap_log => true + } + end + + it { should contain_rabbitmq_plugin('rabbitmq_auth_backend_ldap') } + + it 'should contain ldap parameters' do + verify_contents(subject, 'rabbitmq.config', + ['[', ' {rabbit, [', ' {auth_backends, [rabbit_auth_backend_internal, rabbit_auth_backend_ldap]},', ' ]}', + ' {rabbitmq_auth_backend_ldap, [', ' {other_bind, anon},', + ' {servers, ["ldap.example.com"]},', + ' {user_dn_pattern, "ou=users,dc=example,dc=com"},', ' {use_ssl, false},', + ' {port, 389},', ' {log, true}']) + end + end + describe 'default_user and default_pass set' do let(:params) {{ :default_user => 'foo', :default_pass => 'bar' }} it 'should set default_user and default_pass to specified values' do @@ -295,10 +319,31 @@ describe 'rabbitmq' do it 'should set ssl options to specified values' do contain_file('rabbitmq.config').with({ - 'content' => /ssl_listeners, \[3141\].* - ssl_options, \[{cacertfile,"\/path\/to\/cacert".* - certfile="\/path\/to\/cert".* - keyfile,"\/path\/to\/key/, + 'content' => %r|ssl_listeners, \[3141\].* + ssl_options, \[{cacertfile,"/path/to/cacert".* + certfile="/path/to/cert".* + keyfile,"/path/to/key|, + }) + end + end + + describe 'ssl options with ssl_only' do + let(:params) { + { :ssl => true, + :ssl_only => true, + :ssl_management_port => 3141, + :ssl_cacert => '/path/to/cacert', + :ssl_cert => '/path/to/cert', + :ssl_key => '/path/to/key' + } } + + it 'should set ssl options to specified values' do + contain_file('rabbitmq.config').with({ + 'content' => %r|tcp_listeners, \[\].* + ssl_listeners, \[3141\].* + ssl_options, \[{cacertfile,"/path/to/cacert".* + certfile="/path/to/cert".* + keyfile,"/path/to/key|, }) end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/unit/puppet/provider/rabbitmq_user/rabbitmqctl_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/unit/puppet/provider/rabbitmq_user/rabbitmqctl_spec.rb index ea4233cba13..2c13b886a8c 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/unit/puppet/provider/rabbitmq_user/rabbitmqctl_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/spec/unit/puppet/provider/rabbitmq_user/rabbitmqctl_spec.rb @@ -147,4 +147,90 @@ EOT @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ['bar','baz'].sort) @provider.admin=:false end + + it 'should clear all tags on existing user' do + @provider.expects(:rabbitmqctl).with('list_users').returns <<-EOT +Listing users ... +one [administrator] +foo [tag1,tag2] +icinga [monitoring] +kitchen [] +kitchen2 [abc, def, ghi] +...done. +EOT + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', []) + @provider.tags=[] + end + + it 'should set multiple tags' do + @provider.expects(:rabbitmqctl).with('list_users').returns <<-EOT +Listing users ... +one [administrator] +foo [] +icinga [monitoring] +kitchen [] +kitchen2 [abc, def, ghi] +...done. +EOT + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ['tag1','tag2']) + @provider.tags=['tag1','tag2'] + end + + it 'should clear tags while keep admin tag' do + @resource[:admin] = true + @provider.expects(:rabbitmqctl).with('list_users').returns <<-EOT +Listing users ... +one [administrator] +foo [administrator, tag1, tag2] +icinga [monitoring] +kitchen [] +kitchen2 [abc, def, ghi] +...done. +EOT + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ["administrator"]) + @provider.tags=[] + end + + it 'should change tags while keep admin tag' do + @resource[:admin] = true + @provider.expects(:rabbitmqctl).with('list_users').returns <<-EOT +Listing users ... +one [administrator] +foo [administrator, tag1, tag2] +icinga [monitoring] +kitchen [] +kitchen2 [abc, def, ghi] +...done. +EOT + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ["administrator","tag1","tag3","tag7"]) + @provider.tags=['tag1','tag7','tag3'] + end + + it 'should create user with tags and without admin' do + @resource[:tags] = [ "tag1", "tag2" ] + @provider.expects(:rabbitmqctl).with('add_user', 'foo', 'bar') + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ["tag1","tag2"]) + @provider.expects(:rabbitmqctl).with('list_users').returns <<-EOT +Listing users ... +foo [] +...done. +EOT + @provider.create + end + + it 'should create user with tags and with admin' do + @resource[:tags] = [ "tag1", "tag2" ] + @resource[:admin] = true + @provider.expects(:rabbitmqctl).with('add_user', 'foo', 'bar') + @provider.expects(:rabbitmqctl).with('list_users').twice.returns <<-EOT +Listing users ... +foo [] +...done. +EOT + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ["administrator"]) + @provider.expects(:rabbitmqctl).with('set_user_tags', 'foo', ["administrator","tag1","tag2"]) + @provider.create + end + + end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/templates/rabbitmq.config.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/templates/rabbitmq.config.erb index 766192dfdac..2d7f81bf21d 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/templates/rabbitmq.config.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/rabbitmq/templates/rabbitmq.config.erb @@ -9,7 +9,10 @@ {cluster_nodes, {[<%= @r_cluster_nodes.map { |n| "\'rabbit@#{n}\'" }.join(', ') %>], <%= @cluster_node_type %>}}, {cluster_partition_handling, <%= @cluster_partition_handling %>}, <% end -%> -<%- if @ssl %> +<%- if @ssl_only -%> + {tcp_listeners, []}, +<%- end -%> +<%- if @ssl -%> {ssl_listeners, [<%= @ssl_management_port %>]}, {ssl_options, [{cacertfile,"<%= @ssl_cacert %>"}, {certfile,"<%= @ssl_cert %>"}, @@ -37,6 +40,7 @@ {ssl_listeners, [<%= @ssl_stomp_port %>]} <%- end -%> ]} +<% end -%> <%- if @ldap_auth -%>, % Configure the LDAP authentication plugin {rabbitmq_auth_backend_ldap, [ @@ -47,7 +51,6 @@ {port, <%= @ldap_port %>}, {log, <%= @ldap_log %>} ]} -<% end -%> <%- end -%> ]. % EOF diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/Modulefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/Modulefile new file mode 100644 index 00000000000..19228ff3dbb --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/Modulefile @@ -0,0 +1,13 @@ +name 'puppetlabs-sqlite' +version '0.0.1' +source 'https://github.com/puppetlabs/puppetlabs-sqlite/' +author 'puppetlabs' +license 'Apache' +summary 'Manage a sqlite installation and databases' +description 'This module provides a sqlite class to manage +the installation of sqlite on a node. It also provides +a sqlite::db defined type to manage databases on a system' +project_page 'http://projects.puppetlabs.com/projects/modules/issues' + +## Add dependencies, if any: +# dependency 'username/name', '>= 1.2.0' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/README.md b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/README.md new file mode 100644 index 00000000000..1eb43afa55e --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/README.md @@ -0,0 +1,32 @@ +sqlite +====== + +Author: Carl Caum +Copyright (c) 2011, Puppet Labs Inc. + +ABOUT +===== + +This module manages [sqlite](http://www.sqlite.org). Through declarion of the `sqlite` class, sqlite will be installed on the system. + +The `sqlite::db` defined type allows for the management of a sqlite database on the node + +CONFIGURATION +============= + +The main class (sqlite) only needs to be declared. No class parameters or top scope variables are needed. + +The `sqlite::db` defined type can be used to manage a sqlite database on the system. +The following parameters are available for the resources declaration: + +location What directory the database should go in. The presence of the directory must be managed separately of the defined type. +owner The owner of the sqlite database file on disk +group The group owning the sqlite database file on disk +mode The mode of the sqlite database file on disk +ensure Whether the database should be `present` or `absent`. Default to `present` +sqlite_cmd The sqlite command for the node's platform. Defaults to `sqlite3` + +TODO +==== + + * Allow for sql commands to be based to sqlite::db for use during creation diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/db.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/db.pp new file mode 100644 index 00000000000..8b780462e9e --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/db.pp @@ -0,0 +1,44 @@ +# Define: sqlite::db +# +# This define allows for managing the existance of a sqlite database +# +# Parameters: +# $location: +# The location on disk to store the sqlite database +# $owner: +# The owner of the sqlite database file on disk +# $group: +# The group owning the sqlite database file on disk +# $mode: +# The mode of the sqlite datbase file on disk +# $ensure: +# Whether the database should be `present` or `absent`. Defaults to `present` +# $sqlite_cmd: +# The sqlite command for the node's platform. Defaults to `sqlite3` +define sqlite::db( + $location = '', + $owner = 'root', + $group = 0, + $mode = '755', + $ensure = present, + $sqlite_cmd = 'sqlite3' + ) { + + $safe_location = $location ? { + '' => "/var/lib/sqlite/${name}.db", + default => $location, + } + + file { $safe_location: + ensure => $ensure, + owner => $owner, + group => $group, + notify => Exec["create_${name}_db"], + } + + exec { "create_${name}_db": + command => "${sqlite_cmd} $safe_location", + path => '/usr/bin:/usr/local/bin', + refreshonly => true, + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/init.pp new file mode 100644 index 00000000000..46b25062812 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/manifests/init.pp @@ -0,0 +1,16 @@ +# Class: sqlite +# +# This class manages the installation of the sqlite +# database. +# +# Sample Usage: +# class { 'sqlite': } +class sqlite { + package { 'sqlite': + ensure => installed, + } + + file { '/var/lib/sqlite/': + ensure => directory, + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/metadata.json b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/metadata.json new file mode 100644 index 00000000000..8ce7797ff33 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/metadata.json @@ -0,0 +1,12 @@ +/* ++-----------------------------------------------------------------------+ +| | +| ==> DO NOT EDIT THIS FILE! <== | +| | +| You should edit the `Modulefile` and run `puppet-module build` | +| to generate the `metadata.json` file for your releases. | +| | ++-----------------------------------------------------------------------+ +*/ + +{} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec.opts b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec.opts new file mode 100644 index 00000000000..91cd6427ed6 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec.opts @@ -0,0 +1,6 @@ +--format +s +--colour +--loadby +mtime +--backtrace diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec_helper.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec_helper.rb new file mode 100644 index 00000000000..a4aeeae232f --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/spec/spec_helper.rb @@ -0,0 +1,18 @@ +require 'pathname' +dir = Pathname.new(__FILE__).parent +$LOAD_PATH.unshift(dir, dir + 'lib', dir + '../lib') + +require 'mocha' +require 'puppet' +gem 'rspec', '=1.2.9' +require 'spec/autorun' + +Spec::Runner.configure do |config| + config.mock_with :mocha +end + +# We need this because the RAL uses 'should' as a method. This +# allows us the same behaviour but with a different method name. +class Object + alias :must :should +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/tests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/tests/init.pp new file mode 100644 index 00000000000..520d095142b --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/sqlite/tests/init.pp @@ -0,0 +1 @@ +include sqlite diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/border.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/border.png index df13bb6daf7..bc04508aae3 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/border.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/border.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/controls.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/controls.png index 65cfd1dc95c..57fe953b7e5 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/controls.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/controls.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/loading_background.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/loading_background.png index 9de11f46719..2d8598bf8cb 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/loading_background.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/colorbox/loading_background.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_green.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_green.png index 74db330cd05..7cf67ed1993 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_green.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_green.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_red.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_red.png index fbe093a5511..1460b78d120 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_red.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_red.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_yellow.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_yellow.png index e53847ea09a..e7d18257f11 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_yellow.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/favicon_yellow.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/magnify.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/magnify.png index 6073b9530ed..2a5079f4c4c 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/magnify.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/magnify.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png index 5b5dab2ab7b..68aa3f48d06 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_75_ffffff_40x100.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_75_ffffff_40x100.png index ac8b229af95..2b49a7ae745 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_75_ffffff_40x100.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_flat_75_ffffff_40x100.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png index ad3d6346e00..4b38ff2d7f6 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_65_ffffff_1x400.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_65_ffffff_1x400.png index 42ccba269b6..5c0c93f1e9f 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_65_ffffff_1x400.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_65_ffffff_1x400.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_dadada_1x400.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_dadada_1x400.png index 5a46b47cb16..43d3253fc7e 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_dadada_1x400.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_dadada_1x400.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png index 86c2baa655e..8265061241d 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png index 4443fdc1a15..c6270881b87 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png index 7c9fa6c6edc..67e0eb9b4d1 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_222222_256x240.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_222222_256x240.png index b273ff111d2..192e2b85257 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_222222_256x240.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_222222_256x240.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_2e83ff_256x240.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_2e83ff_256x240.png index 09d1cdc856c..88442a01937 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_2e83ff_256x240.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_2e83ff_256x240.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_454545_256x240.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_454545_256x240.png index 59bd45b907c..327cc6d4614 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_454545_256x240.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_454545_256x240.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_888888_256x240.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_888888_256x240.png index 6d02426c114..c71c1446075 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_888888_256x240.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_888888_256x240.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_cd0a0a_256x240.png b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_cd0a0a_256x240.png index 2ab019b73ec..30c8c0d35b8 100644 Binary files a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_cd0a0a_256x240.png and b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/stdlib/spec/unit/facter/coverage/assets/0.8.0/smoothness/images/ui-icons_cd0a0a_256x240.png differ diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.fixtures.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.fixtures.yml index 15f96922e01..3f18ef2fca2 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.fixtures.yml +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.fixtures.yml @@ -1,6 +1,10 @@ fixtures: repositories: - stdlib: "git://github.com/puppetlabs/puppetlabs-stdlib" - concat: "git://github.com/puppetlabs/puppetlabs-concat" + 'stdlib': + repo: 'git://github.com/puppetlabs/puppetlabs-stdlib' + ref: '4.1.0' + 'concat': + repo: 'git://github.com/puppetlabs/puppetlabs-concat' + ref: '1.0.1' symlinks: supervisord: "#{source_dir}" \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.travis.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.travis.yml index 6e544518c19..bc96a165e59 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.travis.yml +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/.travis.yml @@ -1,21 +1,28 @@ language: ruby bundler_args: --without development -script: "bundle exec rake spec lint" +script: "bundle exec rake test" rvm: - 1.8.7 - 1.9.3 - 2.0.0 env: - matrix: - - PUPPET_GEM_VERSION="~> 2.7.0" - - PUPPET_GEM_VERSION="~> 3.3.0" - - PUPPET_GEM_VERSION="~> 3.4.0" + - PUPPET_VERSION="~> 2.7.0" + - PUPPET_VERSION="~> 3.1.0" + - PUPPET_VERSION="~> 3.2.0" + - PUPPET_VERSION="~> 3.3.0" + - PUPPET_VERSION="~> 3.4.0" + - PUPPET_VERSION="~> 3.5.0" + - PUPPET_VERSION="~> 3.6.0" matrix: exclude: - - rvm: 1.9.3 - env: PUPPET_GEM_VERSION="~> 2.7.0" - rvm: 2.0.0 - env: PUPPET_GEM_VERSION="~> 2.7.0" + env: PUPPET_VERSION="~> 2.7.0" + - rvm: 1.9.3 + env: PUPPET_VERSION="~> 2.7.0" + - rvm: 2.0.0 + env: PUPPET_VERSION="~> 3.1.0" + - rvm: 1.8.7 + env: PUPPET_VERSION="~> 3.2.0" notifications: email: false diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Changelog b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Changelog index ab4faa445ff..ea933f5dbcb 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Changelog +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Changelog @@ -1,3 +1,72 @@ +2014-07-02 - v0.4.1 + +Fixes: + +- Fixed status code error on supervisord::supervisorctl commands, thanks to @jtreminio for the PR. + +2014-06-20 - v0.4.0 + +Fixes: + +- Removed root as group and replaced with uid 0 to enhance system +compatibility + +Enhancements: + +- Made package provider a user definable param see supervisord::package_provider and README for details of how to change this. +- All define types can now be automatically pulled in from hiera see example https://github.com/ajcrowe/puppet-supervisord#configure-a-program +- You can now override the default include path of $config_include/*.conf with your own array using $config_dirs. Bear in mind this would need to include whatever you set $config_include to be, with *.conf on the end. + +Many thanks for the PRs from @jasperla, @mvantellingen for the bug report on the service name and @hasc for the enhancement ideas. + +2014-06-06 - v0.3.3 + +Fixes: + +- Fixed typo in stopwaitsec param, should have been stopwaitsecs, thanks to @rchrd2 + +2014-05-03 - v0.3.2 + +Changes: + +- Added supervisord::executable_ctl variable for supervisorctl binary path, thanks to @bpgoldsb + +2014-04-22 - v0.3.1 + +Fixes: + +- Fixed typo in unix_socket_group param, thanks to @dig412 + +2014-03-11 - v0.3.0 + +Fixes: + +- Fixed typo in fcgi config +- Fixed typo in supervisord config with minfds and minprocs, thanks to @peefourtee +- Typo in README fixed thanks to @hopkinsth +- Removed refreshonly from pip_install exec resource +- Number of syntax fixes thanks to `puppet lint` + +Important Changes: + +- Lots of input validation has been added **PLEASE** check your config works before upgrading! +- Changed init_extras naming to defaults and cleaned things up. +- Starting and stopping apps is now done with supervisorctl commands to avoid service restarts + +Other Changes: + +- CSV functions now order things consistently +- Included description for classes and functions +- Expanded spec testing built with Travis CI +- Added beaker acceptance tests +- Added greater validation of various parameters +- Added coverage reporting for resources + +To-Do: + +- Add support for additional OS families such as Solaris. + + 2013-10-31 - v0.2.3 Fixes: diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Gemfile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Gemfile index 8612255f5b8..ba9a19d533a 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Gemfile +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Gemfile @@ -1,14 +1,26 @@ source 'https://rubygems.org' -group :development, :test do +group :test do gem 'rake' - gem 'puppetlabs_spec_helper', :require => false - gem 'rspec-system-puppet', '~> 2.0' - gem 'puppet-lint', '~> 0.3.2' + gem 'puppet-lint' + gem 'puppet-syntax' + gem 'puppetlabs_spec_helper' + gem 'rspec-puppet', :git => 'https://github.com/rodjek/rspec-puppet.git' , :ref => 'c44381a240ec420d4ffda7bffc55ee4d9c08d682' + gem 'rspec', '2.14.1' end -if puppetversion = ENV['PUPPET_GEM_VERSION'] - gem 'puppet', puppetversion, :require => false -else - gem 'puppet', :require => false +group :development do + gem 'travis' + gem 'travis-lint' + gem 'beaker' + gem 'beaker-rspec' + gem 'pry' + gem 'guard-rake' +end + + +if puppetversion = ENV['PUPPET_VERSION'] + gem 'puppet', puppetversion +else + gem 'puppet', '~> 3.4.0' end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Modulefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Modulefile index 4a0552115da..80d47f22679 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Modulefile +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Modulefile @@ -1,5 +1,5 @@ name 'ajcrowe-supervisord' -version '0.2.3' +version '0.4.1' source 'git@github.com/ajcrowe/puppet-supervisord.git' author 'Alex Crowe' license 'Apache License, Version 2.0' diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/README.md b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/README.md index a8419a09082..b454cd9307a 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/README.md +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/README.md @@ -4,7 +4,7 @@ Puppet module to manage the [supervisord](http://supervisord.org/) process control system. -Functions available to configure +Functions available to configure * [programs](http://supervisord.org/configuration.html#program-x-section-settings) * [groups](http://supervisord.org/configuration.html#group-x-section-settings) @@ -31,10 +31,16 @@ class supervisord { } ``` -This will download [setuptool](https://bitbucket.org/pypa/setuptools) and install pip with easy_install. +This will download [setuptool](https://bitbucket.org/pypa/setuptools) and install pip with easy_install. You can pass a specific url with `$setuptools_url = 'url'` +### Install without pip + +If you want to use your system package manager you can specify that with `supervisord::package_provider`. + +You'll also likely need to adjust the `supervisord::service_name` to match that installed by the system package. If you're using Debian or Redhat OS families you'll also want to disable the init scripts with `supervisord::install_init = false`. + Note: Only Debian and RedHat families have an init script currently. ### Configure a program @@ -61,23 +67,61 @@ supervisord::program { 'myprogram': } ``` +Or you can fully define your programs in hiera: + +```yaml +supervisord::programs: + 'myprogram': + command: 'command --args' + autostart: yes + autorestart: 'true' + environment: + HOME: '/home/myuser' + PATH: '/bin:/sbin:/usr/bin:/usr/sbin' + SECRET: 'mysecret' +``` + ### Configure a group ```ruby supervisord::group { 'mygroup': priority => 100, - program => ['program1', 'program2', 'program3'] + programs => ['program1', 'program2', 'program3'] } ``` +### Configure an eventlistener + +```ruby +supervisord::eventlistener { 'mylistener': + command => 'command --args', + events => ['PROCESS_STATE', 'PROCESS_STATE_START'] + priority => '100', + env_var => 'my_common_envs' +} +``` + +### Run supervisorctl Commands + +Should you need to run a sequence of command with `supervisorctl` you can use the define type `supervisord::supervisorctl` + +```ruby +supervisord::supervisorctl { 'restart_myapp': + command => 'restart', + process => 'myapp' +} +``` + +You can also issue a command without specifying a process. + ### Development If you have suggestions or improvements please file an issue or pull request, i'll try and sort them as quickly as possble. -If you submit a pull please try and include tests for the new functionality. The module is tested with [Travis-CI](https://travis-ci.org/ajcrowe/puppet-supervisord). +If you submit a pull please try and include tests for the new functionality/fix. The module is tested with [Travis-CI](https://travis-ci.org/ajcrowe/puppet-supervisord). ### Credits * Debian init script sourced from the system package. -* RedHat/Centos init script sourced from https://github.com/Supervisor/initscripts +* RedHat/Centos init script sourced from https://github.com/Supervisor/initscripts diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Rakefile b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Rakefile index e00f7d11877..cd592af48f4 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Rakefile +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/Rakefile @@ -1,7 +1,28 @@ require 'puppetlabs_spec_helper/rake_tasks' require 'puppet-lint/tasks/puppet-lint' -require 'rspec-system/rake_task' +require 'puppet-syntax/tasks/puppet-syntax' PuppetLint.configuration.send('disable_80chars') PuppetLint.configuration.send('disable_class_inherits_from_params_class') -PuppetLint.configuration.send('disable_documentation') +PuppetLint.configuration.send('disable_quoted_booleans') +PuppetLint.configuration.send('disable_autoloader_layout') + +exclude_paths = [ + "pkg/**/*", + "vendor/**/*", + "spec/**/*", +] +PuppetLint.configuration.ignore_paths = exclude_paths +PuppetSyntax.exclude_paths = exclude_paths + +desc "Acceptance Tests" +RSpec::Core::RakeTask.new(:acceptance) do |t| + t.pattern = 'spec/acceptance' +end + +desc "Test Suite" +task :test => [ + :lint, + :syntax, + :spec +] \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/array2csv.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/array2csv.rb index cfa52b2bbf2..6d34d5d5474 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/array2csv.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/array2csv.rb @@ -1,14 +1,12 @@ # # Converts the array to a csv string # -# # $array = [ 'string1', 'string2', 'string3' ] # # becomes: # # $string = "string1,string2,string3" # - module Puppet::Parser::Functions newfunction(:array2csv, :type => :rvalue, :doc => <<-'EOS' Returns a sorted csv formatted string from an array in the form diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/hash2csv.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/hash2csv.rb index 6098b67367d..5371328f2ff 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/hash2csv.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/lib/puppet/parser/functions/hash2csv.rb @@ -1,7 +1,6 @@ # # Converts the hash to a csv string # -# # $hash = { # HOME => '/home/user', # ENV1 => 'env1', @@ -12,7 +11,6 @@ # # $string = "HOME='/home/user',ENV1='env1',SECRET='secret'" # - module Puppet::Parser::Functions newfunction(:hash2csv, :type => :rvalue, :doc => <<-'EOS' Returns a csv formatted string from an hash in the form diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/config.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/config.pp index cc8b1ee49d0..93713729e8b 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/config.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/config.pp @@ -1,6 +1,16 @@ +# Class: supervisord::config +# +# Configuration class for supervisor init and conf directories +# class supervisord::config inherits supervisord { - file { [ "${supervisord::config_include}", "${supervisord::log_path}"]: + file { $supervisord::config_include: + ensure => directory, + owner => 'root', + mode => '0755' + } + + file { $supervisord::log_path: ensure => directory, owner => 'root', mode => '0755' @@ -15,30 +25,26 @@ class supervisord::config inherits supervisord { } if $supervisord::install_init { - - $osname = downcase($::osfamily) - file { '/etc/init.d/supervisord': ensure => present, owner => 'root', mode => '0755', - content => template("supervisord/init/${osname}_init.erb") + content => template("supervisord/init/${::osfamily}/init.erb") } - if $supervisord::init_extras { - file { $supervisord::init_extras: + if $supervisord::init_defaults { + file { $supervisord::init_defaults: ensure => present, owner => 'root', mode => '0755', - content => template("supervisord/init/${osname}_extra.erb") + content => template("supervisord/init/${::osfamily}/defaults.erb") } } - } concat { $supervisord::config_file: owner => 'root', - group => 'root', + group => '0', mode => '0755' } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/eventlistener.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/eventlistener.pp index 41b7cf6c730..fd52d6e4da4 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/eventlistener.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/eventlistener.pp @@ -1,8 +1,16 @@ +# Define: supervisord::eventlistener +# +# This define creates an eventlistener configuration file +# +# Documentation on parameters available at: +# http://supervisord.org/configuration.html#eventlistener-x-section-settings +# define supervisord::eventlistener( $command, $ensure = present, + $ensure_process = 'running', + $buffer_size = 10, $events = undef, - $buffer_size = undef, $result_handler = undef, $env_var = undef, $process_name = undef, @@ -15,16 +23,16 @@ define supervisord::eventlistener( $startretries = undef, $exitcodes = undef, $stopsignal = undef, - $stopwaitsec = undef, + $stopwaitsecs = undef, $stopasgroup = undef, $killasgroup = undef, $user = undef, $redirect_stderr = undef, - $stdout_logfile = "${supervisord::log_path}/eventlistener_${name}.log", + $stdout_logfile = "eventlistener_${name}.log", $stdout_logfile_maxbytes = undef, $stdout_logfile_backups = undef, $stdout_events_enabled = undef, - $stderr_logfile = "${supervisord::log_path}/eventlistener_${name}.error", + $stderr_logfile = "eventlistener_${name}.error", $stderr_logfile_maxbytes = undef, $stderr_logfile_backups = undef, $stderr_events_enabled = undef, @@ -36,11 +44,45 @@ define supervisord::eventlistener( include supervisord + # parameter validation + validate_string($command) + validate_re($ensure_process, ['running', 'stopped', 'removed']) + validate_re($buffer_size, '^\d+') + if $events { validate_array($events) } + if $result_handler { validate_string($result_handler) } + if $numprocs { validate_re($numprocs, '^\d+')} + if $numprocs_start { validate_re($numprocs_start, '^\d+')} + if $priority { validate_re($priority, '^\d+') } + if $autostart { validate_bool($autostart) } + if $autorestart { validate_re($autorestart, ['true', 'false', 'unexpected']) } + if $startsecs { validate_re($startsecs, '^\d+')} + if $startretries { validate_re($startretries, '^\d+')} + if $exitcodes { validate_string($exitcodes)} + if $stopsignal { validate_re($stopsignal, ['TERM', 'HUP', 'INT', 'QUIT', 'KILL', 'USR1', 'USR2']) } + if $stopwaitsecs { validate_re($stopwaitsecs, '^\d+')} + if $stopasgroup { validate_bool($stopasgroup) } + if $killasgroup { validate_bool($killasgroup) } + if $user { validate_string($user) } + if $redirect_stderr { validate_bool($redirect_stderr) } + validate_string($stdout_logfile) + if $stdout_logfile_maxbytes { validate_string($stdout_logfile_maxbytes) } + if $stdout_logfile_backups { validate_re($stdout_logfile_backups, '^\d+')} + if $stdout_events_enabled { validate_bool($stdout_events_enabled) } + validate_string($stderr_logfile) + if $stderr_logfile_maxbytes { validate_string($stderr_logfile_maxbytes) } + if $stderr_logfile_backups { validate_re($stderr_logfile_backups, '^\d+')} + if $stderr_events_enabled { validate_bool($stderr_events_enabled) } + if $directory { validate_absolute_path($directory) } + if $umask { validate_re($umask, '^[0-7][0-7][0-7]$') } + + # convert environment data into a csv if $env_var { - $env_hash = hiera($env_var) + $env_hash = hiera_hash($env_var) + validate_hash($env_hash) $env_string = hash2csv($env_hash) } elsif $environment { + validate_hash($environment) $env_string = hash2csv($environment) } @@ -55,6 +97,22 @@ define supervisord::eventlistener( owner => 'root', mode => '0755', content => template('supervisord/conf/eventlistener.erb'), - notify => Class['supervisord::service'] + notify => Class['supervisord::reload'] + } + + case $ensure_process { + 'stopped': { + supervisord::supervisorctl { "stop_${name}": + command => 'stop', + process => $name + } + } + 'removed': { + supervisord::supervisorctl { "remove_${name}": + command => 'remove', + process => $name + } + } + default: { } } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/fcgi_program.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/fcgi_program.pp index 923b1798bff..633b024917e 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/fcgi_program.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/fcgi_program.pp @@ -1,7 +1,15 @@ +# Define: supervisord::fcgi_program +# +# This define creates an eventlistener configuration file +# +# Documentation on parameters available at: +# http://supervisord.org/configuration.html#fcgi-program-x-section-settings +# define supervisord::fcgi_program( $command, $socket, $ensure = present, + $ensure_process = 'running', $socket_owner = undef, $socket_mode = undef, $env_var = undef, @@ -15,17 +23,17 @@ define supervisord::fcgi_program( $startretries = undef, $exitcodes = undef, $stopsignal = undef, - $stopwaitsec = undef, + $stopwaitsecs = undef, $stopasgroup = undef, $killasgroup = undef, $user = undef, $redirect_stderr = undef, - $stdout_logfile = "${supervisord::log_path}/fcgi-program_${name}.log", + $stdout_logfile = "fcgi-program_${name}.log", $stdout_logfile_maxbytes = undef, $stdout_logfile_backups = undef, $stdout_capture_maxbytes = undef, $stdout_events_enabled = undef, - $stderr_logfile = "${supervisord::log_path}/fcgi-program_${name}.error", + $stderr_logfile = "fcgi-program_${name}.error", $stderr_logfile_maxbytes = undef, $stderr_logfile_backups = undef, $stderr_capture_maxbytes = undef, @@ -38,11 +46,46 @@ define supervisord::fcgi_program( include supervisord + # parameter validation + validate_string($command) + validate_re($ensure_process, ['running', 'stopped', 'removed']) + validate_re($socket, ['^tcp:\/\/.*:\d+$', '^unix:\/\/\/']) + if $process_name { validate_string($process_name) } + if $numprocs { validate_re($numprocs, '^\d+')} + if $numprocs_start { validate_re($numprocs_start, '^\d+')} + if $priority { validate_re($priority, '^\d+') } + if $autostart { validate_bool($autostart) } + if $autorestart { validate_re($autorestart, ['true', 'false', 'unexpected']) } + if $startsecs { validate_re($startsecs, '^\d+')} + if $startretries { validate_re($startretries, '^\d+')} + if $exitcodes { validate_string($exitcodes)} + if $stopsignal { validate_re($stopsignal, ['TERM', 'HUP', 'INT', 'QUIT', 'KILL', 'USR1', 'USR2']) } + if $stopwaitsecs { validate_re($stopwaitsecs, '^\d+')} + if $stopasgroup { validate_bool($stopasgroup) } + if $killasgroup { validate_bool($killasgroup) } + if $user { validate_string($user) } + if $redirect_stderr { validate_bool($redirect_stderr) } + validate_string($stdout_logfile) + if $stdout_logfile_maxbytes { validate_string($stdout_logfile_maxbytes) } + if $stdout_logfile_backups { validate_re($stdout_logfile_backups, '^\d+')} + if $stdout_capture_maxbytes { validate_string($stdout_capture_maxbytes) } + if $stdout_events_enabled { validate_bool($stdout_events_enabled) } + validate_string($stderr_logfile) + if $stderr_logfile_maxbytes { validate_string($stderr_logfile_maxbytes) } + if $stderr_logfile_backups { validate_re($stderr_logfile_backups, '^\d+')} + if $stderr_capture_maxbytes { validate_string($stderr_capture_maxbytes) } + if $stderr_events_enabled { validate_bool($stderr_events_enabled) } + if $directory { validate_absolute_path($directory) } + if $umask { validate_re($umask, '^[0-7][0-7][0-7]$') } + + # convert environment data into a csv if $env_var { - $env_hash = hiera($env_var) + $env_hash = hiera_hash($env_var) + validate_hash($env_hash) $env_string = hash2csv($env_hash) } elsif $environment { + validate_hash($environment) $env_string = hash2csv($environment) } @@ -53,6 +96,22 @@ define supervisord::fcgi_program( owner => 'root', mode => '0755', content => template('supervisord/conf/fcgi_program.erb'), - notify => Class['supervisord::service'] + notify => Class['supervisord::reload'] + } + + case $ensure_process { + 'stopped': { + supervisord::supervisorctl { "stop_${name}": + command => 'stop', + process => $name + } + } + 'removed': { + supervisord::supervisorctl { "remove_${name}": + command => 'remove', + process => $name + } + } + default: { } } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/group.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/group.pp index 0f6b1ca2adc..45cb29cf290 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/group.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/group.pp @@ -1,3 +1,10 @@ +# Define: supervisord::group +# +# This define creates an group configuration file +# +# Documentation on parameters available at: +# http://supervisord.org/configuration.html#group-x-section-settings +# define supervisord::group ( $programs, $ensure = present, @@ -6,6 +13,10 @@ define supervisord::group ( include supervisord + # parameter validation + validate_array($programs) + if $priority { validate_re($priority, '^\d+', "invalid priority value of: ${priority}") } + $progstring = array2csv($programs) $conf = "${supervisord::config_include}/group_${name}.conf" @@ -13,6 +24,7 @@ define supervisord::group ( ensure => $ensure, owner => 'root', mode => '0755', - content => template('supervisord/conf/group.erb') + content => template('supervisord/conf/group.erb'), + notify => Class['supervisord::reload'] } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/init.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/init.pp index 801c46b3b36..fa396da578d 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/init.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/init.pp @@ -1,12 +1,20 @@ -# This class installs supervisord and configured it to run on boot +# Class: supervisord +# +# This class installs supervisord via pip +# class supervisord( $package_ensure = $supervisord::params::package_ensure, + $package_name = $supervisord::params::package_name, + $package_provider = $supervisord::params::package_provider, $service_ensure = $supervisord::params::service_ensure, + $service_name = $supervisord::params::service_name, $install_init = $supervisord::params::install_init, $install_pip = false, - $init_extras = $supervisord::params::init_extras, + $init_defaults = $supervisord::params::init_defaults, $setuptools_url = $supervisord::params::setuptools_url, + $executable_path = $supervisord::params::executable_path, $executable = $supervisord::params::executable, + $executable_ctl = $supervisord::params::executable_ctl, $log_path = $supervisord::params::log_path, $log_file = $supervisord::params::log_file, @@ -19,20 +27,20 @@ class supervisord( $nodaemon = $supervisord::params::nodaemon, $minfds = $supervisord::params::minfds, $minprocs = $supervisord::params::minprocs, - $config_path = $supervisord::params::config_path, $config_include = $supervisord::params::config_include, $config_file = $supervisord::params::config_file, + $config_dirs = undef, $umask = $supervisord::params::umask, $unix_socket = $supervisord::params::unix_socket, $unix_socket_file = $supervisord::params::unix_socket_file, $unix_socket_mode = $supervisord::params::unix_socket_mode, $unix_socket_owner = $supervisord::params::unix_socket_owner, - $unix_scoket_group = $supervisord::params::unix_socket_group, + $unix_socket_group = $supervisord::params::unix_socket_group, $inet_server = $supervisord::params::inet_server, - $inet_server_hostname = $supervisord::params::inet_hostname, - $inet_server_port = $supervisord::params::inet_port, + $inet_server_hostname = $supervisord::params::inet_server_hostname, + $inet_server_port = $supervisord::params::inet_server_port, $unix_auth = false, $unix_username = undef, @@ -47,26 +55,76 @@ class supervisord( $childlogdir = undef, $environment = undef, $env_var = undef, + $directory = undef, $strip_ansi = false, - $nocleanup = false + $nocleanup = false, + + $eventlisteners = {}, + $fcgi_programs = {}, + $groups = {}, + $programs = {} ) inherits supervisord::params { + validate_bool($install_pip) + validate_bool($install_init) + validate_bool($nodaemon) + validate_bool($unix_auth) + validate_bool($inet_auth) + validate_bool($strip_ansi) + validate_bool($nocleanup) + + validate_hash($eventlisteners) + validate_hash($fcgi_programs) + validate_hash($groups) + validate_hash($programs) + + validate_absolute_path($config_include) + validate_absolute_path($log_path) + validate_absolute_path($run_path) + if $childlogdir { validate_absolute_path($childlogdir) } + if $directory { validate_absolute_path($directory) } + + $log_levels = ['^critical$', '^error$', '^warn$', '^info$', '^debug$', '^trace$', '^blather$'] + validate_re($log_level, $log_levels, "invalid log_level: ${log_level}") + validate_re($umask, '^0[0-7][0-7]$', "invalid umask: ${umask}.") + validate_re($unix_socket_mode, '^[0-7][0-7][0-7][0-7]$', "invalid unix_socket_mode: ${unix_socket_mode}") + + if ! is_integer($logfile_backups) { fail("invalid logfile_backups: ${logfile_backups}.")} + if ! is_integer($minfds) { fail("invalid minfds: ${minfds}.")} + if ! is_integer($minprocs) { fail("invalid minprocs: ${minprocs}.")} + if ! is_integer($inet_server_port) { fail("invalid inet_server_port: ${inet_server_port}.")} + if $env_var { + validate_hash($env_var) $env_hash = hiera($env_var) $env_string = hash2csv($env_hash) } elsif $environment { + validate_hash($environment) $env_string = hash2csv($environment) } + if $config_dirs { + validate_array($config_dirs) + $config_include_string = join($config_dirs, " ") + } + else { + $config_include_string = "${config_include}/*.conf" + } + + create_resources('supervisord::eventlistener', $eventlisteners) + create_resources('supervisord::fcgi_program', $fcgi_programs) + create_resources('supervisord::group', $groups) + create_resources('supervisord::program', $programs) + if $install_pip { include supervisord::pip Class['supervisord::pip'] -> Class['supervisord::install'] } - include supervisord::install, supervisord::config, supervisord::service + include supervisord::install, supervisord::config, supervisord::service, supervisord::reload Class['supervisord::install'] -> Class['supervisord::config'] ~> Class['supervisord::service'] - + Class['supervisord::reload'] -> Supervisord::Supervisorctl <| |> } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/install.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/install.pp index 1d36ec68334..387c77f5cba 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/install.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/install.pp @@ -1,6 +1,10 @@ +# Class supervisord::install +# +# Installs supervisor package (defaults to using pip) +# class supervisord::install inherits supervisord { - package { 'supervisor': + package { $supervisord::package_name: ensure => $supervisord::package_ensure, - provider => 'pip' + provider => $supervisord::package_provider } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/params.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/params.pp index 87d17d16179..47a21852e01 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/params.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/params.pp @@ -1,13 +1,42 @@ +# Class: supervisord::params +# +# Default parameters for supervisord +# class supervisord::params { + case $::osfamily { + 'RedHat': { + $init_defaults = '/etc/sysconfig/supervisord' + $unix_socket_group = 'nobody' + $install_init = true + $executable_path = '/usr/bin' + } + 'Debian': { + $init_defaults = '/etc/default/supervisor' + $unix_socket_group = 'nogroup' + $install_init = true + $executable_path = '/usr/local/bin' + } + default: { + $init_defaults = false + $unix_socket_group = 'nogroup' + $install_init = false + $executable_path = '/usr/local/bin' + } + } + + # default supervisord params $package_ensure = 'installed' + $package_provider = 'pip' $service_ensure = 'running' + $service_name = 'supervisord' $package_name = 'supervisor' - $executable = '/usr/local/bin/supervisord' + $executable = "${$executable_path}/supervisord" + $executable_ctl = "${executable_path}/supervisorctl" $run_path = '/var/run' - $pid_file = "${run_path}/supervisord.pid" + $pid_file = 'supervisord.pid' $log_path = '/var/log/supervisor' - $log_file = "${log_path}/supervisord.log" + $log_file = 'supervisord.log' $logfile_maxbytes = '50MB' $logfile_backups = '10' $log_level = 'info' @@ -20,7 +49,7 @@ class supervisord::params { $setuptools_url = 'https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py' $unix_socket = true - $unix_socket_file = "${run_path}/supervisor.sock" + $unix_socket_file = 'supervisor.sock' $unix_socket_mode = '0700' $unix_socket_owner = 'nobody' @@ -28,22 +57,4 @@ class supervisord::params { $inet_server_hostname = '127.0.0.1' $inet_server_port = '9001' $inet_auth = false - - case $::osfamily { - 'RedHat': { - $init_extras = '/etc/sysconfig/supervisord' - $unix_socket_group = 'nobody' - $install_init = true - } - 'Debian': { - $init_extras = '/etc/default/supervisor' - $unix_socket_group = 'nogroup' - $install_init = true - } - default: { - $init_extras = false - $unix_socket_group = 'nogroup' - $install_init = false - } - } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/pip.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/pip.pp index c05f2d7f64b..dcf57223498 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/pip.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/pip.pp @@ -1,3 +1,7 @@ +# Class: supervisord::pip +# +# Optional class to install setuptool and pip +# class supervisord::pip inherits supervisord { Exec { diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/program.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/program.pp index 8a00d41c77c..617a68ab208 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/program.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/program.pp @@ -1,6 +1,14 @@ +# Define: supervisord::program +# +# This define creates an program configuration file +# +# Documentation on parameters available at: +# http://supervisord.org/configuration.html#program-x-section-settings +# define supervisord::program( $command, $ensure = present, + $ensure_process = 'running', $env_var = undef, $process_name = undef, $numprocs = undef, @@ -12,17 +20,17 @@ define supervisord::program( $startretries = undef, $exitcodes = undef, $stopsignal = undef, - $stopwaitsec = undef, + $stopwaitsecs = undef, $stopasgroup = undef, $killasgroup = undef, $user = undef, $redirect_stderr = undef, - $stdout_logfile = "${supervisord::log_path}/program_${name}.log", + $stdout_logfile = "program_${name}.log", $stdout_logfile_maxbytes = undef, $stdout_logfile_backups = undef, $stdout_capture_maxbytes = undef, $stdout_events_enabled = undef, - $stderr_logfile = "${supervisord::log_path}/program_${name}.error", + $stderr_logfile = "program_${name}.error", $stderr_logfile_maxbytes = undef, $stderr_logfile_backups = undef, $stderr_capture_maxbytes = undef, @@ -35,11 +43,45 @@ define supervisord::program( include supervisord + # parameter validation + validate_string($command) + validate_re($ensure_process, ['running', 'stopped', 'removed']) + if $process_name { validate_string($process_name) } + if $numprocs { validate_re($numprocs, '^\d+')} + if $numprocs_start { validate_re($numprocs_start, '^\d+')} + if $priority { validate_re($priority, '^\d+') } + if $autostart { validate_bool($autostart) } + if $autorestart { validate_re($autorestart, ['true', 'false', 'unexpected']) } + if $startsecs { validate_re($startsecs, '^\d+')} + if $startretries { validate_re($startretries, '^\d+')} + if $exitcodes { validate_string($exitcodes)} + if $stopsignal { validate_re($stopsignal, ['TERM', 'HUP', 'INT', 'QUIT', 'KILL', 'USR1', 'USR2']) } + if $stopwaitsecs { validate_re($stopwaitsecs, '^\d+')} + if $stopasgroup { validate_bool($stopasgroup) } + if $killasgroup { validate_bool($killasgroup) } + if $user { validate_string($user) } + if $redirect_stderr { validate_bool($redirect_stderr) } + validate_string($stdout_logfile) + if $stdout_logfile_maxbytes { validate_string($stdout_logfile_maxbytes) } + if $stdout_logfile_backups { validate_re($stdout_logfile_backups, '^\d+')} + if $stdout_capture_maxbytes { validate_string($stdout_capture_maxbytes) } + if $stdout_events_enabled { validate_bool($stdout_events_enabled) } + validate_string($stderr_logfile) + if $stderr_logfile_maxbytes { validate_string($stderr_logfile_maxbytes) } + if $stderr_logfile_backups { validate_re($stderr_logfile_backups, '^\d+')} + if $stderr_capture_maxbytes { validate_string($stderr_capture_maxbytes) } + if $stderr_events_enabled { validate_bool($stderr_events_enabled) } + if $directory { validate_absolute_path($directory) } + if $umask { validate_re($umask, '^[0-7][0-7][0-7]$') } + + # convert environment data into a csv if $env_var { - $env_hash = hiera($env_var) + $env_hash = hiera_hash($env_var) + validate_hash($env_hash) $env_string = hash2csv($env_hash) } elsif $environment { + validate_hash($environment) $env_string = hash2csv($environment) } @@ -50,6 +92,22 @@ define supervisord::program( owner => 'root', mode => '0755', content => template('supervisord/conf/program.erb'), - notify => Class['supervisord::service'] + notify => Class['supervisord::reload'] + } + + case $ensure_process { + 'stopped': { + supervisord::supervisorctl { "stop_${name}": + command => 'stop', + process => $name + } + } + 'removed': { + supervisord::supervisorctl { "remove_${name}": + command => 'remove', + process => $name + } + } + default: { } } } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/reload.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/reload.pp new file mode 100644 index 00000000000..79eca3d7e0f --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/reload.pp @@ -0,0 +1,19 @@ +# Class: supervisord::reload +# +# Class to reread and update supervisord with supervisorctl +# +class supervisord::reload inherits supervisord { + + $supervisorctl = $::supervisord::executable_ctl + + exec { 'supervisorctl_reread': + command => "${supervisorctl} reread", + refreshonly => true, + require => Service[$supervisord::service_name], + } + exec { 'supervisorctl_update': + command => "${supervisorctl} update", + refreshonly => true, + require => Service[$supervisord::service_name], + } +} diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/service.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/service.pp index 6e17976165d..f02a0d0a081 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/service.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/service.pp @@ -1,5 +1,9 @@ +# Class: supervisord::service +# +# Class for the supervisord service +# class supervisord::service inherits supervisord { - service { 'supervisord': + service { $supervisord::service_name: ensure => $supervisord::service_ensure, enable => true, hasrestart => true, diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/supervisorctl.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/supervisorctl.pp new file mode 100644 index 00000000000..473d301185b --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/manifests/supervisorctl.pp @@ -0,0 +1,27 @@ +# Define: supervisord:supervisorctl +# +# This define executes command with the supervisorctl tool +# +define supervisord::supervisorctl( + $command, + $process = undef, + $refreshonly = false +) { + + validate_string($command) + validate_string($process) + + $supervisorctl = $::supervisord::executable_ctl + + if $process { + $cmd = join([$supervisorctl, $command, $process], ' ') + } + else { + $cmd = join([$supervisorctl, $command]) + } + + exec { "supervisorctl_command_${name}": + command => $cmd, + refreshonly => $refreshonly + } +} \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-i386.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-i386.yml new file mode 100644 index 00000000000..f8d4013a31b --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-i386.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-65-i386: + roles: + - master + platform: el-6-i386 + box : centos-65-i386-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-i386-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-x64.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-x64.yml new file mode 100644 index 00000000000..7535c104afb --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/centos-65-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + centos-65-x64: + roles: + - master + platform: el-6-x86_64 + box : centos-65-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-i386.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-i386.yml new file mode 100644 index 00000000000..d1233aa83d1 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-i386.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-73-i386: + roles: + - master + platform: debian-7-i386 + box : debian-73-i386-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-i386-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-x64.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-x64.yml new file mode 100644 index 00000000000..5b87870a909 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/debian-73-x64.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-73-x64: + roles: + - master + platform: debian-7-amd64 + box : debian-73-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/default.yml b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/default.yml new file mode 100644 index 00000000000..5b87870a909 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/nodesets/default.yml @@ -0,0 +1,10 @@ +HOSTS: + debian-73-x64: + roles: + - master + platform: debian-7-amd64 + box : debian-73-x64-virtualbox-nocm + box_url : http://puppet-vagrant-boxes.puppetlabs.com/debian-73-x64-virtualbox-nocm.box + hypervisor : vagrant +CONFIG: + type: foss diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/supervisord_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/supervisord_spec.rb new file mode 100644 index 00000000000..47d052a4eec --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/acceptance/supervisord_spec.rb @@ -0,0 +1,114 @@ +require 'spec_helper_acceptance' + +describe 'supervisord install' do + + context 'default parameters with pip and init install' do + it 'should work with no errors' do + pp = <<-EOS + class { 'supervisord': install_pip => true, install_init => true} + EOS + + expect(apply_manifest(pp).exit_code).to_not eq(1) + expect(apply_manifest(pp).exit_code).to eq(0) + end + + describe service('supervisord') do + it { should be_enabled } + it { should be_running } + it 'should restart successfully' do + cmd="service supervisord restart" + expect(shell(cmd).exit_code).to_not eq(1) + end + end + end +end + +describe 'supervisord::program' do + context 'create a program config' do + it 'should install a program file' do + + pp = <<-EOS + include supervisord + supervisord::program { 'test': + command => 'echo', + priority => '100', + environment => { + 'HOME' => '/root', + 'PATH' => '/bin', + } + } + EOS + + expect(apply_manifest(pp).exit_code).to_not eq(1) + expect(apply_manifest(pp).exit_code).to eq(0) + end + + it 'should contain the correct values' do + cmd='grep command=echo /etc/supervisor.d/program_test.conf' + expect(shell(cmd).exit_code).to eq(0) + cmd='grep priority=100 /etc/supervisor.d/program_test.conf' + expect(shell(cmd).exit_code).to eq(0) + cmd='grep "environment=" /etc/supervisor.d/program_test.conf' + expect(shell(cmd).exit_code).to eq(0) + end + end +end + +describe 'supervisord::fcgi-program' do + context 'create fcgi-program config' do + it 'should install a fcgi-program file' do + + pp = <<-EOS + include supervisord + supervisord::fcgi_program { 'test': + socket => 'tcp://localhost:1000', + command => 'echo', + priority => '100', + environment => { + 'HOME' => '/root', + 'PATH' => '/bin', + } + } + EOS + + expect(apply_manifest(pp).exit_code).to_not eq(1) + expect(apply_manifest(pp).exit_code).to eq(0) + end + + it 'should contain the correct values' do + cmd='grep socket=tcp://localhost:1000 /etc/supervisor.d/fcgi-program_test.conf' + expect(shell(cmd).exit_code).to eq(0) + cmd="grep command=echo /etc/supervisor.d/fcgi-program_test.conf" + expect(shell(cmd).exit_code).to eq(0) + cmd="grep priority=100 /etc/supervisor.d/fcgi-program_test.conf" + expect(shell(cmd).exit_code).to eq(0) + cmd='grep "environment=" /etc/supervisor.d/fcgi-program_test.conf' + expect(shell(cmd).exit_code).to eq(0) + end + end +end + +describe 'supervisord::group' do + context 'create group config' do + it 'should install a group config' do + + pp = <<-EOS + include supervisord + supervisord::group { 'test': + programs => ['test'], + priority => '100', + } + EOS + + expect(apply_manifest(pp).exit_code).to_not eq(1) + expect(apply_manifest(pp).exit_code).to eq(0) + end + + it 'should contain the correct values' do + cmd='grep "programs=test" /etc/supervisor.d/group_test.conf' + expect(shell(cmd).exit_code).to eq(0) + cmd="grep priority=100 /etc/supervisor.d/group_test.conf" + expect(shell(cmd).exit_code).to eq(0) + end + end +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/classes/supervisord_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/classes/supervisord_spec.rb index 238876c7dcd..b845920f6fe 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/classes/supervisord_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/classes/supervisord_spec.rb @@ -3,14 +3,26 @@ require 'spec_helper' describe 'supervisord' do concatdir = '/var/lib/puppet/concat' - configfile = '/etc/supervisord.conf' let(:facts) {{ :concat_basedir => concatdir }} it { should contain_class('supervisord') } it { should contain_class('supervisord::install') } it { should contain_class('supervisord::config') } it { should contain_class('supervisord::service') } - it { should contain_concat__fragment('supervisord_main').with_content(/logfile/) } + it { should contain_class('supervisord::params') } + it { should contain_class('supervisord::reload') } + it { should contain_package('supervisor') } + + describe '#service_name' do + context 'default' do + it { should contain_service('supervisord') } + end + + context 'specified' do + let(:params) {{ :service_name => 'myservicename' }} + it { should contain_service('myservicename') } + end + end describe '#install_pip' do context 'default' do @@ -18,8 +30,16 @@ describe 'supervisord' do end context 'true' do - let (:params) {{ :install_pip => true }} + let(:params) {{ :install_pip => true }} it { should contain_class('supervisord::pip') } + it { should contain_exec('install_setuptools') } + it { should contain_exec('install_pip') } + end + + context 'true and RedHat' do + let(:params) {{ :install_pip => true }} + let(:facts) {{ :osfamily => 'RedHat', :concat_basedir => concatdir }} + it { should contain_exec('pip_provider_name_fix') } end end @@ -28,11 +48,6 @@ describe 'supervisord' do it { should contain_class('supervisord').without_env_hash } it { should contain_class('supervisord').without_env_string } end - #context 'is specified' do - # let(:params) {{ :env_var => 'foovars' }} - # let(:hiera_data) {{ :foovars => { 'key1' => 'value1', 'key2' => 'value2' } }} - # it { should contain_concat__fragment('supervisord_main').with_content(/environment=key1='value1',key2='value2'/) } - #end end describe '#environment' do @@ -41,7 +56,8 @@ describe 'supervisord' do end context 'is specified' do let(:params) {{ :environment => { 'key1' => 'value1', 'key2' => 'value2' } }} - it { should contain_concat__fragment('supervisord_main').with_content(/environment=key1='value1',key2='value2'/) } + it { should contain_concat__fragment('supervisord_main')\ + .with_content(/environment=key1='value1',key2='value2'/) } end end @@ -54,17 +70,20 @@ describe 'supervisord' do it { should_not contain_file('/etc/init.d/supervisord') } end - describe 'on supported OS' + describe 'on supported OS' do context 'with Debian' do let(:facts) {{ :osfamily => 'Debian', :concat_basedir => concatdir }} it { should contain_file('/etc/init.d/supervisord') } + it { should contain_file('/etc/default/supervisor') } end context 'with RedHat' do let(:facts) {{ :osfamily => 'RedHat', :concat_basedir => concatdir }} it { should contain_file('/etc/init.d/supervisord') } + it { should contain_file('/etc/sysconfig/supervisord') } end end + end describe '#unix_socket' do context 'default' do @@ -89,10 +108,192 @@ describe 'supervisord' do describe '#run_path' do context 'default' do it { should_not contain_file('/var/run') } + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/pidfile=\/var\/run\/supervisord.pid$/) } end - context 'custom setting' do - let(:params) {{ :run_path => '/var/run/supervisord'}} - it { should contain_file('/var/run/supervisord') } + context 'is specified' do + let(:params) {{ :run_path => '/opt/supervisord/run' }} + it { should contain_file('/opt/supervisord/run') } + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/pidfile=\/opt\/supervisord\/run\/supervisord.pid$/) } + end + end + + describe '#log_path' do + context 'default' do + it { should contain_file('/var/log/supervisor') } + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/logfile=\/var\/log\/supervisor\/supervisord.log$/) } + end + context 'is specified' do + let(:params) {{ :log_path => '/opt/supervisord/logs' }} + it { should contain_file('/opt/supervisord/logs')} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/logfile=\/opt\/supervisord\/logs\/supervisord.log$/) } + end + end + + describe '#config_include' do + context 'default' do + it { should contain_file('/etc/supervisor.d') } + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/files=\/etc\/supervisor.d\/\*.conf$/) } + end + context 'is specified' do + let(:params) {{ :config_include => '/opt/supervisord/conf.d' }} + it { should contain_file('/opt/supervisord/conf.d') } + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/files=\/opt\/supervisord\/conf.d\/\*.conf$/) } + end + end + + describe '#config_dirs' do + context 'is specified' do + let(:params) {{ :config_dirs => ['/etc/supervisor.d/*.conf', '/opt/supervisor.d/*', '/usr/share/supervisor.d/*.config'] }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/files=\/etc\/supervisor.d\/\*.conf \/opt\/supervisor.d\/\* \/usr\/share\/supervisor.d\/\*.config$/) } + end + end + + describe '#config_file' do + context 'default' do + it { should contain_file('/etc/supervisord.conf') } + end + context 'is specified' do + let(:params) {{ :config_file => '/opt/supervisord/supervisor.conf' }} + it { should contain_file('/opt/supervisord/supervisor.conf') } + end + end + + describe '#nodaemon' do + context 'default' do + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/nodaemon=false$/) } + end + context 'true' do + let(:params) {{ :nodaemon => true }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/nodaemon=true$/) } + end + context 'invalid' do + let(:params) {{ :nodaemon => 'invalid' }} + it { expect { raise_error(Puppet::Error, /is not a boolean/) }} + end + end + + describe '#minfds' do + context 'default' do + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/minfds=1024$/) } + end + context 'specified' do + let(:params) {{ :minfds => 2048 }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/minfds=2048$/) } + end + context 'invalid' do + let(:params) {{ :minfds => 'string' }} + it { expect { raise_error(Puppet::Error, /invalid minfds/) }} + end + end + + describe '#minprocs' do + context 'default' do + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/minprocs=200$/) } + end + context 'specified' do + let(:params) {{ :minprocs => 300 }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/minprocs=300$/) } + end + context 'invalid' do + let(:params) {{ :minfds => 'string' }} + it { expect { raise_error(Puppet::Error, /invalid minprocs/) }} + end + end + + describe '#strip_ansi' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/strip_ansi$/) } + end + context 'true' do + let(:params) {{ :strip_ansi => true }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/strip_ansi=true$/) } + end + context 'invalid' do + let(:params) {{ :strip_ansi => 'string' }} + it { expect { raise_error(Puppet::Error, /is not a boolean/) }} + end + end + + describe '#user' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/user$/) } + end + context 'specified' do + let(:params) {{ :user => 'myuser' }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/user=myuser$/) } + end + end + + describe '#identifier' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/identifier$/) } + end + context 'specified' do + let(:params) {{ :identifier => 'myidentifier' }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/identifier=myidentifier$/) } + end + end + + describe '#directory' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/directory$/) } + end + context 'specified' do + let(:params) {{ :directory => '/opt/supervisord' }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/directory=\/opt\/supervisord$/) } + end + end + + describe '#nocleanup' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/nocleanup$/) } + end + context 'true' do + let(:params) {{ :nocleanup => true }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/nocleanup=true$/) } + end + context 'invalid' do + let(:params) {{ :nocleanup => 'string' }} + it { expect { raise_error(Puppet::Error, /is not a boolean/) }} + end + end + + describe '#childlogdir' do + context 'default' do + it { should_not contain_concat__fragment('supervisord_main') \ + .with_content(/childlogdir$/) } + end + context 'specified' do + let(:params) {{ :childlogdir => '/opt/supervisord/logdir' }} + it { should contain_concat__fragment('supervisord_main') \ + .with_content(/childlogdir=\/opt\/supervisord\/logdir$/) } + end + context 'invalid' do + let(:params) {{ :childlogdir => 'not_a_path' }} + it { expect { raise_error(Puppet::Error, /is not an absolute path/) }} end end end \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/eventlistener_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/eventlistener_spec.rb index 6e04f44f97b..1083b8a3230 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/eventlistener_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/eventlistener_spec.rb @@ -2,14 +2,85 @@ require 'spec_helper' describe 'supervisord::eventlistener', :type => :define do let(:title) {'foo'} - let(:default_params) {{ :command => 'bar', - :stdout_logfile => '/var/log/supervisor/eventlistener_foo.log', - :stderr_logfile => '/var/log/supervisor/eventlistener_foo.error', - }} - let(:params) { default_params } let(:facts) {{ :concat_basedir => '/var/lib/puppet/concat' }} + let(:default_params) do + { + :command => 'bar', + :process_name => '%(process_num)s', + :events => ['PROCESS_STATE', 'PROCESS_STATE_STARTING'], + :buffer_size => 10, + :numprocs => '1', + :numprocs_start => '0', + :priority => '999', + :autostart => true, + :autorestart => 'unexpected', + :startsecs => '1', + :startretries => '3', + :exitcodes => '0,2', + :stopsignal => 'TERM', + :stopwaitsecs => '10', + :stopasgroup => true, + :killasgroup => true, + :user => 'baz', + :redirect_stderr => true, + :stdout_logfile => 'eventlistener_foo.log', + :stdout_logfile_maxbytes => '50MB', + :stdout_logfile_backups => '10', + :stdout_events_enabled => true, + :stderr_logfile => 'eventlistener_foo.error', + :stderr_logfile_maxbytes => '50MB', + :stderr_logfile_backups => '10', + :stderr_events_enabled => true, + :environment => { 'env1' => 'value1', 'env2' => 'value2' }, + :directory => '/opt/supervisord/chroot', + :umask => '022', + :serverurl => 'AUTO' + } + end - it { should contain_supervisord__eventlistener('foo') } - it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/command=bar/) } + context 'default' do + let(:params) { default_params } + it { should contain_supervisord__eventlistener('foo') } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/\[eventlistener:foo\]/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/command=bar/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/process_name=\%\(process_num\)s/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/events=PROCESS_STATE,PROCESS_STATE_STARTING/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/buffer_size=10/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/numprocs=1/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/numprocs_start=0/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/priority=999/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/autostart=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/startsecs=1/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/startretries=3/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/exitcodes=0,2/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stopsignal=TERM/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stopwaitsecs=10/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stopasgroup=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/killasgroup=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/user=baz/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/redirect_stderr=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stdout_logfile=\/var\/log\/supervisor\/eventlistener_foo.log/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stdout_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stdout_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stdout_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stderr_logfile=\/var\/log\/supervisor\/eventlistener_foo.error/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stderr_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stderr_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/stderr_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/environment=env1='value1',env2='value2'/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/directory=\/opt\/supervisord\/chroot/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/umask=022/) } + it { should contain_file('/etc/supervisor.d/eventlistener_foo.conf').with_content(/serverurl=AUTO/) } + end + + context 'ensure_process_stopped' do + let(:params) { default_params.merge({ :ensure_process => 'stopped' }) } + it { should contain_supervisord__supervisorctl('stop_foo') } + end + + context 'ensure_process_removed' do + let(:params) { default_params.merge({ :ensure_process => 'removed' }) } + it { should contain_supervisord__supervisorctl('remove_foo') } + end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/fcgi_program_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/fcgi_program_spec.rb index 7fd8ab07b86..e01311be70d 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/fcgi_program_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/fcgi_program_spec.rb @@ -2,21 +2,87 @@ require 'spec_helper' describe 'supervisord::fcgi_program', :type => :define do let(:title) {'foo'} - let(:default_params) {{ :command => 'bar', - :socket => 'tcp://localhost:1000', - :stdout_logfile => '/var/log/supervisor/fcgi-program_foo.log', - :stderr_logfile => '/var/log/supervisor/fcgi-program_foo.error', - :user => 'baz' - }} - let(:params) { default_params } let(:facts) {{ :concat_basedir => '/var/lib/puppet/concat' }} + let(:default_params) do + { + :command => 'bar', + :socket => 'tcp://localhost:1000', + :process_name => '%(process_num)s', + :numprocs => '1', + :numprocs_start => '0', + :priority => '999', + :autostart => true, + :autorestart => 'unexpected', + :startsecs => '1', + :startretries => '3', + :exitcodes => '0,2', + :stopsignal => 'TERM', + :stopwaitsecs => '10', + :stopasgroup => true, + :killasgroup => true, + :user => 'baz', + :redirect_stderr => true, + :stdout_logfile => 'fcgi-program_foo.log', + :stdout_logfile_maxbytes => '50MB', + :stdout_logfile_backups => '10', + :stdout_capture_maxbytes => '0', + :stdout_events_enabled => true, + :stderr_logfile => 'fcgi-program_foo.error', + :stderr_logfile_maxbytes => '50MB', + :stderr_logfile_backups => '10', + :stderr_capture_maxbytes => '0', + :stderr_events_enabled => true, + :environment => { 'env1' => 'value1', 'env2' => 'value2' }, + :directory => '/opt/supervisord/chroot', + :umask => '022', + :serverurl => 'AUTO' + } + end - it { should contain_supervisord__fcgi_program('foo') } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/\[fcgi-program:foo\]/) } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/socket=tcp:\/\/localhost:1000/) } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/command=bar/) } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/user=baz/) } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_logfile=\/var\/log\/supervisor\/fcgi-program_foo.log/) } - it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_logfile=\/var\/log\/supervisor\/fcgi-program_foo.error/) } + context 'default' do + let(:params) { default_params } + it { should contain_supervisord__fcgi_program('foo') } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/\[fcgi-program:foo\]/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/socket=tcp:\/\/localhost:1000/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/command=bar/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/process_name=\%\(process_num\)s/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/numprocs=1/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/numprocs_start=0/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/priority=999/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/autostart=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/startsecs=1/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/startretries=3/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/exitcodes=0,2/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stopsignal=TERM/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stopwaitsecs=10/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stopasgroup=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/killasgroup=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/user=baz/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/redirect_stderr=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_logfile=\/var\/log\/supervisor\/fcgi-program_foo.log/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_capture_maxbytes=0/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stdout_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_logfile=\/var\/log\/supervisor\/fcgi-program_foo.error/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_capture_maxbytes=0/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/stderr_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/environment=env1='value1',env2='value2'/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/directory=\/opt\/supervisord\/chroot/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/umask=022/) } + it { should contain_file('/etc/supervisor.d/fcgi-program_foo.conf').with_content(/serverurl=AUTO/) } + end + + context 'ensure_process_stopped' do + let(:params) { default_params.merge({ :ensure_process => 'stopped' }) } + it { should contain_supervisord__supervisorctl('stop_foo') } + end + + context 'ensure_process_removed' do + let(:params) { default_params.merge({ :ensure_process => 'removed' }) } + it { should contain_supervisord__supervisorctl('remove_foo') } + end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/program_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/program_spec.rb index 077828bdfcf..e32c24ab2d5 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/program_spec.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/program_spec.rb @@ -2,19 +2,85 @@ require 'spec_helper' describe 'supervisord::program', :type => :define do let(:title) {'foo'} - let(:default_params) {{ :command => 'bar', - :stdout_logfile => '/var/log/supervisor/program_foo.log', - :stderr_logfile => '/var/log/supervisor/program_foo.error', - :user => 'baz' - }} - let(:params) { default_params } let(:facts) {{ :concat_basedir => '/var/lib/puppet/concat' }} + let(:default_params) do + { + :command => 'bar', + :process_name => '%(process_num)s', + :numprocs => '1', + :numprocs_start => '0', + :priority => '999', + :autostart => true, + :autorestart => 'unexpected', + :startsecs => '1', + :startretries => '3', + :exitcodes => '0,2', + :stopsignal => 'TERM', + :stopwaitsecs => '10', + :stopasgroup => true, + :killasgroup => true, + :user => 'baz', + :redirect_stderr => true, + :stdout_logfile => 'program_foo.log', + :stdout_logfile_maxbytes => '50MB', + :stdout_logfile_backups => '10', + :stdout_capture_maxbytes => '0', + :stdout_events_enabled => true, + :stderr_logfile => 'program_foo.error', + :stderr_logfile_maxbytes => '50MB', + :stderr_logfile_backups => '10', + :stderr_capture_maxbytes => '0', + :stderr_events_enabled => true, + :environment => { 'env1' => 'value1', 'env2' => 'value2' }, + :directory => '/opt/supervisord/chroot', + :umask => '022', + :serverurl => 'AUTO' + } + end - it { should contain_supervisord__program('foo') } - it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/\[program:foo\]/) } - it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/command=bar/) } - it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/user=baz/) } - it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_logfile=\/var\/log\/supervisor\/program_foo.log/) } - it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_logfile=\/var\/log\/supervisor\/program_foo.error/) } + context 'default' do + let(:params) { default_params } + it { should contain_supervisord__program('foo') } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/\[program:foo\]/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/command=bar/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/process_name=\%\(process_num\)s/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/numprocs=1/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/numprocs_start=0/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/priority=999/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/autostart=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/startsecs=1/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/startretries=3/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/exitcodes=0,2/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stopsignal=TERM/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stopwaitsecs=10/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stopasgroup=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/killasgroup=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/user=baz/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/redirect_stderr=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_logfile=\/var\/log\/supervisor\/program_foo.log/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_capture_maxbytes=0/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stdout_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_logfile=\/var\/log\/supervisor\/program_foo.error/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_logfile_maxbytes=50MB/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_logfile_backups=10/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_capture_maxbytes=0/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/stderr_events_enabled=true/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/environment=env1='value1',env2='value2'/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/directory=\/opt\/supervisord\/chroot/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/umask=022/) } + it { should contain_file('/etc/supervisor.d/program_foo.conf').with_content(/serverurl=AUTO/) } + end + + context 'ensure_process_stopped' do + let(:params) { default_params.merge({ :ensure_process => 'stopped' }) } + it { should contain_supervisord__supervisorctl('stop_foo') } + end + + context 'ensure_process_removed' do + let(:params) { default_params.merge({ :ensure_process => 'removed' }) } + it { should contain_supervisord__supervisorctl('remove_foo') } + end end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/supervisorctl.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/supervisorctl.rb new file mode 100644 index 00000000000..33cfd75efe9 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/defines/supervisorctl.rb @@ -0,0 +1,13 @@ +require 'spec_helper' + +describe 'supervisord::supervisorctl', :type => :define do + let(:title) {'command_foo'} + let(:default_params) {{ + :command => 'command', + :process => 'foo' + }} + let(:params) { default_params } + let(:facts) {{ :concat_basedir => '/var/lib/puppet/concat' }} + + it { should contain_supervisord__supervisorctl('command_foo') } +end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper.rb index 644f7c33ac0..745ad4a5493 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper.rb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper.rb @@ -7,3 +7,4 @@ RSpec.configure do |c| c.manifest_dir = File.join(fixture_path, 'manifests') end +at_exit { RSpec::Puppet::Coverage.report! } diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_acceptance.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_acceptance.rb new file mode 100644 index 00000000000..dcae2850d27 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/spec_helper_acceptance.rb @@ -0,0 +1,24 @@ +require 'beaker-rspec' + +hosts.each do |host| + # Install Puppet + install_puppet +end + +RSpec.configure do |c| + # Project root + proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..')) + + # Readable test descriptions + c.formatter = :documentation + + # Configure all nodes in nodeset + c.before :suite do + # Install module + puppet_module_install(:source => proj_root, :module_name => 'supervisord') + hosts.each do |host| + on host, puppet('module','install','puppetlabs-stdlib'), { :acceptable_exit_codes => [0,1] } + on host, puppet('module','install','puppetlabs-concat'), { :acceptable_exit_codes => [0,1] } + end + end +end \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/system/basic_spec.rb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/system/basic_spec.rb deleted file mode 100644 index 62cf7dd8c2e..00000000000 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/spec/system/basic_spec.rb +++ /dev/null @@ -1,120 +0,0 @@ -require 'spec_helper_system' - -describe 'basic install' do - - it 'class should work with no errors' do - pp = <<-EOS - class { 'supervisord': install_pip => true, install_init => true} - EOS - - puppet_apply(pp) do |r| - r.exit_code.should_not == 1 - r.refresh - r.exit_code.should be_zero - end - - shell("pgrep supervisord") do |r| - r.exit_code.should be_zero - end - - end -end - -describe 'add a program config' do - - it 'supervisord::program should install a program config' do - - pp = <<-EOS - include supervisord - supervisord::program { 'test': - command => 'echo', - priority => '100', - environment => { - 'HOME' => '/root', - 'PATH' => '/bin', - } - } - EOS - - puppet_apply(pp) do |r| - r.exit_code.should_not == 1 - r.refresh - r.exit_code.should be_zero - end - - shell("grep command=echo /etc/supervisor.d/program_test.conf") do |r| - r.exit_code.should be_zero - end - shell("grep priority=100 /etc/supervisor.d/program_test.conf") do |r| - r.exit_code.should be_zero - end - shell('grep "environment=" /etc/supervisor.d/program_test.conf') do |r| - r.exit_code.should be_zero - end - end -end - -describe 'add a fcgi-program config' do - - it 'supervisord::fcgi_program should install a program config' do - - pp = <<-EOS - include supervisord - supervisord::fcgi_program { 'test': - socket => 'tcp://localhost:1000', - command => 'echo', - priority => '100', - environment => { - 'HOME' => '/root', - 'PATH' => '/bin', - } - } - EOS - - puppet_apply(pp) do |r| - r.exit_code.should_not == 1 - r.refresh - r.exit_code.should be_zero - end - - shell("grep socket=tcp://localhost:1000 /etc/supervisor.d/fcgi-program_test.conf") do |r| - r.exit_code.should be_zero - end - shell("grep command=echo /etc/supervisor.d/fcgi-program_test.conf") do |r| - r.exit_code.should be_zero - end - shell("grep priority=100 /etc/supervisor.d/fcgi-program_test.conf") do |r| - r.exit_code.should be_zero - end - shell('grep "environment=" /etc/supervisor.d/fcgi-program_test.conf') do |r| - r.exit_code.should be_zero - end - end -end - -describe 'add a group config' do - - it 'supervisord::group should install a program config' do - - pp = <<-EOS - include supervisord - supervisord::group { 'test': - programs => ['program1', 'program2'], - priority => '100', - } - EOS - - puppet_apply(pp) do |r| - r.exit_code.should_not == 1 - r.refresh - r.exit_code.should be_zero - end - - shell('grep "programs=program1,program2" /etc/supervisor.d/group_test.conf') do |r| - r.exit_code.should be_zero - end - shell("grep priority=100 /etc/supervisor.d/fcgi-program_test.conf") do |r| - r.exit_code.should be_zero - end - end -end diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/eventlistener.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/eventlistener.erb index 4ee2b893419..9875c8ef5b2 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/eventlistener.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/eventlistener.erb @@ -39,8 +39,8 @@ exitcodes=<%= @exitcodes %> <% if @stopsignal -%> stopsignal=<%= @stopsignal %> <% end -%> -<% if @stopwaitsec -%> -stopwaitsec=<%= @stopwaitsec %> +<% if @stopwaitsecs -%> +stopwaitsecs=<%= @stopwaitsecs %> <% end -%> <% if @stopasgroup -%> stopasgroup=<%= @stopasgroup %> @@ -54,7 +54,7 @@ user=<%= @user %> <% if @redirect_stderr -%> redirect_stderr=<%= @redirect_stderr %> <% end -%> -stdout_logfile=<%= @stdout_logfile %> +stdout_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stdout_logfile %> <% if @stdout_logfile_maxbytes -%> stdout_logfile_maxbytes=<%= @stdout_logfile_maxbytes %> <% end -%> @@ -64,7 +64,7 @@ stdout_logfile_backups=<%= @stdout_logfile_backups %> <% if @stdout_events_enabled -%> stdout_events_enabled=<%= @stdout_events_enabled %> <% end -%> -stderr_logfile=<%= @stderr_logfile %> +stderr_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stderr_logfile %> <% if @stderr_logfile_maxbytes -%> stderr_logfile_maxbytes=<%= @stderr_logfile_maxbytes %> <% end -%> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/fcgi_program.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/fcgi_program.erb index a1478bce536..98a7fb1cb32 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/fcgi_program.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/fcgi_program.erb @@ -37,8 +37,8 @@ exitcodes=<%= @exitcodes %> <% if @stopsignal -%> stopsignal=<%= @stopsignal %> <% end -%> -<% if @stopwaitsec -%> -stopwaitsec=<%= @stopwaitsec %> +<% if @stopwaitsecs -%> +stopwaitsecs=<%= @stopwaitsecs %> <% end -%> <% if @stopasgroup -%> stopasgroup=<%= @stopasgroup %> @@ -53,7 +53,7 @@ user=<%= @user %> redirect_stderr=<%= @redirect_stderr %> <% end -%> <% if @stdout_logfile -%> -stdout_logfile=<%= @stdout_logfile %> +stdout_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stdout_logfile %> <% end -%> <% if @stdout_logfile_maxbytes -%> stdout_logfile_maxbytes=<%= @stdout_logfile_maxbytes %> @@ -68,7 +68,7 @@ stdout_capture_maxbytes=<%= @stdout_capture_maxbytes %> stdout_events_enabled=<%= @stdout_events_enabled %> <% end -%> <% if @stderr_logfile -%> -stderr_logfile=<%= @stderr_logfile %> +stderr_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stderr_logfile %> <% end -%> <% if @stderr_logfile_maxbytes -%> stderr_logfile_maxbytes=<%= @stderr_logfile_maxbytes %> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/program.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/program.erb index ca96d34d6ad..78002c87ca6 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/program.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/conf/program.erb @@ -30,8 +30,8 @@ exitcodes=<%= @exitcodes %> <% if @stopsignal -%> stopsignal=<%= @stopsignal %> <% end -%> -<% if @stopwaitsec -%> -stopwaitsec=<%= @stopwaitsec %> +<% if @stopwaitsecs -%> +stopwaitsecs=<%= @stopwaitsecs %> <% end -%> <% if @stopasgroup -%> stopasgroup=<%= @stopasgroup %> @@ -46,7 +46,7 @@ user=<%= @user %> redirect_stderr=<%= @redirect_stderr %> <% end -%> <% if @stdout_logfile -%> -stdout_logfile=<%= @stdout_logfile %> +stdout_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stdout_logfile %> <% end -%> <% if @stdout_logfile_maxbytes -%> stdout_logfile_maxbytes=<%= @stdout_logfile_maxbytes %> @@ -61,7 +61,7 @@ stdout_capture_maxbytes=<%= @stdout_capture_maxbytes %> stdout_events_enabled=<%= @stdout_events_enabled %> <% end -%> <% if @stderr_logfile -%> -stderr_logfile=<%= @stderr_logfile %> +stderr_logfile=<%= scope.lookupvar('supervisord::log_path') %>/<%= @stderr_logfile %> <% end -%> <% if @stderr_logfile_maxbytes -%> stderr_logfile_maxbytes=<%= @stderr_logfile_maxbytes %> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/debian_extra.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/Debian/defaults.erb similarity index 100% rename from dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/debian_extra.erb rename to dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/Debian/defaults.erb diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/debian_init.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/Debian/init.erb similarity index 93% rename from dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/debian_init.erb rename to dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/Debian/init.erb index b94f9337f59..f8bdb5ff854 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/debian_init.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/Debian/init.erb @@ -16,18 +16,22 @@ DAEMON=<%= @executable %> NAME=supervisord DESC=supervisor -test -x $DAEMON || exit 0 +# Tests if executable exists +if [ ! -x $DAEMON ] ; then + echo "Executable not found ${DAEMON}" + exit 1 +fi LOGDIR=<%= @log_path %> -PIDFILE=<%= @pid_file %> +PIDFILE=<%= @run_path %>/<%= @pid_file %> DODTIME=5 # Time to wait for the server to die, in seconds # If this value is set too low you might not # let some servers to die gracefully and # 'restart' will not work # Include supervisor defaults if available -if [ -f /etc/default/supervisor ] ; then - . /etc/default/supervisor +if [ -f <%= @init_defaults %> ] ; then + . <%= @init_defaults %> fi set -e diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_extra.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/defaults.erb similarity index 81% rename from dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_extra.erb rename to dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/defaults.erb index b892c2d6203..0d7862d0233 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_extra.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/defaults.erb @@ -5,4 +5,4 @@ set -a # should probably put both of these options as runtime arguments OPTIONS="-c <%= @config_file %>" -PIDFILE=<%= @pid_file %> +PIDFILE=<%= @run_path %><%= @pid_file %> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_init.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/init.erb similarity index 87% rename from dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_init.erb rename to dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/init.erb index 1dc2da2aff1..617f3eed93b 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/redhat_init.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/init/RedHat/init.erb @@ -13,18 +13,26 @@ # xmlrpc interface as well as a few other nifty features. # processname: supervisord # config: <%= @config_file %> -# pidfile: <%= @pid_file %> +# pidfile: <%= @run_path %>/<%= @pid_file %> # # source function library . /etc/rc.d/init.d/functions # source system settings -[ -e <%= @init_extras %> ] && . <%= @init_extras %> +[ -e <%= @init_defaults %> ] && . <%= @init_defaults %> RETVAL=0 -DAEMON=/usr/bin/supervisord +DAEMON=<%= @executable %> +CTL=<%= @executable_ctl %> DESC=supervisord +PIDFILE=<%= @run_path %>/<%= @pid_file %> + +# Tests if executable exists +if [ ! -x $DAEMON ] ; then + echo "Executable not found ${DAEMON}" + exit 1 +fi running_pid() { @@ -88,7 +96,7 @@ case "$1" in restart ;; reload) - /usr/bin/supervisorctl $OPTIONS reload + $CTL $OPTIONS reload RETVAL=$? ;; condrestart) @@ -109,4 +117,4 @@ case "$1" in exit 1 esac -exit $RETVAL \ No newline at end of file +exit $RETVAL diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_main.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_main.erb index 1baf5607a2f..8ab8fee51df 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_main.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_main.erb @@ -1,9 +1,9 @@ [supervisord] -logfile=<%= @log_file %> -pidfile=<%= @pid_file %> +logfile=<%= @log_path %>/<%= @log_file %> +pidfile=<%= @run_path %>/<%= @pid_file %> nodaemon=<%= @nodaemon %> minfds=<%= @minfds %> -minfds=<%= @minprocs %> +minprocs=<%= @minprocs %> umask=<%= @umask %> <% if @strip_ansi -%> strip_ansi=<%= @strip_ansi %> @@ -12,7 +12,7 @@ strip_ansi=<%= @strip_ansi %> user=<%= @user %> <% end -%> <% if @identifier -%> -indentifier=<%= @identifier %> +identifier=<%= @identifier %> <% end -%> <% if @directory -%> directory=<%= @directory %> @@ -31,4 +31,4 @@ environment=<%= @env_string %> supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [include] -files=<%= @config_include %>/*.conf +files=<%= @config_include_string %> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_unix.erb b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_unix.erb index 414e75198ba..39e85199916 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_unix.erb +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/templates/supervisord_unix.erb @@ -1,5 +1,5 @@ [unix_http_server] -file=<%= @unix_socket_file %> +file=<%= @run_path %>/<%= @unix_socket_file %> chmod=<%= @unix_socket_mode %> chown=<%= @unix_socket_owner %>:<%= @unix_socket_group %> <% if @unix_auth -%> @@ -8,7 +8,7 @@ password=<%= @unix_socket_password %> <% end -%> [supervisorctl] -serverurl=unix://<%= @unix_socket_file %> +serverurl=unix://<%= @run_path %>/<%= @unix_socket_file %> <% if @unix_auth -%> username=<%= @unix_username %> password=<%= @unix_password %> diff --git a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/tests/program.pp b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/tests/program.pp index 6c789c96dc1..0d45ebe1b3d 100644 --- a/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/tests/program.pp +++ b/dev/vagrant/dolibarrdev/puphpet/puppet/modules/supervisord/tests/program.pp @@ -1,9 +1,35 @@ supervisord::program { 'myprogram': - command => 'command --args', - priority => '100', - environment => { + command => 'command --args', + process_name => '%(process_num)s', + numprocs => '1', + numprocs_start => '0', + priority => '999', + autostart => true, + autorestart => 'unexpected', + startsecs => '1', + startretries => '3', + exitcodes => '0,2', + stopsignal => 'TERM', + stopwaitsecs => '10', + stopasgroup => false, + killasgroup => false, + redirect_stderr => false, + stdout_logfile => 'program_foo.log', + stdout_logfile_maxbytes => '50MB', + stdout_logfile_backups => '10', + stdout_capture_maxbytes => '0', + stdout_events_enabled => false, + stderr_logfile => 'program_foo.error', + stderr_logfile_maxbytes => '50MB', + stderr_logfile_backups => '10', + stderr_capture_maxbytes => '0', + stderr_events_enabled => false, + environment => { 'HOME' => '/home/myuser', 'PATH' => '/bin:/sbin:/usr/bin:/usr/sbin', 'SECRET' => 'mysecret' - } + }, + directory => undef, + umask => '022', + serverurl => 'AUTO' } \ No newline at end of file diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/execute-files.sh b/dev/vagrant/dolibarrdev/puphpet/shell/execute-files.sh index 06713c2ee99..198d7e2dfb7 100644 --- a/dev/vagrant/dolibarrdev/puphpet/shell/execute-files.sh +++ b/dev/vagrant/dolibarrdev/puphpet/shell/execute-files.sh @@ -4,17 +4,27 @@ export DEBIAN_FRONTEND=noninteractive VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') -shopt -s nullglob -files=("${VAGRANT_CORE_FOLDER}"/files/exec-once/*) +EXEC_ONCE_DIR="$1" +EXEC_ALWAYS_DIR="$2" -if [[ ! -f '/.puphpet-stuff/exec-once-ran' && (${#files[@]} -gt 0) ]]; then - echo 'Running files in files/exec-once' - find "${VAGRANT_CORE_FOLDER}/files/exec-once" -maxdepth 1 -not -path '*/\.*' -type f \( ! -iname "empty" \) -exec chmod +x '{}' \; -exec {} \; - echo 'Finished running files in files/exec-once' - echo 'To run again, delete file /.puphpet-stuff/exec-once-ran' - touch /.puphpet-stuff/exec-once-ran +shopt -s nullglob +files=("${VAGRANT_CORE_FOLDER}"/files/"${EXEC_ONCE_DIR}"/*) + +if [[ (${#files[@]} -gt 0) ]]; then + echo "Running files in files/${EXEC_ONCE_DIR}" + + if [ ! -d "/.puphpet-stuff/${EXEC_ONCE_DIR}-ran" ]; then + mkdir "/.puphpet-stuff/${EXEC_ONCE_DIR}-ran" + echo "Created directory /.puphpet-stuff/${EXEC_ONCE_DIR}-ran" + fi + + find "${VAGRANT_CORE_FOLDER}/files/${EXEC_ONCE_DIR}" -maxdepth 1 -not -path '/.*' -type f \( ! -iname "empty" \) -exec cp -n '{}' "/.puphpet-stuff/${EXEC_ONCE_DIR}-ran" \; + find "/.puphpet-stuff/${EXEC_ONCE_DIR}-ran" -maxdepth 1 -type f -exec chmod +x '{}' \; -exec ls {} \; | sort | xargs -r0 sh -c + echo "Finished running files in files/${EXEC_ONCE_DIR}" + echo "To run again, delete file(s) you want rerun in /.puphpet-stuff/${EXEC_ONCE_DIR}-ran or the whole folder to rerun all" fi -echo 'Running files in files/exec-always' -find "${VAGRANT_CORE_FOLDER}/files/exec-always" -maxdepth 1 -not -path '*/\.*' -type f \( ! -iname "empty" \) -exec chmod +x '{}' \; -exec {} \; -echo 'Finished running files in files/exec-always' +echo "Running files in files/${EXEC_ALWAYS_DIR}" +find "${VAGRANT_CORE_FOLDER}/files/${EXEC_ALWAYS_DIR}" -maxdepth 1 -not -path '/.*' -type f \( ! -iname "empty" \) -exec chmod +x '{}' \; -exec ls {} \; | sort | xargs -r0 sh -c +echo "Finished running files in files/${EXEC_ALWAYS_DIR}" + diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/hostsupdater-notice.txt b/dev/vagrant/dolibarrdev/puphpet/shell/hostsupdater-notice.txt new file mode 100644 index 00000000000..ce3331b3ced --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/shell/hostsupdater-notice.txt @@ -0,0 +1,4 @@ +=============================================================================== +You have the Vagrant::Hostsupdater plugin installed. You may be required to +enter your host's root/privileged password below to continue! +=============================================================================== diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/important-notices.sh b/dev/vagrant/dolibarrdev/puphpet/shell/important-notices.sh index bd1bb95cabe..21486cd3b93 100644 --- a/dev/vagrant/dolibarrdev/puphpet/shell/important-notices.sh +++ b/dev/vagrant/dolibarrdev/puphpet/shell/important-notices.sh @@ -2,8 +2,10 @@ VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') -if [[ ! -f '/.puphpet-stuff/displayed-important-notices' ]]; then - cat "${VAGRANT_CORE_FOLDER}/shell/important-notices.txt" - - touch '/.puphpet-stuff/displayed-important-notices' +if [[ -f '/.puphpet-stuff/displayed-important-notices' ]]; then + exit 0 fi + +cat "${VAGRANT_CORE_FOLDER}/shell/important-notices.txt" + +touch '/.puphpet-stuff/displayed-important-notices' diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/initial-setup.sh b/dev/vagrant/dolibarrdev/puphpet/shell/initial-setup.sh index 8fbfe3a2014..e653f8991c1 100644 --- a/dev/vagrant/dolibarrdev/puphpet/shell/initial-setup.sh +++ b/dev/vagrant/dolibarrdev/puphpet/shell/initial-setup.sh @@ -8,6 +8,8 @@ OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID) CODENAME=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" CODENAME) cat "${VAGRANT_CORE_FOLDER}/shell/self-promotion.txt" +printf "\n" +echo "" if [[ ! -d '/.puphpet-stuff' ]]; then mkdir '/.puphpet-stuff' @@ -17,91 +19,49 @@ fi touch '/.puphpet-stuff/vagrant-core-folder.txt' echo "${VAGRANT_CORE_FOLDER}" > '/.puphpet-stuff/vagrant-core-folder.txt' -if [[ ! -f '/.puphpet-stuff/initial-setup-base-packages' ]]; then - if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then - echo 'Running initial-setup apt-get update' - apt-get update >/dev/null - echo 'Finished running initial-setup apt-get update' - - echo 'Installing git' - apt-get -q -y install git-core >/dev/null - echo 'Finished installing git' - - if [[ "${CODENAME}" == 'lucid' || "${CODENAME}" == 'precise' ]]; then - echo 'Installing basic curl packages (Ubuntu only)' - apt-get install -y libcurl3 libcurl4-gnutls-dev curl >/dev/null - echo 'Finished installing basic curl packages (Ubuntu only)' - fi - - echo 'Installing rubygems' - apt-get install -y rubygems >/dev/null - echo 'Finished installing rubygems' - - echo 'Installing base packages for r10k' - apt-get install -y build-essential ruby-dev >/dev/null - gem install json >/dev/null - echo 'Finished installing base packages for r10k' - - if [ "${OS}" == 'ubuntu' ]; then - echo 'Updating libgemplugin-ruby (Ubuntu only)' - apt-get install -y libgemplugin-ruby >/dev/null - echo 'Finished updating libgemplugin-ruby (Ubuntu only)' - fi - - if [ "${CODENAME}" == 'lucid' ]; then - echo 'Updating rubygems (Ubuntu Lucid only)' - gem install rubygems-update >/dev/null 2>&1 - /var/lib/gems/1.8/bin/update_rubygems >/dev/null 2>&1 - echo 'Finished updating rubygems (Ubuntu Lucid only)' - fi - - echo 'Installing r10k' - gem install r10k >/dev/null 2>&1 - echo 'Finished installing r10k' - - touch '/.puphpet-stuff/initial-setup-base-packages' - elif [[ "${OS}" == 'centos' ]]; then - echo 'Running initial-setup yum update' - perl -p -i -e 's@enabled=1@enabled=0@gi' /etc/yum/pluginconf.d/fastestmirror.conf - perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/os/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo - perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/updates/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo - perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/extras/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/extras/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo - - yum -y --nogpgcheck install 'http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm' >/dev/null - yum -y --nogpgcheck install 'https://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm' >/dev/null - yum -y install centos-release-SCL >/dev/null - yum clean all >/dev/null - yum -y check-update >/dev/null - echo 'Finished running initial-setup yum update' - - echo 'Installing git' - yum -y install git >/dev/null - echo 'Finished installing git' - - echo 'Updating to Ruby 1.9.3' - yum -y install centos-release-SCL >/dev/null 2>&1 - yum remove ruby >/dev/null 2>&1 - yum -y install ruby193 ruby193-ruby-irb ruby193-ruby-doc ruby193-libyaml rubygems >/dev/null 2>&1 - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/dependencies/x86_64/ruby-rgen-0.6.5-2.el6.noarch.rpm' >/dev/null 2>&1 - gem update --system >/dev/null 2>&1 - gem install haml >/dev/null 2>&1 - - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/products/x86_64/hiera-1.3.2-1.el6.noarch.rpm' >/dev/null - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/products/x86_64/facter-1.7.5-1.el6.x86_64.rpm' >/dev/null - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/dependencies/x86_64/rubygem-json-1.5.5-1.el6.x86_64.rpm' >/dev/null - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/dependencies/x86_64/ruby-json-1.5.5-1.el6.x86_64.rpm' >/dev/null - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/dependencies/x86_64/ruby-shadow-2.2.0-2.el6.x86_64.rpm' >/dev/null - yum -y --nogpgcheck install 'https://yum.puppetlabs.com/el/6/dependencies/x86_64/ruby-augeas-0.4.1-3.el6.x86_64.rpm' >/dev/null - echo 'Finished updating to Ruby 1.9.3' - - echo 'Installing basic development tools (CentOS)' - yum -y groupinstall 'Development Tools' >/dev/null - echo 'Finished installing basic development tools (CentOS)' - - echo 'Installing r10k' - gem install r10k >/dev/null 2>&1 - echo 'Finished installing r10k' - - touch '/.puphpet-stuff/initial-setup-base-packages' - fi +if [[ -f '/.puphpet-stuff/initial-setup-base-packages' ]]; then + exit 0 fi + +if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then + echo 'Running initial-setup apt-get update' + apt-get update >/dev/null + echo 'Finished running initial-setup apt-get update' + + echo 'Installing git' + apt-get -y install git-core >/dev/null + echo 'Finished installing git' + + if [[ "${CODENAME}" == 'lucid' || "${CODENAME}" == 'precise' ]]; then + echo 'Installing basic curl packages' + apt-get -y install libcurl3 libcurl4-gnutls-dev curl >/dev/null + echo 'Finished installing basic curl packages' + fi + + echo 'Installing build-essential package' + apt-get -y install build-essential >/dev/null + echo 'Finished installing build-essential packages' +elif [[ "${OS}" == 'centos' ]]; then + echo 'Adding repos: elrep, epel, scl' + perl -p -i -e 's@enabled=1@enabled=0@gi' /etc/yum/pluginconf.d/fastestmirror.conf + perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/os/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo + perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/updates/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo + perl -p -i -e 's@#baseurl=http://mirror.centos.org/centos/\$releasever/extras/\$basearch/@baseurl=http://mirror.rackspace.com/CentOS//\$releasever/extras/\$basearch/\nenabled=1@gi' /etc/yum.repos.d/CentOS-Base.repo + + yum -y --nogpgcheck install 'http://www.elrepo.org/elrepo-release-6-6.el6.elrepo.noarch.rpm' >/dev/null + yum -y --nogpgcheck install 'https://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm' >/dev/null + yum -y install centos-release-SCL >/dev/null + yum clean all >/dev/null + yum -y check-update >/dev/null + echo 'Finished adding repos: elrep, epel, scl' + + echo 'Installing git' + yum -y install git >/dev/null + echo 'Finished installing git' + + echo 'Installing Development Tools' + yum -y groupinstall 'Development Tools' >/dev/null + echo 'Finished installing Development Tools' +fi + +touch '/.puphpet-stuff/initial-setup-base-packages' diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/install-puppet.sh b/dev/vagrant/dolibarrdev/puphpet/shell/install-puppet.sh new file mode 100644 index 00000000000..93f1c32c6c7 --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/shell/install-puppet.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +export DEBIAN_FRONTEND=noninteractive + +VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') + +OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID) +RELEASE=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" RELEASE) +CODENAME=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" CODENAME) + +if [[ -f '/.puphpet-stuff/install-puppet' ]]; then + exit 0 +fi + +if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then + apt-get -y install augeas-tools libaugeas-dev +elif [[ "${OS}" == 'centos' ]]; then + yum -y install augeas-devel +fi + +echo 'Installing Puppet requirements' +/usr/bin/gem install haml hiera facter json ruby-augeas +echo 'Finished installing Puppet requirements' + +echo 'Installing Puppet 3.4.3' +/usr/bin/gem install puppet --version 3.4.3 + +if [[ -f '/usr/bin/puppet' ]]; then + mv /usr/bin/puppet /usr/bin/puppet-old +fi + +ln -s /usr/local/rvm/wrappers/default/puppet /usr/bin/puppet +echo 'Finished installing Puppet 3.4.3' + +touch '/.puphpet-stuff/install-puppet' diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/install-ruby.sh b/dev/vagrant/dolibarrdev/puphpet/shell/install-ruby.sh new file mode 100644 index 00000000000..d1b94e37f7d --- /dev/null +++ b/dev/vagrant/dolibarrdev/puphpet/shell/install-ruby.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +export DEBIAN_FRONTEND=noninteractive + +VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') + +OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID) +RELEASE=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" RELEASE) +CODENAME=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" CODENAME) + +if [[ -f '/.puphpet-stuff/install-ruby' ]]; then + exit 0 +fi + +if [[ -f '/usr/local/rvm/wrappers/default/ruby' ]]; then + RUBY_VERSION=$(/usr/local/rvm/wrappers/default/ruby --version); + if [ "grep '1.9.3' ${RUBY_VERSION}" ]; then + touch '/.puphpet-stuff/install-ruby' + exit 0 + fi +fi + +echo 'Installing Ruby 1.9.3 using RVM' + +curl -sSL https://get.rvm.io | bash -s stable --ruby=1.9.3 +source /usr/local/rvm/scripts/rvm + +if [[ -f '/usr/bin/ruby' ]]; then + mv /usr/bin/ruby /usr/bin/ruby-old +fi + +if [[ -f '/usr/bin/gem' ]]; then + mv /usr/bin/gem /usr/bin/gem-old +fi + +ln -s /usr/local/rvm/wrappers/default/ruby /usr/bin/ruby +ln -s /usr/local/rvm/wrappers/default/gem /usr/bin/gem + +gem update --system >/dev/null + +touch '/.puphpet-stuff/install-ruby' + +echo 'Finished install Ruby 1.9.3 using RVM' diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/os-detect.sh b/dev/vagrant/dolibarrdev/puphpet/shell/os-detect.sh index 3f679008fe8..5a73825dd59 100644 --- a/dev/vagrant/dolibarrdev/puphpet/shell/os-detect.sh +++ b/dev/vagrant/dolibarrdev/puphpet/shell/os-detect.sh @@ -1,36 +1,32 @@ #!/bin/bash -# Try and get debian operating system -# id, codename, and release - TYPE=$(echo "$1" | tr '[A-Z]' '[a-z]') OS=$(uname) ID='unknown' CODENAME='unknown' RELEASE='unknown' +ARCH='unknown' -if [ "${OS}" == 'Linux' ]; then - # detect centos - grep 'centos' /etc/issue -i -q - if [ $? = '0' ]; then - ID='centos' - RELEASE=$(cat /etc/redhat-release | grep -o 'release [0-9]' | cut -d " " -f2) - # could be debian or ubuntu - elif [ $(which lsb_release) ]; then - ID=$(lsb_release -i | cut -f2) - CODENAME=$(lsb_release -c | cut -f2) - RELEASE=$(lsb_release -r | cut -f2) - elif [ -f '/etc/lsb-release' ]; then - ID=$(cat /etc/lsb-release | grep DISTRIB_ID | cut -d "=" -f2) - CODENAME=$(cat /etc/lsb-release | grep DISTRIB_CODENAME | cut -d "=" -f2) - RELEASE=$(cat /etc/lsb-release | grep DISTRIB_RELEASE | cut -d "=" -f2) - elif [ -f '/etc/issue' ]; then - ID=$(head -1 /etc/issue | cut -d " " -f1) - if [ -f '/etc/debian_version' ]; then - RELEASE=$(/dev/null -echo 'Finished running update r10k' diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/ssh-keygen.sh b/dev/vagrant/dolibarrdev/puphpet/shell/ssh-keygen.sh index 6bb7614f9c6..ef00495b2b6 100644 --- a/dev/vagrant/dolibarrdev/puphpet/shell/ssh-keygen.sh +++ b/dev/vagrant/dolibarrdev/puphpet/shell/ssh-keygen.sh @@ -5,37 +5,76 @@ VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID) VAGRANT_SSH_USERNAME=$(echo "$1") -if [[ ! -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa" ]]; then - ssh-keygen -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa" -P "" +function create_key() +{ + BASE_KEY_NAME=$(echo "$1") - if [[ ! -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.ppk" ]]; then - if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then - apt-get install -y putty-tools >/dev/null - elif [ "${OS}" == 'centos' ]; then - yum -y install putty >/dev/null + if [[ ! -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/${BASE_KEY_NAME}" ]]; then + ssh-keygen -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/${BASE_KEY_NAME}" -P "" + + if [[ ! -f "${VAGRANT_CORE_FOLDER}/files/dot/ssh/${BASE_KEY_NAME}.ppk" ]]; then + if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then + apt-get install -y putty-tools >/dev/null + elif [ "${OS}" == 'centos' ]; then + yum -y install putty >/dev/null + fi + + puttygen "${VAGRANT_CORE_FOLDER}/files/dot/ssh/${BASE_KEY_NAME}" -O private -o "${VAGRANT_CORE_FOLDER}/files/dot/ssh/${BASE_KEY_NAME}.ppk" fi - puttygen "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa" -O private -o "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.ppk" + echo "Your private key for SSH-based authentication has been saved to 'puphpet/files/dot/ssh/${BASE_KEY_NAME}'!" + else + echo "Pre-existing private key found at 'puphpet/files/dot/ssh/${BASE_KEY_NAME}'" fi +} - echo 'Your private key for SSH-based authentication have been saved to "puphpet/files/dot/ssh/"!' -else - echo 'Using pre-existing private key at "puphpet/files/dot/ssh/id_rsa"' +create_key 'root_id_rsa' +create_key 'id_rsa' + +PUBLIC_SSH_KEY=$(cat "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub") + +echo 'Adding generated key to /root/.ssh/id_rsa' +echo 'Adding generated key to /root/.ssh/id_rsa.pub' +echo 'Adding generated key to /root/.ssh/authorized_keys' + +mkdir -p /root/.ssh + +cp "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa" '/root/.ssh/' +cp "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" '/root/.ssh/' + +if [[ ! -f '/root/.ssh/authorized_keys' ]] || ! grep -q "${PUBLIC_SSH_KEY}" '/root/.ssh/authorized_keys'; then + cat "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" >> '/root/.ssh/authorized_keys' fi -echo 'Adding generated key to /root/.ssh/authorized_keys' -mkdir -p /root/.ssh -cat "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" > '/root/.ssh/authorized_keys' +chown -R root '/root/.ssh' +chgrp -R root '/root/.ssh' +chmod 700 '/root/.ssh' +chmod 644 '/root/.ssh/id_rsa.pub' +chmod 600 '/root/.ssh/id_rsa' chmod 600 '/root/.ssh/authorized_keys' if [ "${VAGRANT_SSH_USERNAME}" != 'root' ]; then VAGRANT_SSH_FOLDER="/home/${VAGRANT_SSH_USERNAME}/.ssh"; - echo "Adding generated key to ${VAGRANT_SSH_FOLDER}/authorized_keys" - cat "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" > "${VAGRANT_SSH_FOLDER}/authorized_keys" - chown "${VAGRANT_SSH_USERNAME}" "${VAGRANT_SSH_FOLDER}/authorized_keys" - chgrp "${VAGRANT_SSH_USERNAME}" "${VAGRANT_SSH_FOLDER}/authorized_keys" - chmod 600 "${VAGRANT_SSH_FOLDER}/authorized_keys" -fi + mkdir -p "${VAGRANT_SSH_FOLDER}" -passwd -d vagrant >/dev/null + echo "Adding generated key to ${VAGRANT_SSH_FOLDER}/id_rsa" + echo "Adding generated key to ${VAGRANT_SSH_FOLDER}/id_rsa.pub" + echo "Adding generated key to ${VAGRANT_SSH_FOLDER}/authorized_keys" + + cp "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa" "${VAGRANT_SSH_FOLDER}/id_rsa" + cp "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" "${VAGRANT_SSH_FOLDER}/id_rsa.pub" + + if [[ ! -f "${VAGRANT_SSH_FOLDER}/authorized_keys" ]] || ! grep -q "${PUBLIC_SSH_KEY}" "${VAGRANT_SSH_FOLDER}/authorized_keys"; then + cat "${VAGRANT_CORE_FOLDER}/files/dot/ssh/id_rsa.pub" >> "${VAGRANT_SSH_FOLDER}/authorized_keys" + fi + + chown -R "${VAGRANT_SSH_USERNAME}" "${VAGRANT_SSH_FOLDER}" + chgrp -R "${VAGRANT_SSH_USERNAME}" "${VAGRANT_SSH_FOLDER}" + chmod 700 "${VAGRANT_SSH_FOLDER}" + chmod 644 "${VAGRANT_SSH_FOLDER}/id_rsa.pub" + chmod 600 "${VAGRANT_SSH_FOLDER}/id_rsa" + chmod 600 "${VAGRANT_SSH_FOLDER}/authorized_keys" + + passwd -d "${VAGRANT_SSH_USERNAME}" >/dev/null +fi diff --git a/dev/vagrant/dolibarrdev/puphpet/shell/update-puppet.sh b/dev/vagrant/dolibarrdev/puphpet/shell/update-puppet.sh deleted file mode 100644 index f8c1f5d2256..00000000000 --- a/dev/vagrant/dolibarrdev/puphpet/shell/update-puppet.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash - -export DEBIAN_FRONTEND=noninteractive - -VAGRANT_CORE_FOLDER=$(cat '/.puphpet-stuff/vagrant-core-folder.txt') - -OS=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" ID) -RELEASE=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" RELEASE) -CODENAME=$(/bin/bash "${VAGRANT_CORE_FOLDER}/shell/os-detect.sh" CODENAME) - -if [[ ! -f '/.puphpet-stuff/update-puppet' ]]; then - if [ "${OS}" == 'debian' ] || [ "${OS}" == 'ubuntu' ]; then - echo "Downloading http://apt.puppetlabs.com/puppetlabs-release-${CODENAME}.deb" - wget --quiet --tries=5 --connect-timeout=10 -O "/.puphpet-stuff/puppetlabs-release-${CODENAME}.deb" "http://apt.puppetlabs.com/puppetlabs-release-${CODENAME}.deb" - echo "Finished downloading http://apt.puppetlabs.com/puppetlabs-release-${CODENAME}.deb" - - dpkg -i "/.puphpet-stuff/puppetlabs-release-${CODENAME}.deb" >/dev/null - - echo 'Running update-puppet apt-get update' - apt-get update >/dev/null - echo 'Finished running update-puppet apt-get update' - - echo 'Updating Puppet to version 3.4.x' - apt-get install -y puppet-common=3.4.* puppet=3.4.* >/dev/null - apt-mark hold puppet puppet-common >/dev/null - PUPPET_VERSION=$(puppet help | grep 'Puppet v') - echo "Finished updating puppet to latest version: ${PUPPET_VERSION}" - - touch '/.puphpet-stuff/update-puppet' - elif [ "${OS}" == 'centos' ]; then - echo "Downloading http://yum.puppetlabs.com/el/${RELEASE}/products/x86_64/puppet-3.4.3-1.el6.noarch.rpm" - yum -y --nogpgcheck install "http://yum.puppetlabs.com/el/${RELEASE}/products/x86_64/puppet-3.4.3-1.el6.noarch.rpm" >/dev/null - echo "Finished downloading http://yum.puppetlabs.com/el/${RELEASE}/products/x86_64/puppet-3.4.3-1.el6.noarch.rpm" - - echo 'Installing/Updating Puppet to version 3.4.x' - yum -y install yum-versionlock puppet >/dev/null - yum versionlock puppet - PUPPET_VERSION=$(puppet help | grep 'Puppet v') - echo "Finished installing/updating puppet to version: ${PUPPET_VERSION}" - - touch '/.puphpet-stuff/update-puppet' - fi -fi diff --git a/htdocs/.gitignore b/htdocs/.gitignore index e7d542c9320..3cba3ce99cd 100644 --- a/htdocs/.gitignore +++ b/htdocs/.gitignore @@ -2,6 +2,7 @@ /custom* /extensions* /nltechno* +/ancot* /teclib* /bootstrap* /google* diff --git a/htdocs/accountancy/admin/account.php b/htdocs/accountancy/admin/account.php new file mode 100644 index 00000000000..0c2a825604b --- /dev/null +++ b/htdocs/accountancy/admin/account.php @@ -0,0 +1,223 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/account.php + * \ingroup Accounting Expert + * \brief List accounting account + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("accountancy"); + +$mesg = ''; +$action = GETPOST('action'); +$id = GETPOST('id', 'int'); +$rowid = GETPOST('rowid', 'int'); +$search_account = GETPOST("search_account"); +$search_label = GETPOST("search_label"); +$search_accountparent = GETPOST("search_accountparent"); +$search_pcgtype = GETPOST("search_pcgtype"); +$search_pcgsubtype = GETPOST("search_pcgsubtype"); + +// Security check +if (!$user->admin) + accessforbidden(); + +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'sortorder'); +$limit = $conf->liste_limit; +$page = GETPOST("page", 'int'); +if ($page == - 1) { + $page = 0; +} +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) + $sortfield = "aa.account_number"; +if (! $sortorder) + $sortorder = "ASC"; + +if ($action == 'delete') { + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id, $langs->trans('DeleteAccount'), $langs->trans('ConfirmDeleteAccount'), 'confirm_delete', '', 0, 1); + print $formconfirm; +} + +$accounting = new AccountingAccount($db); + +if ($action == 'disable') { + if ($accounting->fetch($id)) { + $result = $accounting->account_desactivate($id); + } + + $action = 'update'; + if ($result < 0) { + setEventMessage($accounting->error, 'errors'); + } +} else if ($action == 'enable') { + if ($accounting->fetch($id)) { + $result = $accounting->account_activate($id); + } + $action = 'update'; + if ($result < 0) { + setEventMessage($accounting->error, 'errors'); + } +} + +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_account=""; + $search_label=""; + $search_accountparent=""; + $search_pcgtype=""; + $search_pcgsubtype=""; +} + +/* + * View + * + */ +llxHeader('', $langs->trans("ListAccounts")); + +$pcgver = $conf->global->CHARTOFACCOUNTS; + +$sql = "SELECT aa.rowid, aa.fk_pcg_version, aa.pcg_type, aa.pcg_subtype, aa.account_number, aa.account_parent , aa.label, aa.active "; +$sql .= " FROM " . MAIN_DB_PREFIX . "accountingaccount as aa, " . MAIN_DB_PREFIX . "accounting_system as asy"; +$sql .= " WHERE aa.fk_pcg_version = asy.pcg_version"; +$sql .= " AND asy.rowid = " . $pcgver; + +if (strlen(trim($search_account))) { + $sql .= " AND aa.account_number like '%" . $search_account . "%'"; +} +if (strlen(trim($search_label))) { + $sql .= " AND aa.label like '%" . $search_label . "%'"; +} +if (strlen(trim($search_accountparent))) { + $sql .= " AND aa.account_parent like '%" . $search_accountparent . "%'"; +} +if (strlen(trim($search_pcgtype))) { + $sql .= " AND aa.pcg_type like '%" . $search_pcgtype . "%'"; +} +if (strlen(trim($search_pcgsubtype))) { + $sql .= " AND aa.pcg_subtype like '%" . $search_pcgsubtype . "%'"; +} + +$sql .= $db->order($sortfield, $sortorder); +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/admin/account.php:: $sql=' . $sql); +$result = $db->query($sql); + +if ($result) { + $num = $db->num_rows($result); + + print_barre_liste($langs->trans('ListAccounts'), $page, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', $num); + + $i = 0; + + print '
'; + + print '
'; + + print '' . $langs->trans("Addanaccount") . ''; + print '' . $langs->trans("ImportAccount") . ''; + print '

'; + + print ''; + print ''; + print_liste_field_titre($langs->trans("AccountNumber"), $_SERVER["PHP_SELF"], "aa.account_number", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Label"), $_SERVER["PHP_SELF"], "aa.label", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Accountparent"), $_SERVER["PHP_SELF"], "aa.account_parent", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Pcgtype"), $_SERVER["PHP_SELF"], "aa.pcg_type", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Pcgsubtype"), $_SERVER["PHP_SELF"], "aa.pcg_subtype", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Active"), $_SERVER["PHP_SELF"], "aa.active", "", $param, "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"",$param,"",'width="60" align="center"',$sortfield,$sortorder); + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $var = true; + + while ( $i < min($num, $limit) ) { + $obj = $db->fetch_object($resql); + + $var = ! $var; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + // Action + print '' . "\n"; + + print "\n"; + $i ++; + } + + print "
 '; + print ''; + print ' '; + print ''; + print '
' . $obj->account_number . '' . $obj->label . '' . $obj->account_parent . '' . $obj->pcg_type . '' . $obj->pcg_subtype . ''; + if (empty($obj->active)) { + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print ''; + } else { + print ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + } + print ''; + if ($user->admin) { + print ''; + print img_edit(); + print ''; + print ' '; + print ''; + print img_delete(); + print ''; + } + print '
"; + print '
'; +} else { + dol_print_error($db); +} + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php new file mode 100644 index 00000000000..ad6ca01b6ca --- /dev/null +++ b/htdocs/accountancy/admin/card.php @@ -0,0 +1,297 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/card.php + * \ingroup Accounting Expert + * \brief Card accounting account + */ +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("bills"); +$langs->load("accountancy"); + +$mesg = ''; +$action = GETPOST('action'); +$id = GETPOST('id', 'int'); +$rowid = GETPOST('rowid', 'int'); + +// Security check +if (!$user->admin) + accessforbidden(); + +$accounting = new AccountingAccount($db); + +// Action +if ($action == 'add') +{ + if (! GETPOST('cancel', 'alpha')) { + $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; + + dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + $result = $db->query($sql); + $obj = $db->fetch_object($result); + + $accounting->fk_pcg_version = $obj->pcg_version; + $accounting->pcg_type = GETPOST('pcg_type'); + $accounting->pcg_subtype = GETPOST('pcg_subtype'); + $accounting->account_number = GETPOST('account_number', 'int'); + $accounting->account_parent = GETPOST('account_parent', 'int'); + $accounting->label = GETPOST('label', 'alpha'); + $accounting->active = 1; + + $res = $accounting->create($user); + + if ($res == 0) { + } else { + if ($res == - 3) { + $_error = 1; + $action = "create"; + } + if ($res == - 4) { + $_error = 2; + $action = "create"; + } + } + } + Header("Location: account.php"); +} +else if ($action == 'edit') +{ + if (! GETPOST('cancel', 'alpha')) { + $result = $accounting->fetch($id); + + $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; + + dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + $result2 = $db->query($sql); + $obj = $db->fetch_object($result2); + + $accounting->fk_pcg_version = $obj->pcg_version; + $accounting->pcg_type = GETPOST('pcg_type'); + $accounting->pcg_subtype = GETPOST('pcg_subtype'); + $accounting->account_number = GETPOST('account_number', 'int'); + $accounting->account_parent = GETPOST('account_parent', 'int'); + $accounting->label = GETPOST('label', 'alpha'); + + $result = $accounting->update($user); + + if ($result > 0) { + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + exit(); + } else { + $mesg = $object->error; + } + } else { + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + exit(); + } +} +else if ($action == 'delete') +{ + $result = $accounting->fetch($id); + + if (! empty($accounting->id)) { + $result = $accounting->delete($user); + + if ($result > 0) { + Header("Location: account.php"); + } + } + + if ($result < 0) { + setEventMessage($accounting->error, 'errors'); + } +} + +/* + * View + * + */ +llxheader('', $langs->trans('AccountAccounting')); + +$form = new Form($db); +$htmlacc = new FormVentilation($db); + +if ($action == 'create') +{ + print_fiche_titre($langs->trans('NewAccount')); + + print '
' . "\n"; + print ''; + print ''; + + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print '
' . $langs->trans("AccountNumber") . '
' . $langs->trans("Label") . '
' . $langs->trans("Accountparent") . ''; + print $htmlacc->select_account($accounting->account_parent, 'account_parent'); + print '
' . $langs->trans("Pcgtype") . ''; + print $htmlacc->select_pcgtype($accounting->pcg_type, 'pcg_type'); + print '
' . $langs->trans("Pcgsubtype") . ''; + print $htmlacc->select_pcgsubtype($accounting->pcg_subtype, 'pcg_subtype'); + print '
'; + + print '
    '; + print ''; +} +else if ($id) +{ + $rowid = $id; + $account = $accounting->fetch($rowid); + + if ($account > 0) { + dol_htmloutput_mesg($mesg); + + $head = accounting_prepare_head($accounting); + + if ($action == 'update') + { + $soc = new Societe($db); + if ($object->socid) { + $soc->fetch($object->socid); + } + + dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr'); + + print '' . "\n"; + print ''; + print ''; + print ''; + + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print '
' . $langs->trans("AccountNumber") . '
' . $langs->trans("Label") . '
' . $langs->trans("Accountparent") . ''; + print $htmlacc->select_account($accounting->account_parent, 'account_parent'); + print '
' . $langs->trans("Pcgtype") . ''; + print $htmlacc->select_pcgtype($accounting->pcg_type, 'pcg_type'); + print '
' . $langs->trans("Pcgsubtype") . ''; + print $htmlacc->select_pcgsubtype($accounting->pcg_subtype, 'pcg_subtype'); + print '
'; + + print '
  '; + print ''; + print '
'; + + print ''; + + print ''; + } + else + { + $linkback = '' . $langs->trans("BackToChartofaccounts") . ''; + + dol_fiche_head($head, 'card', $langs->trans('AccountAccounting'), 0, 'billr'); + + print ''; + + // Account number + print ''; + print ''; + print ''; + + print ''; + print ''; + + $accp = new AccountingAccount($db); + if (! empty($accounting->account_parent)) { + $accp->fetch($accounting->account_parent, ''); + } + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print '
' . $langs->trans("AccountNumber") . '' . $accounting->account_number . '' . $linkback . '
' . $langs->trans("Label") . '' . $accounting->label . '
' . $langs->trans("Accountparent") . '' . $accp->account_number . ' - ' . $accp->label . '
' . $langs->trans("Pcgtype") . '' . $accounting->pcg_type . '
' . $langs->trans("Pcgsubtype") . '' . $accounting->pcg_subtype . '
' . $langs->trans("Active") . ''; + + if (empty($accounting->active)) { + print img_picto($langs->trans("Disabled"), 'switch_off'); + } else { + print img_picto($langs->trans("Activated"), 'switch_on'); + } + + print '
'; + + print ''; + + /* + * Barre d'actions + */ + + print '
'; + + if ($user->admin) { + print '' . $langs->trans('Modify') . ''; + } else { + print '' . $langs->trans('Modify') . ''; + } + + if ($user->admin) { + print '' . $langs->trans('Delete') . ''; + } else { + print '' . $langs->trans('Delete') . ''; + } + + print '
'; + } + } + else + { + dol_print_error($db); + } +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/export.php b/htdocs/accountancy/admin/export.php new file mode 100644 index 00000000000..d0eef1dc2f4 --- /dev/null +++ b/htdocs/accountancy/admin/export.php @@ -0,0 +1,164 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * Copyright (C) 2014 Marcos García + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/export.php + * \ingroup Accounting Expert + * \brief Setup page to configure accounting expert module + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +$langs->load("compta"); +$langs->load("bills"); +$langs->load("admin"); +$langs->load("accountancy"); + +// Security check +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action', 'alpha'); + +// Other parameters ACCOUNTING_* +$list = array ( + 'ACCOUNTING_SEPARATORCSV' +); + +/* + * Actions + */ +if ($action == 'update') { + $error = 0; + + $modelcsv = GETPOST('modelcsv', 'int'); + + if (! empty($modelcsv)) { + + if (! dolibarr_set_const($db, 'ACCOUNTING_MODELCSV', $modelcsv, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } else { + $error ++; + } + + foreach ( $list as $constname ) { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } + + if (! $error) { + setEventMessage($langs->trans("SetupSaved")); + } else { + setEventMessage($langs->trans("Error"), 'errors'); + } +} + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print_fiche_titre($langs->trans('ConfigAccountingExpert'),$linkback,'setup'); + +$head = admin_accounting_prepare_head(); + +dol_fiche_head($head, 'export', $langs->trans("Configuration"), 0, 'cron'); + +print '
'; +print ''; +print ''; + +print ''; +$var = true; + +print ''; +print ''; +print ''; + +$var = ! $var; + +print ''; +print ""; +print ""; +print "
' . $langs->trans("Modelcsv") . '
" . $langs->trans("Selectmodelcsv") . ""; +print '"; +print "
"; + +print "
\n"; + +/* + * Params + * + */ + +$num = count($list); +if ($num) { + print ''; + print ''; + print ''; + print "\n"; +} + +foreach ( $list as $key ) { + $var = ! $var; + + print ''; + + // Param + $label = $langs->trans($key); + print ''; + + // Value + print ''; +} + +print ''; +print "
' . $langs->trans('OtherOptions') . '
' . $label . ''; + print ''; + print '
\n"; + +print '
'; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/fiscalyear.php b/htdocs/accountancy/admin/fiscalyear.php new file mode 100644 index 00000000000..4dd005fca85 --- /dev/null +++ b/htdocs/accountancy/admin/fiscalyear.php @@ -0,0 +1,131 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/fiscalyear.php + * \ingroup fiscal year + * \brief Setup page to configure fiscal year + */ + +require '../../main.inc.php'; + +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; + +$action=GETPOST('action'); + +$langs->load("admin"); +$langs->load("compta"); + +if (! $user->admin) accessforbidden(); + +$error=0; + +// List of statut +static $tmpstatut2label=array( + '0'=>'OpenFiscalYear', + '1'=>'CloseFiscalYear' +); +$statut2label=array(''); +foreach ($tmpstatut2label as $key => $val) $statut2label[$key]=$langs->trans($val); + +$errors=array(); + +$object = new Fiscalyear($db); + +/* + * Actions + */ + +/* + * View + */ + +$max=100; + +$form = new Form($db); + +$title = $langs->trans('FiscalYears'); + +llxHeader('',$title,LOG_ERR); + +print_fiche_titre($langs->trans('FiscalYears')); + +$sql = "SELECT f.rowid, f.label, f.date_start, f.date_end, f.statut, f.entity"; +$sql.= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear as f"; +$sql.= " WHERE f.entity = ".$conf->entity; + +$result = $db->query($sql); +if ($result) +{ + $var=false; + $num = $db->num_rows($result); + + $i = 0; + + // Load attribute_label + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + if ($num) + { + $fiscalyearstatic=new Fiscalyear($db); + + while ($i < $num && $i < $max) + { + $obj = $db->fetch_object($result); + $fiscalyearstatic->ref=$obj->rowid; + $fiscalyearstatic->id=$obj->rowid; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $var=!$var; + $i++; + } + + } + else + { + print ''; + } + + print '
'.$langs->trans("Ref").''.$langs->trans("Label").''.$langs->trans("DateStart").''.$langs->trans("DateEnd").''.$langs->trans("Statut").'
'.img_object($langs->trans("ShowFiscalYear"),"technic").' '.$obj->rowid.''.$obj->label.''.dol_print_date($db->jdate($obj->date_start),'day').''.dol_print_date($db->jdate($obj->date_end),'day').''.$fiscalyearstatic->LibStatut($obj->statut,5).'
'.$langs->trans("None").'
'; +} +else +{ + dol_print_error($db); +} + +dol_fiche_end(); + +// Buttons +print ''; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php new file mode 100644 index 00000000000..423ac88b490 --- /dev/null +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -0,0 +1,334 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/fiscalyear_card.php + * \brief Page to show a fiscal year + */ + +require '../../main.inc.php'; + +require_once DOL_DOCUMENT_ROOT.'/core/lib/fiscalyear.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; + + +$langs->load("admin"); +$langs->load("compta"); + +// Security check +if (! $user->admin) accessforbidden(); + +$error=0; + +$action = GETPOST('action','alpha'); +$confirm = GETPOST('confirm','alpha'); +$id = GETPOST('id','int'); + +// List of statut +static $tmpstatut2label=array( + '0'=>'OpenFiscalYear', + '1'=>'CloseFiscalYear' +); +$statut2label=array(''); +foreach ($tmpstatut2label as $key => $val) $statut2label[$key]=$langs->trans($val); + +$object = new Fiscalyear($db); + +$date_start=dol_mktime(0,0,0,GETPOST('fiscalyearmonth','int'),GETPOST('fiscalyearday','int'),GETPOST('fiscalyearyear','int')); +$date_end=dol_mktime(0,0,0,GETPOST('fiscalyearendmonth','int'),GETPOST('fiscalyearendday','int'),GETPOST('fiscalyearendyear','int')); + + +/* + * Actions + */ + +if ($action == 'confirm_delete' && $confirm == "yes") +{ + $result=$object->delete($id); + if ($result >= 0) + { + header("Location: fiscalyear.php"); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } +} + +else if ($action == 'add') +{ + if (! GETPOST('cancel','alpha')) + { + $error=0; + + $object->date_start = $date_start; + $object->date_end = $date_end; + $object->label = GETPOST('label','alpha'); + $object->statut = GETPOST('statut','int'); + $object->datec = dol_now(); + + if (empty($object->date_start) && empty($object->date_end)) + { + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Date")), 'errors'); + $error++; + } + if (empty($object->label)) + { + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Label")), 'errors'); + $error++; + } + + if (! $error) + { + $db->begin(); + + $id = $object->create($user); + + if ($id > 0) + { + $db->commit(); + + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + exit; + } + else + { + $db->rollback(); + + setEventMessage($object->error, 'errors'); + $action='create'; + } + } + else + { + $action='create'; + } + } + else + { + header("Location: ./fiscalyear.php"); + exit; + } +} + +// Update record +else if ($action == 'update') +{ + if (! GETPOST('cancel','alpha')) + { + $result = $object->fetch($id); + + $object->date_start = empty($_POST["fiscalyear"])?'':$date_start; + $object->date_end = empty($_POST["fiscalyearend"])?'':$date_end; + $object->label = GETPOST('label','alpha'); + $object->statut = GETPOST('statut','int'); + + $result = $object->update($user); + + if ($result > 0) + { + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + exit; + } + else + { + setEventMessage($object->error, 'errors'); + } + } + else + { + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $id); + exit; + } +} + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); + +/* + * Action create +*/ +if ($action == 'create') +{ + print_fiche_titre($langs->trans("NewFiscalYear")); + + print '
'; + print ''; + print ''; + + print ''; + + // Label + print ''; + + // Date start + print ''; + + // Date end + print ''; + + // Statut + print ''; + print ''; + print ''; + + print '
'.$langs->trans("Label").'
'.$langs->trans("DateStart").''; + print $form->select_date(($date_start?$date_start:''),'fiscalyear'); + print '
'.$langs->trans("DateEnd").''; + print $form->select_date(($date_end?$date_end:-1),'fiscalyearend'); + print '
'.$langs->trans("Statut").''; + print $form->selectarray('statut',$statut2label,GETPOST('statut')); + print '
'; + + print '
    '; + print ''; +} +else if ($id) +{ + $result = $object->fetch($id); + if ($result > 0) + { + $head = fiscalyear_prepare_head($object); + + if ($action == 'edit') + { + dol_fiche_head($head, 'card', $langs->trans("FiscalYearCard"), 0, 'cron'); + + print '' . "\n"; + print ''; + print ''; + print ''; + + print ''; + + // Ref + print ""; + print ''; + + // Label + print ''; + + // Date start + print ''; + + // Date end + print ''; + + // Statut + print ''; + + print '
'.$langs->trans("Ref").''; + print $object->ref; + print '
'.$langs->trans("Label").''; + print ''; + print '
'.$langs->trans("DateStart").''; + print $form->select_date($object->date_start?$object->date_start:-1,'fiscalyear'); + print '
'.$langs->trans("DateEnd").''; + print $form->select_date($object->date_end?$object->date_end:-1,'fiscalyearend'); + print '
'.$langs->trans("Statut").''; + print $form->selectarray('statut',$statut2label,$object->statut); + print '
'; + + print '
  '; + print ''; + print '
'; + + print ''; + + dol_fiche_end(); + } + else + { + /* + * Confirm delete + */ + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id,$langs->trans("DeleteFiscalYear"),$langs->trans("ConfirmDeleteFiscalYear"),"confirm_delete"); + + } + + dol_fiche_head($head, 'card', $langs->trans("FiscalYearCard"), 0, 'cron'); + + print ''; + + $linkback = ''.$langs->trans("BackToList").''; + + // Ref + print ''; + + // Label + print '"; + + // Date start + print ''; + + // Date end + print ''; + + // Statut + print ''; + + print "
'.$langs->trans("Ref").''; + print $object->ref; + print ''; + print $linkback; + print '
'; + print $form->editfieldkey("Label",'label',$object->label,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'alpha:32'); + print ''; + print $form->editfieldval("Label",'label',$object->label,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'alpha:32'); + print "
'; + print $form->editfieldkey("Date",'date_start',$object->date_start,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'datepicker'); + print ''; + print $form->editfieldval("Date",'date_start',$object->date_start,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'datepicker'); + print '
'; + print $form->editfieldkey("Date",'date_end',$object->date_end,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'datepicker'); + print ''; + print $form->editfieldval("Date",'date_end',$object->date_end,$object,$conf->global->MAIN_EDIT_ALSO_INLINE,'datepicker'); + print '
'.$langs->trans("Status").''.$object->getLibStatut(4).'
"; + + dol_fiche_end(); + + /* + * Barre d'actions + */ + + print '
'; + + print ''.$langs->trans('Modify').''; + + print ''.$langs->trans('Delete').''; + + print '
'; + } + } + else + { + dol_print_error($db); + } +} + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/admin/fiscalyear_info.php b/htdocs/accountancy/admin/fiscalyear_info.php new file mode 100644 index 00000000000..b6fa546edff --- /dev/null +++ b/htdocs/accountancy/admin/fiscalyear_info.php @@ -0,0 +1,60 @@ + + * + * 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, seehttp://www.gnu.org/licenses/>. + */ + +/** + * \file htdocs/accountancy/admin/fiscalyear_card.php + * \brief Page to show info of a fiscal year + */ + +require '../../main.inc.php'; + +require_once DOL_DOCUMENT_ROOT.'/core/lib/fiscalyear.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php'; + + +$langs->load("admin"); +$langs->load("compta"); + +// Security check +if (! $user->admin) accessforbidden(); + +$id = GETPOST('id','int'); + +// View +llxHeader(); + +if ($id) +{ + $object = new Fiscalyear($db); + $object->fetch($id); + $object->info($id); + + $head = fiscalyear_prepare_head($object); + + dol_fiche_head($head, 'info', $langs->trans("FiscalYearCard"), 0, 'cron'); + + print '
'; + dol_print_object_info($object); + print '
'; + + print ''; +} + +$db->close(); + +llxFooter(); diff --git a/htdocs/accountancy/admin/importaccounts.php b/htdocs/accountancy/admin/importaccounts.php new file mode 100644 index 00000000000..9e5c59f4555 --- /dev/null +++ b/htdocs/accountancy/admin/importaccounts.php @@ -0,0 +1,186 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/importaccounts.php + * \ingroup Accounting Expert + * \brief Page import accounting account + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if (!$user->admin) + accessforbidden(); + +llxHeader('', $langs->trans("ImportAccount")); + +$to_import = GETPOST("mesCasesCochees"); + +if ($_POST["action"] == 'import') { + print '
' . $langs->trans("Processing") . '...
'; + if (is_array($to_import) && count($to_import) > 0) { + print '
' . count($to_import) . ' ' . $langs->trans("SelectedLines") . '
'; + $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; + + $result = $db->query($sql); + if ($result && ($db->num_rows($result) > 0)) { + + $obj = $db->fetch_object($result); + + $cpt = 0; + foreach ( $to_import as $maLigneCochee ) { + + $accounting = new AccountingAccount($db); + + $monLabel = GETPOST('label' . $maLigneCochee); + $monParentAccount = GETPOST('AccountParent' . $maLigneCochee); + $monType = GETPOST('pcgType' . $maLigneCochee); + $monSubType = GETPOST('pcgSubType' . $maLigneCochee); + + $accounting->fk_pcg_version = $obj->pcg_version; + $accounting->account_number = $maLigneCochee; + $accounting->label = $monLabel; + $accounting->account_parent = $monParentAccount; + $accounting->pcg_type = $monType; + $accounting->pcg_subtype = $monSubType; + $accounting->active = 1; + + $result = $accounting->create($user); + if ($result > 0) { + setEventMessage($langs->trans("AccountingAccountAdd"), 'mesgs'); + } else { + setEventMessage($accounting->error, 'errors'); + } + $cpt ++; + } + } else { + setEventMessage($langs->trans('AccountPlanNotFoundCheckSetting'), 'errors'); + } + } else { + print '
' . $langs->trans("AnyLineImport") . '
'; + } + print '
' . $langs->trans("EndProcessing") . '
'; +} + +/* +* list accounting account from product +* +*/ +$page = GETPOST("page"); +if ($page < 0) + $page = 0; +$limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; +$offset = $limit * $page; + +$sql = "(SELECT p.rowid as product_id, p.accountancy_code_sell as accounting "; +$sql .= " FROM " . MAIN_DB_PREFIX . "product as p "; +$sql .= " WHERE p.accountancy_code_sell >=0"; +$sql .= " GROUP BY accounting "; +$sql .= ")"; +$sql .= "UNION ALL(SELECT p.rowid as product_id, p.accountancy_code_buy as accounting "; +$sql .= " FROM " . MAIN_DB_PREFIX . "product as p "; +$sql .= " WHERE p.accountancy_code_buy >=0"; +$sql .= " GROUP BY accounting "; +$sql .= ") "; +$sql .= " ORDER BY accounting DESC " . $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/admin/importaccounts.php:: $sql=' . $sql); +$result = $db->query($sql); +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + print_barre_liste($langs->trans("ImportAccount"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $form = new Form($db); + $htmlacc = new FormVentilation($db); + + print '' . "\n"; + print ''; + + $var = true; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + print ""; + + print ''; + + print ''; + + // Colonne choix du compte + print ''; + + print ''; + + print ''; + + // Colonne choix ligne a ventiler + + $checked = ('label' == 'O') ? ' checked=checked' : ''; + + print ''; + + print ''; + $i ++; + } + + print ''; + + print '
' . $langs->trans("accountingaccount") . '' . $langs->trans("label") . '' . $langs->trans("Accountparent") . '' . $langs->trans("Pcgtype") . '' . $langs->trans("Pcgsubtype") . '' . $langs->trans("Import") . '
'; + print $objp->accounting; + print ''; + print ''; + print ''; + print $htmlacc->select_account($accounting->account_parent, 'AccountParent'); + print ''; + print $htmlacc->select_pcgtype($accounting->pcg_type, 'pcgType'); + print ''; + print $htmlacc->select_pcgsubtype($accounting->pcg_subtype, 'pcgSubType'); + print ''; + print ''; + print '
 
'; + print ''; +} else { + print $db->error(); +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/index.html b/htdocs/accountancy/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php new file mode 100644 index 00000000000..e72df6a0431 --- /dev/null +++ b/htdocs/accountancy/admin/index.php @@ -0,0 +1,294 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Ari Elbaz (elarifr) + * Copyright (C) 2014 Marcos García + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/admin/index.php + * \ingroup Accounting Expert + * \brief Setup page to configure accounting expert module + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +$langs->load("compta"); +$langs->load("bills"); +$langs->load("admin"); +$langs->load("accountancy"); + +// Security check +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action', 'alpha'); + +// Other parameters ACCOUNTING_* +$list = array ( + 'ACCOUNTING_LIMIT_LIST_VENTILATION', + 'ACCOUNTING_LENGTH_GACCOUNT', + 'ACCOUNTING_LENGTH_AACCOUNT', + 'ACCOUNTING_ACCOUNT_CUSTOMER', + 'ACCOUNTING_ACCOUNT_SUPPLIER', + 'ACCOUNTING_PRODUCT_BUY_ACCOUNT', + 'ACCOUNTING_PRODUCT_SOLD_ACCOUNT', + 'ACCOUNTING_SERVICE_BUY_ACCOUNT', + 'ACCOUNTING_SERVICE_SOLD_ACCOUNT', + 'ACCOUNTING_ACCOUNT_SUSPENSE', + 'ACCOUNTING_ACCOUNT_TRANSFER_CASH' +); + +/* + * Actions + */ + +$accounting_mode = defined('ACCOUNTING_MODE')?ACCOUNTING_MODE:'RECETTES-DEPENSES'; + +if ($action == 'update') +{ + $error = 0; + + $accounting_modes = array( + 'RECETTES-DEPENSES', + 'CREANCES-DETTES' + ); + + $accounting_mode = GETPOST('accounting_mode','alpha'); + + if (in_array($accounting_mode,$accounting_modes)) { + + if (!dolibarr_set_const($db, 'ACCOUNTING_MODE', $accounting_mode, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } else { + $error++; + } + + $chartofaccounts = GETPOST('chartofaccounts', 'int'); + + if (! empty($chartofaccounts)) { + + if (! dolibarr_set_const($db, 'CHARTOFACCOUNTS', $chartofaccounts, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } else { + $error ++; + } + + foreach ($list as $constname) { + $constvalue = GETPOST($constname, 'alpha'); + + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } + } + + if (! $error) + { + setEventMessage($langs->trans("SetupSaved")); + } + else + { + setEventMessage($langs->trans("Error"),'errors'); + } +} + +if ($action == 'setlistsorttodo') { + $setlistsorttodo = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $setlistsorttodo, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + + if (! $error) { + setEventMessage($langs->trans("SetupSaved"), 'mesgs'); + } else { + setEventMessage($langs->trans("Error"), 'mesgs'); + } +} + +if ($action == 'setlistsortdone') { + $setlistsortdone = GETPOST('value', 'int'); + $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $setlistsortdone, 'yesno', 0, '', $conf->entity); + if (! $res > 0) + $error ++; + if (! $error) { + setEventMessage($langs->trans("SetupSaved"), 'mesgs'); + } else { + setEventMessage($langs->trans("Error"), 'mesgs'); + } +} + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print_fiche_titre($langs->trans('ConfigAccountingExpert'),$linkback,'setup'); + +$head = admin_accounting_prepare_head($accounting); + +dol_fiche_head($head, 'general', $langs->trans("Configuration"), 0, 'cron'); + +print '
'; +print ''; +print ''; + +print ''; + +// Cas du parametre ACCOUNTING_MODE + +print ''; +print ''; +print "\n"; +print ''; +print '\n"; +print ''; +print '\n"; +print ''; + +print "
'.$langs->trans('OptionMode').''.$langs->trans('Description').'
'.$langs->trans('OptionModeTrue').''.nl2br($langs->trans('OptionModeTrueDesc')); +// Write info on way to count VAT +//if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) +//{ +// // print "
\n"; +// // print nl2br($langs->trans('OptionModeTrueInfoModuleComptabilite')); +//} +//else +//{ +// // print "
\n"; +// // print nl2br($langs->trans('OptionModeTrueInfoExpert')); +//} +print "
'.$langs->trans('OptionModeVirtual').''.nl2br($langs->trans('OptionModeVirtualDesc'))."
\n"; + +print "
\n"; + +/* + * Define Chart of accounts + */ +print ''; +$var = true; + +print ''; +print ''; +print "\n"; +$var = ! $var; +print ''; +print ""; +print ""; +print "
'; +print $langs->trans("Chartofaccounts") . '
" . $langs->trans("Selectchartofaccounts") . ""; +print '"; +print "
"; + +print "
\n"; + +/* + * Others params + */ +print ''; +print ''; +print ''; +print "\n"; + +foreach ($list as $key) +{ + $var=!$var; + + print ''; + + // Param + $label = $langs->trans($key); + print ''; + + // Value + print ''; +} + +$var = ! $var; +print ""; +print ''; +if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO)) { + print ''; +} else { + print ''; +} +print ''; + +$var = ! $var; +print ""; +print ''; +if (! empty($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE)) { + print ''; +} else { + print ''; +} +print ''; + +print ''; +print "
' . $langs->trans('OtherOptions') . '
'; + print ''; + print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_TODO") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
' . $langs->trans("ACCOUNTING_LIST_SORT_VENTILATION_DONE") . ''; + print img_picto($langs->trans("Activated"), 'switch_on'); + print ''; + print img_picto($langs->trans("Disabled"), 'switch_off'); + print '
\n"; + +print '

'; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/journaux.php b/htdocs/accountancy/admin/journaux.php new file mode 100644 index 00000000000..f7507cda234 --- /dev/null +++ b/htdocs/accountancy/admin/journaux.php @@ -0,0 +1,172 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * Copyright (C) 2014 Marcos García + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/admin/journaux.php + * \ingroup Accounting Expert + * \brief Setup page to configure accounting expert module + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + +$langs->load("accountancy"); + +// Security check +if (!$user->admin) + accessforbidden(); + +$action = GETPOST('action', 'alpha'); + +// Other parameters ACCOUNTING_* +$list = array ( + 'ACCOUNTING_SELL_JOURNAL', + 'ACCOUNTING_PURCHASE_JOURNAL', + 'ACCOUNTING_SOCIAL_JOURNAL', + 'ACCOUNTING_CASH_JOURNAL', + 'ACCOUNTING_MISCELLANEOUS_JOURNAL' +); + +/* + * Actions + */ + +if ($action == 'update') { + $error = 0; + + foreach ( $list as $constname ) { + $constvalue = GETPOST($constname, 'alpha'); + + if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error ++; + } + } + + if (! $error) { + setEventMessage($langs->trans("SetupSaved")); + } else { + setEventMessage($langs->trans("Error"), 'errors'); + } +} + +/* + * View + */ + +llxHeader(); + +$form = new Form($db); + +$linkback=''.$langs->trans("BackToModuleList").''; +print_fiche_titre($langs->trans('ConfigAccountingExpert'),$linkback,'setup'); + +$head = admin_accounting_prepare_head(null); + +dol_fiche_head($head, 'journal', $langs->trans("Configuration"), 0, 'cron'); + +print '
'; +print ''; +print ''; + +print ''; +print ''; +print ''; +print "\n"; + +foreach ( $list as $key ) { + $var = ! $var; + + print ''; + + // Param + $label = $langs->trans($key); + print ''; + + // Value + print ''; +} + +print ''; +print "
' . $langs->trans('Journaux') . '
'; + print ''; + print '
\n"; + +print '
'; + +print '
'; + +print ''; +print ''; +print ''; +print "\n"; + +// Bank account +$sql = "SELECT rowid, label, accountancy_journal"; +$sql.= " FROM ".MAIN_DB_PREFIX."bank_account"; +$sql.= " WHERE entity = ".$conf->entity; +$sql.= " AND clos = 0"; +$sql.= " ORDER BY label"; + +$resql = $db->query($sql); +if ($resql) +{ + $numr = $db->num_rows($resql); + $i = 0; + + if ($numr > 0) + + while ($i < $numr) + { + $objp = $db->fetch_object($resql); + + $var = ! $var; + + print ''; + + // Param + print ''; + + // Value + print ''; + + $i++; + } +} +else dol_print_error($db); +$db->free($resql); + +print "
' . $langs->trans('JournalFinancial') . '
'; + print ''; + print '
\n"; + +print ''; +print ''; + +print '
'; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php new file mode 100644 index 00000000000..402ff72ed84 --- /dev/null +++ b/htdocs/accountancy/admin/productaccount.php @@ -0,0 +1,147 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/admin/productaccount.php + * \ingroup Accounting Expert + * \brief Onglet de gestion de parametrages des ventilations + */ + +// Dolibarr environment +$res = @include ("../main.inc.php"); +if (! $res && file_exists("../main.inc.php")) + $res = @include ("../main.inc.php"); +if (! $res && file_exists("../../main.inc.php")) + $res = @include ("../../main.inc.php"); +if (! $res && file_exists("../../../main.inc.php")) + $res = @include ("../../../main.inc.php"); +if (! $res) + die("Include of main fails"); + + // Class +dol_include_once("/core/lib/report.lib.php"); +dol_include_once("/core/lib/date.lib.php"); +dol_include_once("/product/class/product.class.php"); + +$langs->load("companies"); +$langs->load("compta"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if (!$user->admin) + accessforbidden(); + +llxHeader('', $langs->trans("Accounts")); + +$form = new Form($db); + +print ''; + +print ' + '; + +$sql = "SELECT p.rowid, p.ref , p.label, p.description , p.accountancy_code_sell as codesell, p.accountancy_code_buy, p.tms, p.fk_product_type as product_type , p.tosell , p.tobuy "; +$sql .= " FROM " . MAIN_DB_PREFIX . "product as p"; +$sql .= " WHERE p.accountancy_code_sell IS NULL AND p.tosell = 1 OR p.accountancy_code_buy IS NULL AND p.tobuy = 1"; + +dol_syslog('accountancy/admin/productaccount.php:: $sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + + /* +* view +*/ + + print '

'; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $var = true; + + while ( $i < min($num, 250) ) { + $obj = $db->fetch_object($resql); + $var = ! $var; + + $compta_prodsell = $obj->accountancy_code_sell; + if (empty($compta_prodsell)) { + if ($obj->product_type == 0) + $compta_prodsell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + else + $compta_prodsell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } + + $compta_prodbuy = $obj->accountancy_code_buy; + if (empty($compta_prodbuy)) { + if ($obj->product_type == 0) + $compta_prodbuy = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); + else + $compta_prodbuy = (! empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : $langs->trans("CodeNotDef")); + } + + $product_static = new Product($db); + + print ""; + // Ref produit + $product_static->ref = $objp->ref; + $product_static->id = $objp->rowid; + $product_static->type = $objp->type; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + + print ''; + print ''; + + print "\n"; + $i ++; + } + print "
' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("Description") . '' . $langs->trans("Accountancy_code_buy") . '' . $langs->trans("Accountancy_code_buy_suggest") . '' . $langs->trans("Accountancy_code_sell") . '' . $langs->trans("Accountancy_code_sell_suggest") . '
'; + if ($product_static->id) + print $product_static->getNomUrl(1); + else + print ' '; + print '' . $obj->ref . '' . $obj->label . '' . $obj->description . '' . $obj->accountancy_code_buy . '' . $compta_prodbuy . '' . $obj->accountancy_code_sell . '' . $compta_prodsell . '
"; + $db->free($resql); +} else { + dol_print_error($db); +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/bookkeeping/balancebymonth.php b/htdocs/accountancy/bookkeeping/balancebymonth.php new file mode 100644 index 00000000000..120d08db09c --- /dev/null +++ b/htdocs/accountancy/bookkeeping/balancebymonth.php @@ -0,0 +1,134 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/bookkeeping/balancebymonth.php + * \ingroup Accounting Expert + * \brief Balance by month + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +// Langs +$langs->load("main"); +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("accountancy"); + +// Filter +$year = $_GET["year"]; +if ($year == 0) { + $year_current = strftime("%Y", time()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} + +/* + * View + */ +llxHeader('', $langs->trans("CustomersVentilation")); + +$textprevyear = "" . img_previous() . ""; +$textnextyear = " " . img_next() . ""; + +print_fiche_titre($langs->trans("AccountBalanceByMonth") . ' ' . $textprevyear . ' ' . $langs->trans("Year") . ' ' . $year_start . ' ' . $textnextyear); + +$sql = "SELECT count(*) FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " , " . MAIN_DB_PREFIX . "facture as f"; +$sql .= " WHERE fd.fk_code_ventilation = 0"; +$sql .= " AND f.rowid = fd.fk_facture AND f.fk_statut = 1;"; + +dol_syslog('accountancy/bookkeeping/balancebymonth.php:: $sql=' . $sql); +$result = $db->query($sql); +if ($result) { + $row = $db->fetch_row($result); + $nbfac = $row[0]; + + $db->free($result); +} + +$y = $year_current; + +$var = true; + +print ''; +print ''; + +$sql = "SELECT bk.numero_compte AS 'compte',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=1,bk.montant,0)),2) AS 'Janvier',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=2,bk.montant,0)),2) AS 'Fevrier',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=3,bk.montant,0)),2) AS 'Mars',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=4,bk.montant,0)),2) AS 'Avril',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=5,bk.montant,0)),2) AS 'Mai',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=6,bk.montant,0)),2) AS 'Juin',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=7,bk.montant,0)),2) AS 'Juillet',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=8,bk.montant,0)),2) AS 'Aout',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=9,bk.montant,0)),2) AS 'Septembre',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=10,bk.montant,0)),2) AS 'Octobre',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=11,bk.montant,0)),2) AS 'Novembre',"; +$sql .= " ROUND(SUM(IF(MONTH(bk.doc_date)=12,bk.montant,0)),2) AS 'Decembre',"; +$sql .= " ROUND(SUM(bk.montant),2) as 'Total'"; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +$sql .= " WHERE bk.doc_date >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND bk.doc_date <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " GROUP BY bk.numero_compte"; + +$resql = $db->query($sql); +if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $i ++; + } + $db->free($resql); +} else { + print $db->lasterror(); +} +print "
' . $langs->trans("Label") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . 'Total
' . length_accountg($row[0]) . '' . price($row[1]) . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '
\n"; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php new file mode 100644 index 00000000000..608c62cf1d0 --- /dev/null +++ b/htdocs/accountancy/bookkeeping/card.php @@ -0,0 +1,371 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/bookkeeping/card.php + * \ingroup Accounting Expert + * \brief Page to show account + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; + +// Langs +$langs->load("accounting"); + +// Security check +$id = GETPOST('id', 'int'); +if ($user->societe_id > 0) + accessforbidden(); + +$action = GETPOST('action'); +$piece_num = GETPOST("piece_num"); + +$mesg = ''; + +$numero_compte = GETPOST('numero_compte'); +$code_tiers = GETPOST('code_tiers'); +$label_compte = GETPOST('label_compte'); +$debit = price2num(GETPOST('debit')); +$credit = price2num(GETPOST('credit')); + +if ($action == "confirm_update") { + + $error = 0; + + if ((intval($debit) != 0) && (intval($credit) != 0)) { + setEventMessage($langs->trans('ErrorDebitCredit'), 'errors'); + $error ++; + } + + if (empty($error)) { + $book = new BookKeeping($db); + + $result = $book->fetch($id); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + $book->numero_compte = $numero_compte; + $book->code_tiers = $code_tiers; + $book->label_compte = $label_compte; + $book->debit = $debit; + $book->credit = $credit; + + if (! empty($debit)) { + $book->montant = $debit; + $book->sens = 'D'; + } + if (! empty($credit)) { + $book->montant = $credit; + $book->sens = 'C'; + } + + $result = $book->update(); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + setEventMessage($langs->trans('Saved'), 'mesgs'); + $action = ''; + } + } + } +} + +else if ($action == "add") { + + $error = 0; + if ((intval($debit) != 0) && (intval($credit) != 0)) { + setEventMessage($langs->trans('ErrorDebitCredit'), 'errors'); + $error ++; + } + + if (empty($error)) { + $book = new BookKeeping($db); + + $book->numero_compte = $numero_compte; + $book->code_tiers = $code_tiers; + $book->label_compte = $label_compte; + $book->debit = $debit; + $book->credit = $credit; + $book->doc_date = GETPOST('doc_date'); + $book->doc_type = GETPOST('doc_type'); + $book->piece_num = $piece_num; + $book->doc_ref = GETPOST('doc_ref'); + $book->code_journal = GETPOST('code_journal'); + $book->fk_doc = GETPOST('fk_doc'); + $book->fk_docdet = GETPOST('fk_docdet'); + + if (! empty($debit)) { + $book->montant = $debit; + $book->sens = 'D'; + } + if (! empty($credit)) { + $book->montant = $credit; + $book->sens = 'C'; + } + + $result = $book->create_std($user); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + setEventMessage($langs->trans('Saved'), 'mesgs'); + $action = ''; + } + } +} + +else if ($action == "confirm_delete") { + $book = new BookKeeping($db); + + $result = $book->fetch($id); + + $piece_num = $book->piece_num; + + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + $result = $book->delete($user); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } + } + $action = ''; +} + +else if ($action == "confirm_create") { + $book = new BookKeeping($db); + + $book->label_compte = ''; + $book->debit = 0; + $book->credit = 0; + $book->doc_date = $date_start = dol_mktime(0, 0, 0, GETPOST('doc_datemonth'), GETPOST('doc_dateday'), GETPOST('doc_dateyear')); + $book->doc_type = GETPOST('doc_type'); + $book->piece_num = GETPOST('next_num_mvt'); + $book->doc_ref = GETPOST('doc_ref'); + $book->code_journal = GETPOST('code_journal'); + $book->fk_doc = 0; + $book->fk_docdet = 0; + + $book->montant = 0; + + $result = $book->create_std($user); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + setEventMessage($langs->trans('Saved'), 'mesgs'); + $action = ''; + $piece_num = $book->piece_num; + } +} + +llxHeader(); + +$html = new Form($db); + +/* + * Confirmation to delete the command + */ +if ($action == 'delete') { + $formconfirm = $html->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $id, $langs->trans('DeleteMvt'), $langs->trans('ConfirmDeleteMvt'), 'confirm_delete', '', 0, 1); + print $formconfirm; +} + +if ($action == 'create') { + + print_fiche_titre($langs->trans("CreateMvts")); + + $code_journal_array = array ( + $conf->global->ACCOUNTING_SELL_JOURNAL => $conf->global->ACCOUNTING_SELL_JOURNAL, + $conf->global->ACCOUNTING_PURCHASE_JOURNAL => $conf->global->ACCOUNTING_PURCHASE_JOURNAL, + $conf->global->ACCOUNTING_BANK_JOURNAL => $conf->global->ACCOUNTING_BANK_JOURNAL, + $conf->global->ACCOUNTING_SOCIAL_JOURNAL => $conf->global->ACCOUNTING_SOCIAL_JOURNAL + ); + + $book = new BookKeeping($db); + $next_num_mvt = $book->getNextNumMvt(); + + print '
'; + print '' . "\n"; + print '' . "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
' . $langs->trans("NumMvts") . '' . $next_num_mvt . '
' . $langs->trans("Docdate") . ''; + print $html->select_date('', 'doc_date', '', '', '', "create_mvt", 1, 1); + print '
' . $langs->trans("Codejournal") . '' . $html->selectarray('code_journal', $code_journal_array) . '
' . $langs->trans("Docref") . '
' . $langs->trans("Doctype") . '
'; + print '
'; + print ''; + + print '
'; +} +else +{ + $book = new BookKeeping($db); + $result = $book->fetch_per_mvt($piece_num); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } + if (! empty($book->piece_num)) { + + print_fiche_titre($langs->trans("UpdateMvts")); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
' . $langs->trans("NumMvts") . '' . $book->piece_num . '
' . $langs->trans("Docdate") . '' . dol_print_date($book->doc_date, 'daytextshort') . '
' . $langs->trans("Codejournal") . '' . $book->code_journal . '
' . $langs->trans("Docref") . '' . $book->doc_ref . '
' . $langs->trans("Doctype") . '' . $book->doc_type . '
'; + + $result = $book->fetch_all_per_mvt($piece_num); + if ($result < 0) { + setEventMessage($book->errors, 'errors'); + } else { + + print_fiche_titre($langs->trans("ListeMvts")); + print ""; + if (count($book->linesmvt) > 0) { + + print ''; + + print_liste_field_titre($langs->trans("Numerocompte")); + print_liste_field_titre($langs->trans("Code_tiers")); + print_liste_field_titre($langs->trans("Labelcompte")); + print_liste_field_titre($langs->trans("Debit")); + print_liste_field_titre($langs->trans("Credit")); + print_liste_field_titre($langs->trans("Amount")); + print_liste_field_titre($langs->trans("Sens")); + + print ''; + print "\n"; + + foreach ( $book->linesmvt as $line ) { + $var = ! $var; + print ""; + + if ($action == 'update' && $line->id == $id) { + + print ''; + print '' . "\n"; + print '' . "\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + else { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + } + print "\n"; + } + + if ($action == "" || $action == 'add') { + $var = ! $var; + print ""; + + print ''; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + print "
' . $line->montant . '' . $line->sens . ''; + print ''; + print ''; + print '' . $line->numero_compte . '' . $line->code_tiers . '' . $line->label_compte . '' . $line->debit . '' . $line->credit . '' . $line->montant . '' . $line->sens . ''; + print ''; + print img_edit(); + print ' '; + print ''; + print img_delete(); + print ''; + + print '
"; + } + } + } + else { + print_fiche_titre($langs->trans("NoRecords")); + } +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/bookkeeping/index.html b/htdocs/accountancy/bookkeeping/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php new file mode 100644 index 00000000000..b2acc60fb6a --- /dev/null +++ b/htdocs/accountancy/bookkeeping/list.php @@ -0,0 +1,234 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/bookkeeping/list.php + * \ingroup Accounting Expert + * \brief List operation of book keeping + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; + + +$page = GETPOST("page"); +$sortorder = GETPOST("sortorder"); +$sortfield = GETPOST("sortfield"); +$action = GETPOST('action', 'alpha'); +$search_doc_type = GETPOST("search_doc_type"); +$search_doc_ref = GETPOST("search_doc_ref"); +$search_account = GETPOST("search_account"); +$search_thirdparty = GETPOST("search_thirdparty"); +$search_journal = GETPOST("search_journal"); + +if ($sortorder == "") + $sortorder = "ASC"; +if ($sortfield == "") + $sortfield = "bk.rowid"; + +$offset = $conf->liste_limit * $page; + +$formventilation = new FormVentilation($db); + +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_doc_type=""; + $search_doc_ref=""; + $search_account=""; + $search_thirdparty=""; + $search_journal=""; +} + +/* + * Action + */ +if ($action == 'delbookkeeping') { + + $import_key = GETPOST('importkey', 'alpha'); + + if (! empty($import_key)) { + $object = new BookKeeping($db); + $result = $object->delete_by_importkey($import_key); + Header("Location: list.php"); + if ($result < 0) { + setEventMessage($object->errors, 'errors'); + } + } +} // export csv +else if ($action == 'export_csv') { + + header('Content-Type: text/csv'); + header('Content-Disposition: attachment;filename=export_csv.csv'); + + $object = new BookKeeping($db); + $result = $object->export_bookkeping('ebp'); + if ($result < 0) { + setEventMessage($object->errors, 'errors'); + } + + foreach ( $object->linesexport as $line ) { + print $line->id . ','; + print '"' . dol_print_date($line->doc_date, '%d%m%Y') . '",'; + print '"' . $line->code_journal . '",'; + print '"' . $line->numero_compte . '",'; + print '"' . substr($line->code_journal, 0, 2) . '",'; + print '"' . substr($line->doc_ref, 0, 40) . '",'; + print '"' . $line->num_piece . '",'; + print '"' . $line->montant . '",'; + print '"' . $line->sens . '",'; + print '"' . dol_print_date($line->doc_date, '%d%m%Y') . '",'; + print '"' . $conf->currency . '",'; + print "\n"; + } +} + +else { + + llxHeader('', $langs->trans("Bookkeeping")); + +/* + * List + */ + + $sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens , bk.code_journal , bk.piece_num "; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; + + if (dol_strlen(trim($search_doc_type))) { + + $sql .= " WHERE bk.doc_type LIKE '%" . $search_doc_type . "%'"; + + if (dol_strlen(trim($search_doc_ref))) { + $sql .= " AND bk.doc_ref LIKE '%" . $search_doc_ref . "%'"; + } + } + if (dol_strlen(trim($search_doc_ref))) { + $sql .= " WHERE bk.doc_ref LIKE '%" . $search_doc_ref . "%'"; + } + if (dol_strlen(trim($search_account))) { + $sql .= " WHERE bk.numero_compte LIKE '%" . $search_account . "%'"; + } + if (dol_strlen(trim($search_thirdparty))) { + $sql .= " WHERE bk.code_tiers LIKE '%" . $search_thirdparty . "%'"; + } + if (dol_strlen(trim($search_journal))) { + $sql .= " WHERE bk.code_journal LIKE '%" . $search_journal . "%'"; + } + + $sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit + 1, $offset); + + dol_syslog('accountancy/bookkeeping/list.php:: $sql=' . $sql); + $resql = $db->query($sql); + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + + print_barre_liste($langs->trans("Bookkeeping"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num); + + print ''; + print ''; + print ''; + + print $formventilation->select_bookkeeping_importkey('importkey', GETPOST('importkey')); + + print '
'; + + print ''; + + print '' . $langs->trans("NewAccountingMvt") . '
'; + + print '
'; + print ''; + print ''; + print ''; + print '
'; + + print ''; + print ''; + print_liste_field_titre($langs->trans("Doctype"), $_SERVER['PHP_SELF'], "bk.doc_type", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Docdate"), $_SERVER['PHP_SELF'], "bk.doc_date", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "bk.doc_ref", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Numerocompte"), $_SERVER['PHP_SELF'], "bk.numero_compte", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Code_tiers"), $_SERVER['PHP_SELF'], "bk.code_tiers", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Labelcompte"), $_SERVER['PHP_SELF'], "bk_label_compte", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "bk.debit", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "bk.credit", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER['PHP_SELF'], "bk.montant", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Sens"), $_SERVER['PHP_SELF'], "bk.sens", "", "", 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "bk.code_journal", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Action"),$_SERVER["PHP_SELF"],"",$param,"",'width="60" align="center"',$sortfield,$sortorder); + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $var = True; + + while ( $i < min($num, $conf->liste_limit) ) { + $obj = $db->fetch_object($resql); + $var = ! $var; + + print ""; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $i ++; + } + print "
      '; + print ''; + print ' '; + print ''; + print '
' . $obj->doc_type . '' . dol_print_date($db->jdate($obj->doc_date), 'day') . '' . $obj->doc_ref . '' . length_accountg($obj->numero_compte) . '' . length_accounta($obj->code_tiers) . '' . $obj->label_compte . '' . price($obj->debit) . '' . price($obj->credit) . '' . price($obj->montant) . '' . $obj->sens . '' . $obj->code_journal . '' . img_edit() . '
"; + $db->free($resql); + } else { + dol_print_error($db); + } +} + +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/listbyyear.php b/htdocs/accountancy/bookkeeping/listbyyear.php new file mode 100644 index 00000000000..0829f792130 --- /dev/null +++ b/htdocs/accountancy/bookkeeping/listbyyear.php @@ -0,0 +1,128 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/bookkeeping/listbyyear.php + * \ingroup Accounting Expert + * \brief Book keeping by year + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +// Langs +$langs->load("accountancy"); + +$page = GETPOST("page"); +$sortorder = GETPOST("sortorder"); +$sortfield = GETPOST("sortfield"); + +// Filter +$year = GETPOST("year", 'int'); +if ($year == 0) { + $year_current = strftime("%Y", time()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} + +if ($sortorder == "") + $sortorder = "ASC"; +if ($sortfield == "") + $sortfield = "bk.rowid"; + +$offset = $conf->liste_limit * $page; + +llxHeader('', $langs->trans("Bookkeeping")); + +$textprevyear = "" . img_previous() . ""; +$textnextyear = " " . img_next() . ""; + +/* + * Mode Liste + * + */ + +$sql = "SELECT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.code_tiers, bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant , bk.sens, bk.code_journal"; +$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as bk"; +// $sql .= " WHERE bk.doc_date >= '".$db->idate(dol_get_first_day($y,1,false))."'"; +// $sql .= " AND bk.doc_date <= '".$db->idate(dol_get_last_day($y,12,false))."'"; +$sql .= " ORDER BY $sortfield $sortorder " . $db->plimit($conf->liste_limit + 1, $offset); + +dol_syslog('accountancy/bookkeeping/listbyyear.php:: $sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + + print_barre_liste($langs->trans("Bookkeeping") . " $textprevyear " . $langs->trans("Year") . " $year_start $textnextyear", $page, $_SERVER['PHP_SELF'], "", $sortfield, $sortorder, '', $num); + print ""; + + print ''; + print_liste_field_titre($langs->trans("Doctype"), $_SERVER['PHP_SELF'], "bk.doc_type", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Date"), $_SERVER['PHP_SELF'], "bk.doc_date", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Docref"), $_SERVER['PHP_SELF'], "bk.doc_ref", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("AccountAccounting"), $_SERVER['PHP_SELF'], "bk.numero_compte", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("ThirdPartyAccount"), $_SERVER['PHP_SELF'], "bk.code_tiers", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Label"), $_SERVER['PHP_SELF'], "bk_label_compte", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Debit"), $_SERVER['PHP_SELF'], "bk.debit", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Credit"), $_SERVER['PHP_SELF'], "bk.credit", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Amount"), $_SERVER['PHP_SELF'], "bk.montant", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Sens"), $_SERVER['PHP_SELF'], "bk.sens", "", "", "", $sortfield, $sortorder); + print_liste_field_titre($langs->trans("Codejournal"), $_SERVER['PHP_SELF'], "bk.code_journal", "", "", "", $sortfield, $sortorder); + print_liste_field_titre(" "); + print "\n"; + + $var = True; + + while ( $i < min($num, $conf->liste_limit) ) { + $obj = $db->fetch_object($resql); + $var = ! $var; + + print ""; + + print '' . "\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $i ++; + } + print "
' . $obj->doc_type . '' . dol_print_date($db->jdate($obj->doc_date)) . '' . $obj->doc_ref . '' . length_accountg($obj->numero_compte) . '' . length_accounta($obj->code_tiers) . '' . $obj->label_compte . '' . price($obj->debit) . '' . price($obj->credit) . '' . price($obj->montant) . '' . $obj->sens . '' . $obj->code_journal . '' . img_edit() . '
"; + $db->free($resql); +} else { + dol_print_error($db); +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/class/accountancyaccount.class.php b/htdocs/accountancy/class/accountancyaccount.class.php deleted file mode 100644 index 229bc79ba41..00000000000 --- a/htdocs/accountancy/class/accountancyaccount.class.php +++ /dev/null @@ -1,95 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/accountancy/class/accountancyaccount.class.php - * \ingroup accounting - * \brief Fichier de la classe des comptes comptables - */ - - -/** - * \class AccountancyAccount - * \brief Classe permettant la gestion des comptes - */ -class AccountancyAccount -{ - var $db; - var $error; - - var $rowid; - var $fk_pcg_version; - var $pcg_type; - var $pcg_subtype; - var $label; - var $account_number; - var $account_parent; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } - - - /** - * Insert account into database - * - * @param User $user User making add - * @return int <0 if KO, Id line added if OK - */ - function create($user) - { - $now=dol_now(); - - $sql = "INSERT INTO ".MAIN_DB_PREFIX."accountingaccount"; - $sql.= " (date_creation, fk_user_author, numero,intitule)"; - $sql.= " VALUES ('".$this->db->idate($now)."',".$user->id.",'".$this->numero."','".$this->intitule."')"; - - $resql = $this->db->query($sql); - if ($resql) - { - $id = $this->db->last_insert_id(MAIN_DB_PREFIX."accountingaccount"); - - if ($id > 0) - { - $this->id = $id; - $result = $this->id; - } - else - { - $result = -2; - $this->error="AccountancyAccount::Create Erreur $result"; - dol_syslog($this->error, LOG_ERR); - } - } - else - { - $result = -1; - $this->error="AccountancyAccount::Create Erreur $result"; - dol_syslog($this->error, LOG_ERR); - } - - return $result; - } - -} diff --git a/htdocs/accountancy/class/accountancysystem.class.php b/htdocs/accountancy/class/accountancysystem.class.php index 4d81a94985b..7ce2134d0d2 100644 --- a/htdocs/accountancy/class/accountancysystem.class.php +++ b/htdocs/accountancy/class/accountancysystem.class.php @@ -1,5 +1,7 @@ +/* Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,20 +18,18 @@ */ /** - * \file htdocs/accountancy/class/accountancysystem.class.php - * \ingroup accounting - * \brief File of class to manage accountancy systems + * \file htdocs/accountancy/class/accountancysystem.class.php + * \ingroup Accounting Expert + * \brief File of class to manage accountancy systems */ - -/** \class AccountancySystem - * \brief Classe to manage accountancy systems +/** + * Class to manage accountancy systems */ class AccountancySystem { var $db; var $error; - var $rowid; var $fk_pcg_version; var $pcg_type; @@ -38,57 +38,47 @@ class AccountancySystem var $account_number; var $account_parent; - /** - * Constructor + * Constructor * - * @param DoliDB $db Database handler + * @param DoliDB $db handler */ - function __construct($db) - { + function __construct($db) { $this->db = $db; } - /** - * Insert accountancy system name into database + * Insert accountancy system name into database * - * @param User $user User making insert - * @return int <0 if KO, Id of line if OK + * @param User $user making insert + * @return int if KO, Id of line if OK */ - function create($user) - { - $now=dol_now(); + function create($user) { + $now = dol_now(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_system"; - $sql.= " (date_creation, fk_user_author, numero,intitule)"; - $sql.= " VALUES ('".$this->db->idate($now)."',".$user->id.",'".$this->numero."','".$this->intitule."')"; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "accounting_system"; + $sql .= " (date_creation, fk_user_author, numero, label)"; + $sql .= " VALUES (" . $this->db->idate($now) . "," . $user->id . ",'" . $this->numero . "','" . $this->label . "')"; + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - $id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_system"); + if ($resql) { + $id = $this->db->last_insert_id(MAIN_DB_PREFIX . "accounting_system"); - if ($id > 0) - { + if ($id > 0) { $this->id = $id; $result = $this->id; - } - else - { - $result = -2; - $this->error="AccountancySystem::Create Erreur $result"; + } else { + $result = - 2; + $this->error = "AccountancySystem::Create Erreur $result"; dol_syslog($this->error, LOG_ERR); } - } - else - { - $result = -1; - $this->error="AccountancySystem::Create Erreur $result"; + } else { + $result = - 1; + $this->error = "AccountancySystem::Create Erreur $result"; dol_syslog($this->error, LOG_ERR); } return $result; } - -} +} \ No newline at end of file diff --git a/htdocs/accountancy/class/accountingaccount.class.php b/htdocs/accountancy/class/accountingaccount.class.php new file mode 100644 index 00000000000..46a34698785 --- /dev/null +++ b/htdocs/accountancy/class/accountingaccount.class.php @@ -0,0 +1,450 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/class/accountingaccount.class.php + * \ingroup Accounting Expert + * \brief Fichier de la classe des comptes comptable + */ + +/** + * Class to manage accounting accounts + */ +class AccountingAccount +{ + var $db; + var $error; + var $errors; + + var $id; + var $rowid; + + var $datec; // Creation date + var $fk_pcg_version; + var $pcg_type; + var $pcg_subtype; + var $account_number; + var $account_parent; + var $label; + var $fk_user_author; + var $fk_user_modif; + var $active; + + /** + * Constructor + * + * @param DoliDB $db Database handle + */ + function __construct($db) + + { + $this->db = $db; + } + + /** + * Load record in memory + * + * @param int $rowid Id + * @param string $account_number Account number + * @return int <0 if KO, >0 if OK + */ + function fetch($rowid = null, $account_number = null) + { + if ($rowid || $account_number) + { + $sql = "SELECT rowid, datec, tms, fk_pcg_version, pcg_type, pcg_subtype, account_number, account_parent, label, fk_user_author, fk_user_modif, active"; + $sql.= " FROM " . MAIN_DB_PREFIX . "accountingaccount WHERE"; + if ($rowid) { + $sql .= " rowid = '" . $rowid . "'"; + } elseif ($account_number) { + $sql .= " account_number = '" . $account_number . "'"; + } + + dol_syslog(get_class($this) . "::fetch sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + + if ($obj) + { + $this->id = $obj->rowid; + $this->rowid = $obj->rowid; + $this->datec = $obj->datec; + $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; + $this->fk_user_author = $obj->fk_user_author; + $this->fk_user_modif = $obj->fk_user_modif; + $this->active = $obj->active; + + return $this->id; + } + else + { + return 0; + } + } + else + { + dol_print_error($this->db); + } + } + + return -1; + } + + /** + * Insert line in accountingaccount + * + * @param User $user Use making action + * @param int $notrigger Disable triggers + * @return int <0 if KO, >0 if OK + */ + function create($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $now=dol_now(); + + // Clean parameters + if (isset($this->fk_pcg_version)) + $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->account_parent)) + $this->account_parent = trim($this->account_parent); + if (isset($this->label)) + $this->label = trim($this->label); + if (isset($this->fk_user_author)) + $this->fk_user_author = trim($this->fk_user_author); + if (isset($this->active)) + $this->active = trim($this->active); + + // Check parameters + // Put here code to add control on parameters values + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "accountingaccount("; + + $sql .= "datec"; + $sql .= ", entity"; + $sql .= ", fk_pcg_version"; + $sql .= ", pcg_type"; + $sql .= ", pcg_subtype"; + $sql .= ", account_number"; + $sql .= ", account_parent"; + $sql .= ", label"; + $sql .= ", fk_user_author"; + $sql .= ", active"; + + $sql .= ") VALUES ("; + + $sql .= " '" . $this->db->idate($now) . "'"; + $sql .= ", " . $conf->entity; + $sql .= ", " . (! isset($this->fk_pcg_version) ? 'NULL' : "'" . $this->db->escape($this->fk_pcg_version) . "'"); + $sql .= ", " . (! isset($this->pcg_type) ? 'NULL' : "'" . $this->db->escape($this->pcg_type) . "'"); + $sql .= ", " . (! isset($this->pcg_subtype) ? 'NULL' : "'" . $this->pcg_subtype . "'"); + $sql .= ", " . (! isset($this->account_number) ? 'NULL' : "'" . $this->account_number . "'"); + $sql .= ", " . (! isset($this->account_parent) ? 'NULL' : "'" . $this->db->escape($this->account_parent) . "'"); + $sql .= ", " . (! isset($this->label) ? 'NULL' : "'" . $this->db->escape($this->label) . "'"); + $sql .= ", " . $user->id; + $sql .= ", " . (! isset($this->active) ? 'NULL' : "'" . $this->db->escape($this->active) . "'"); + + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (! $error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "accountingaccount"); + + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } + + /** + * Update record + * + * @param User $user Use making update + * @return int <0 if KO, >0 if OK + */ + function update($user) + { + global $langs; + + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "accountingaccount "; + $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->account_number . "'"; + $sql .= " , account_parent = '" . $this->account_parent . "'"; + $sql .= " , label = " . ($this->label ? "'" . $this->db->escape($this->label) . "'" : "null"); + $sql .= " , fk_user_modif = " . $user->id; + $sql .= " , active = '" . $this->active . "'"; + + $sql .= " WHERE rowid = " . $this->id; + + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return - 1; + } + } + + /** + * Check usage of accounting code + * + * @return int <0 if KO, >0 if OK + */ + function checkUsage() + { + global $langs; + + $sql = "(SELECT fk_code_ventilation FROM " . MAIN_DB_PREFIX . "facturedet"; + $sql .= " WHERE fk_code_ventilation=" . $this->id . ")"; + $sql .= "UNION"; + $sql .= "(SELECT fk_code_ventilation FROM " . MAIN_DB_PREFIX . "facture_fourn_det"; + $sql .= " WHERE fk_code_ventilation=" . $this->id . ")"; + + dol_syslog(get_class($this) . "::checkUsage sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $num = $this->db->num_rows($resql); + if ($num > 0) { + $this->error = $langs->trans('ErrorAccountancyCodeIsAlreadyUse'); + return 0; + } else { + return 1; + } + } else { + $this->error = $this->db->lasterror(); + return - 1; + } + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $result = $this->checkUsage(); + + if ($result > 0) { + + $this->db->begin(); + + if (! $error) { + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('ACCOUNTANCY_ACCOUNT_DELETE',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers + } + } + + if (! $error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "accountingaccount"; + $sql .= " WHERE rowid=" . $this->id; + + dol_syslog(get_class($this) . "::delete sql=" . $sql); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return 1; + } + } else { + return - 1; + } + } + + /** + * Information on record + * + * @param int $id of record + * @return void + */ + function info($id) + { + $sql = 'SELECT a.rowid, a.datec, a.fk_user_author, a.fk_user_modif, a.tms'; + $sql .= ' FROM ' . MAIN_DB_PREFIX . 'accountingaccount as a'; + $sql .= ' WHERE a.rowid = ' . $id; + + dol_syslog(get_class($this) . '::info sql=' . $sql); + $result = $this->db->query($sql); + + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + if ($obj->fk_user_modif) { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->tms); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Account desactivate + * + * @param int $id Id + * @return int <0 if KO, >0 if OK + */ + function account_desactivate($id) + { + global $langs; + + $result = $this->checkUsage(); + + if ($result > 0) { + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "accountingaccount "; + $sql .= "SET active = '0'"; + $sql .= " WHERE rowid = ".$this->db->escape($id); + + dol_syslog(get_class($this) . "::desactivate sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + + if ($result) { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return - 1; + } + } else { + return - 1; + } + } + + /** + * Account activate + * + * @param int $id Id + * @return int <0 if KO, >0 if OK + */ + function account_activate($id) + { + global $langs; + + $this->db->begin(); + + $sql = "UPDATE " . MAIN_DB_PREFIX . "accountingaccount "; + $sql .= "SET active = '1'"; + $sql .= " WHERE rowid = ".$this->db->escape($id); + + dol_syslog(get_class($this) . "::activate sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $this->db->commit(); + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->db->rollback(); + return - 1; + } + } +} \ No newline at end of file diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php new file mode 100644 index 00000000000..6291790d008 --- /dev/null +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -0,0 +1,715 @@ + + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/class/bookkeeping.class.php + * \ingroup Accounting Expert + * \brief File of class to manage book keeping + */ + +/** + * Class to manage accountancy book keeping + */ +class BookKeeping +{ + var $db; + var $error; + var $errors; + + var $id; + var $doc_date; + var $doc_type; + var $doc_ref; + var $date_create; + var $fk_doc; + var $fk_docdet; + var $code_tiers; + var $numero_compte; + var $label_compte; + var $debit; + var $credit; + var $montant; + var $sens; + var $fk_user_author; + var $code_journal; + var $piece_num; + var $linesexport = array (); + var $linesmvt = array (); + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + } + + /** + * Load a line into memory from database + * + * @param int $id id of line to get + * @return int <0 if KO, >0 if OK + */ + function fetch($id) + { + $sql = "SELECT rowid, doc_date, doc_type,"; + $sql .= " doc_ref, fk_doc, fk_docdet, code_tiers, "; + $sql .= " numero_compte, label_compte, debit, credit, "; + $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num "; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + $sql .= " WHERE rowid = '" . $id . "'"; + + dol_syslog(get_class($this) . "fetch sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + + $this->id = $obj->rowid; + + $this->doc_date = $this->db->jdate($obj->doc_date); + $this->doc_type = $obj->doc_type; + $this->doc_ref = $obj->doc_ref; + $this->fk_doc = $obj->fk_doc; + $this->fk_docdet = $obj->fk_docdet; + $this->code_tiers = $obj->code_tiers; + $this->numero_compte = $obj->numero_compte; + $this->label_compte = $obj->label_compte; + $this->debit = $obj->debit; + $this->credit = $obj->credit; + $this->montant = $obj->montant; + $this->sens = $obj->sens; + $this->code_journal = $obj->code_journal; + $this->piece_num = $obj->piece_num; + } + else + { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch " . $this->error, LOG_ERR); + return - 1; + } + + return 1; + } + + /** + * Load an accounting document into memory from database + * + * @param int $piecenum Accounting document to get + * @return int <0 if KO, >0 if OK + */ + function fetch_per_mvt($piecenum) + { + $sql = "SELECT piece_num,doc_date,code_journal,doc_ref,doc_type"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping"; + $sql .= " WHERE piece_num = '" . $piecenum . "'"; + + dol_syslog(get_class($this) . "fetch_per_mvt sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + $obj = $this->db->fetch_object($result); + + $this->piece_num = $obj->piece_num; + $this->code_journal = $obj->code_journal; + $this->doc_date = $this->db->jdate($obj->doc_date); + $this->doc_ref = $obj->doc_ref; + $this->doc_type = $obj->doc_type; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch_per_mvt " . $this->error, LOG_ERR); + return - 1; + } + + return 1; + } + + /** + * Return next number movement + * + * @return string Last number + */ + function getNextNumMvt() { + $sql = "SELECT MAX(piece_num)+1 as max FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping"; + + dol_syslog(get_class($this) . "getNextNumMvt sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + + if ($result) + { + $obj = $this->db->fetch_object($result); + + return $obj->max; + } + else + { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::getNextNumMvt " . $this->error, LOG_ERR); + return - 1; + } + } + + /** + * Load all informations of accountancy document + * + * @param int $piecenum id of line to get + * @return int <0 if KO, >0 if OK + */ + function fetch_all_per_mvt($piecenum) + { + $sql = "SELECT rowid, doc_date, doc_type,"; + $sql .= " doc_ref, fk_doc, fk_docdet, code_tiers,"; + $sql .= " numero_compte, label_compte, debit, credit,"; + $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + $sql .= " WHERE piece_num = '" . $piecenum . "'"; + + dol_syslog(get_class($this) . "fetch_all_per_mvt sql=" . $sql, LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) { + + while ( $obj = $this->db->fetch_object($result) ) { + + $line = new BookKeepingLine(); + + $line->id = $obj->rowid; + + $line->doc_date = $this->db->jdate($obj->doc_date); + $line->doc_type = $obj->doc_type; + $line->doc_ref = $obj->doc_ref; + $line->fk_doc = $obj->fk_doc; + $line->fk_docdet = $obj->fk_docdet; + $line->code_tiers = $obj->code_tiers; + $line->numero_compte = $obj->numero_compte; + $line->label_compte = $obj->label_compte; + $line->debit = $obj->debit; + $line->credit = $obj->credit; + $line->montant = $obj->montant; + $line->sens = $obj->sens; + $line->code_journal = $obj->code_journal; + $line->piece_num = $obj->piece_num; + + $this->linesmvt[] = $line; + } + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::fetch_per_mvt " . $this->error, LOG_ERR); + return - 1; + } + + return 1; + } + + /** + * Insert line into bookkeeping + * + * @param User $user User who inserted operation + * @return $result Result + */ + function create($user='') + { + global $conf, $user, $langs; + + $this->piece_num = 0; + + // first check if line not yet in bookkeeping + $sql = "SELECT count(*)"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + $sql .= " WHERE doc_type = '" . $this->doc_type . "'"; + $sql .= " AND fk_docdet = " . $this->fk_docdet; + $sql .= " AND numero_compte = '" . $this->numero_compte . "'"; + + dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + + if ($resql) { + $row = $this->db->fetch_array($resql); + if ($row[0] == 0) { + + // Determine piece_num + $sqlnum = "SELECT piece_num"; + $sqlnum .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + $sqlnum .= " WHERE doc_type = '" . $this->doc_type . "'"; + $sqlnum .= " AND fk_docdet = '" . $this->fk_docdet . "'"; + $sqlnum .= " AND doc_ref = '" . $this->doc_ref . "'"; + + dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); + $resqlnum = $this->db->query($sqlnum); + if ($resqlnum) + { + $objnum = $this->db->fetch_object($resqlnum); + $this->piece_num = $objnum->piece_num; + } + dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG); + if (empty($this->piece_num)) + { + $sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum"; + $sqlnum .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + + dol_syslog(get_class($this) . ":: create sqlnum=" . $sqlnum, LOG_DEBUG); + $resqlnum = $this->db->query($sqlnum); + if ($resqlnum) { + $objnum = $this->db->fetch_object($resqlnum); + $this->piece_num = $objnum->maxpiecenum; + } + } + dol_syslog(get_class($this) . ":: create this->piece_num=" . $this->piece_num, LOG_DEBUG); + if (empty($this->piece_num)) { + $this->piece_num = 1; + } + + $now = dol_now(); + if (empty($this->date_create)) + $this->date_create = $now(); + + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "accounting_bookkeeping (doc_date, "; + $sql .= "doc_type, doc_ref,fk_doc,fk_docdet,code_tiers,numero_compte,label_compte,"; + $sql .= "debit,credit,montant,sens,fk_user_author,import_key,code_journal,piece_num)"; + $sql .= " VALUES ('" . $this->doc_date . "','" . $this->doc_type . "','" . $this->doc_ref . "'," . $this->fk_doc . ","; + $sql .= $this->fk_docdet . ",'" . $this->code_tiers . "','" . $this->numero_compte . "','" . $this->db->escape($this->label_compte) . "',"; + $sql .= $this->debit . "," . $this->credit . "," . $this->montant . ",'" . $this->sens . "'," . $user->id . ", '"; + $sql .= $this->date_create . "','" . $this->code_journal . "'," . $this->piece_num . ")"; + + dol_syslog(get_class($this) . ":: create sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $id = $this->db->last_insert_id(MAIN_DB_PREFIX . "accounting_bookkeeping"); + + if ($id > 0) { + $this->id = $id; + $result = 0; + } else { + $result = - 2; + dol_syslog("BookKeeping::Create Erreur $result lecture ID"); + } + } else { + $result = - 1; + dol_syslog("BookKeeping::Create Erreur $result INSERT Mysql"); + } + } else { + $result = - 3; + dol_syslog("BookKeeping::Create Erreur $result SELECT Mysql"); + } + } else { + $result = - 5; + dol_syslog("BookKeeping::Create Erreur $result SELECT Mysql"); + } + + return $result; + } + + /** + * Delete bookkepping by importkey + * + * @param string $importkey Import key + * @return int Result + */ + function delete_by_importkey($importkey) { + $this->db->begin(); + + // first check if line not yet in bookkeeping + $sql = "DELETE"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping "; + $sql .= " WHERE import_key = '" . $importkey . "'"; + + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Create object into database + * + * @param User $user Object user that create + * @param int $notrigger 1=Does not execute triggers, 0 otherwise + * @return int <0 if KO, >0 if OK + */ + function create_std($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + if (isset($this->doc_type)) + $this->doc_type = trim($this->doc_type); + if (isset($this->doc_ref)) + $this->doc_ref = trim($this->doc_ref); + if (isset($this->fk_doc)) + $this->fk_doc = trim($this->fk_doc); + if (isset($this->fk_docdet)) + $this->fk_docdet = trim($this->fk_docdet); + if (isset($this->code_tiers)) + $this->code_tiers = trim($this->code_tiers); + if (isset($this->numero_compte)) + $this->numero_compte = trim($this->numero_compte); + if (isset($this->label_compte)) + $this->label_compte = trim($this->label_compte); + if (isset($this->debit)) + $this->debit = trim($this->debit); + if (isset($this->credit)) + $this->credit = trim($this->credit); + if (isset($this->montant)) + $this->montant = trim($this->montant); + if (isset($this->sens)) + $this->sens = trim($this->sens); + if (isset($this->fk_user_author)) + $this->fk_user_author = trim($this->fk_user_author); + if (isset($this->import_key)) + $this->import_key = trim($this->import_key); + if (isset($this->code_journal)) + $this->code_journal = trim($this->code_journal); + if (isset($this->piece_num)) + $this->piece_num = trim($this->piece_num); + + // Check parameters + // Put here code to add control on parameters values + + // Insert request + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "accounting_bookkeeping("; + $sql .= "doc_date,"; + $sql .= "doc_type,"; + $sql .= "doc_ref,"; + $sql .= "fk_doc,"; + $sql .= "fk_docdet,"; + $sql .= "code_tiers,"; + $sql .= "numero_compte,"; + $sql .= "label_compte,"; + $sql .= "debit,"; + $sql .= "credit,"; + $sql .= "montant,"; + $sql .= "sens,"; + $sql .= "fk_user_author,"; + $sql .= "import_key,"; + $sql .= "code_journal,"; + $sql .= "piece_num"; + + $sql .= ") VALUES ("; + + $sql .= " " . (! isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : $this->db->idate($this->doc_date)) . ","; + $sql .= " " . (! isset($this->doc_type) ? 'NULL' : "'" . $this->db->escape($this->doc_type) . "'") . ","; + $sql .= " " . (! isset($this->doc_ref) ? 'NULL' : "'" . $this->db->escape($this->doc_ref) . "'") . ","; + $sql .= " " . (! isset($this->fk_doc) ? 'NULL' : "'" . $this->fk_doc . "'") . ","; + $sql .= " " . (! isset($this->fk_docdet) ? 'NULL' : "'" . $this->fk_docdet . "'") . ","; + $sql .= " " . (! isset($this->code_tiers) ? 'NULL' : "'" . $this->db->escape($this->code_tiers) . "'") . ","; + $sql .= " " . (! isset($this->numero_compte) ? 'NULL' : "'" . $this->db->escape($this->numero_compte) . "'") . ","; + $sql .= " " . (! isset($this->label_compte) ? 'NULL' : "'" . $this->db->escape($this->label_compte) . "'") . ","; + $sql .= " " . (! isset($this->debit) ? 'NULL' : "'" . $this->debit . "'") . ","; + $sql .= " " . (! isset($this->credit) ? 'NULL' : "'" . $this->credit . "'") . ","; + $sql .= " " . (! isset($this->montant) ? 'NULL' : "'" . $this->montant . "'") . ","; + $sql .= " " . (! isset($this->sens) ? 'NULL' : "'" . $this->db->escape($this->sens) . "'") . ","; + $sql .= " " . $user->id . ","; + $sql .= " " . (! isset($this->import_key) ? 'NULL' : "'" . $this->db->escape($this->import_key) . "'") . ","; + $sql .= " " . (! isset($this->code_journal) ? 'NULL' : "'" . $this->db->escape($this->code_journal) . "'") . ","; + $sql .= " " . (! isset($this->piece_num) ? 'NULL' : "'" . $this->piece_num . "'") . ""; + + $sql .= ")"; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::create_std sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (! $error) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "accounting_bookkeeping"); + + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::create_std " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return $this->id; + } + } + + /** + * Update object into database + * + * @param User $user Object user that create + * @param int $notrigger 1=Does not execute triggers, 0 otherwise + * @return int <0 if KO, >0 if OK + */ + function update($user = 0, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + if (isset($this->doc_type)) + $this->doc_type = trim($this->doc_type); + if (isset($this->doc_ref)) + $this->doc_ref = trim($this->doc_ref); + if (isset($this->fk_doc)) + $this->fk_doc = trim($this->fk_doc); + if (isset($this->fk_docdet)) + $this->fk_docdet = trim($this->fk_docdet); + if (isset($this->code_tiers)) + $this->code_tiers = trim($this->code_tiers); + if (isset($this->numero_compte)) + $this->numero_compte = trim($this->numero_compte); + if (isset($this->label_compte)) + $this->label_compte = trim($this->label_compte); + if (isset($this->debit)) + $this->debit = trim($this->debit); + if (isset($this->credit)) + $this->credit = trim($this->credit); + if (isset($this->montant)) + $this->montant = trim($this->montant); + if (isset($this->sens)) + $this->sens = trim($this->sens); + if (isset($this->fk_user_author)) + $this->fk_user_author = trim($this->fk_user_author); + if (isset($this->import_key)) + $this->import_key = trim($this->import_key); + if (isset($this->code_journal)) + $this->code_journal = trim($this->code_journal); + if (isset($this->piece_num)) + $this->piece_num = trim($this->piece_num); + + // Check parameters + // Put here code to add a control on parameters values + + // Update request + $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET"; + + $sql .= " doc_date=" . (dol_strlen($this->doc_date) != 0 ? "'" . $this->db->idate($this->doc_date) . "'" : 'null') . ","; + $sql .= " doc_type=" . (isset($this->doc_type) ? "'" . $this->db->escape($this->doc_type) . "'" : "null") . ","; + $sql .= " doc_ref=" . (isset($this->doc_ref) ? "'" . $this->db->escape($this->doc_ref) . "'" : "null") . ","; + $sql .= " fk_doc=" . (isset($this->fk_doc) ? $this->fk_doc : "null") . ","; + $sql .= " fk_docdet=" . (isset($this->fk_docdet) ? $this->fk_docdet : "null") . ","; + $sql .= " code_tiers=" . (isset($this->code_tiers) ? "'" . $this->db->escape($this->code_tiers) . "'" : "null") . ","; + $sql .= " numero_compte=" . (isset($this->numero_compte) ? "'" . $this->db->escape($this->numero_compte) . "'" : "null") . ","; + $sql .= " label_compte=" . (isset($this->label_compte) ? "'" . $this->db->escape($this->label_compte) . "'" : "null") . ","; + $sql .= " debit=" . (isset($this->debit) ? $this->debit : "null") . ","; + $sql .= " credit=" . (isset($this->credit) ? $this->credit : "null") . ","; + $sql .= " montant=" . (isset($this->montant) ? $this->montant : "null") . ","; + $sql .= " sens=" . (isset($this->sens) ? "'" . $this->db->escape($this->sens) . "'" : "null") . ","; + $sql .= " fk_user_author=" . (isset($this->fk_user_author) ? $this->fk_user_author : "null") . ","; + $sql .= " import_key=" . (isset($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null") . ","; + $sql .= " code_journal=" . (isset($this->code_journal) ? "'" . $this->db->escape($this->code_journal) . "'" : "null") . ","; + $sql .= " piece_num=" . (isset($this->piece_num) ? $this->piece_num : "null") . ""; + + $sql .= " WHERE rowid=" . $this->id; + + $this->db->begin(); + + dol_syslog(get_class($this) . "::update sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + + if (! $error) { + if (! $notrigger) { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + // // Call triggers + // include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + // $interface=new Interfaces($this->db); + // $result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf); + // if ($result < 0) { $error++; $this->errors=$interface->errors; } + // // End call triggers + } + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } else { + $this->db->commit(); + return 1; + } + } + + /** + * Delete object in database + * + * @param User $user Object user that create + * @param int $notrigger 1=Does not execute triggers, 0 otherwise + * @return int <0 if KO, >0 if OK + */ + function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + $this->db->begin(); + + if (! $error) + { + if (! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ACCOUNTING_NUMPIECE_DELETE',$user); + if ($result < 0) $error++; + // End call triggers + } + } + + if (! $error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping"; + $sql .= " WHERE rowid=" . $this->id; + + dol_syslog(get_class($this) . "::delete sql=" . $sql); + $resql = $this->db->query($sql); + if (! $resql) { + $error ++; + $this->errors[] = "Error " . $this->db->lasterror(); + } + } + + // Commit or rollback + if ($error) { + foreach ( $this->errors as $errmsg ) { + dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR); + $this->error .= ($this->error ? ', ' . $errmsg : $errmsg); + } + $this->db->rollback(); + return - 1 * $error; + } + else + { + $this->db->commit(); + return 1; + } + } + + /** + * Delete bookkepping by importkey + * + * @param string $model Model + * @return int Result + */ + function export_bookkeping($model = 'ebp') + { + $sql = "SELECT rowid, doc_date, doc_type,"; + $sql .= " doc_ref, fk_doc, fk_docdet, code_tiers,"; + $sql .= " numero_compte, label_compte, debit, credit,"; + $sql .= " montant, sens, fk_user_author, import_key, code_journal, piece_num"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping"; + + $resql = $this->db->query($sql); + + dol_syslog(get_class($this) . "::export_bookkeping sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $this->linesexport = array (); + + $num = $this->db->num_rows($resql); + while ( $obj = $this->db->fetch_object($resql) ) { + $line = new BookKeepingLine(); + + $line->id = $obj->rowid; + + $line->doc_date = $this->db->jdate($obj->doc_date); + $line->doc_type = $obj->doc_type; + $line->doc_ref = $obj->doc_ref; + $line->fk_doc = $obj->fk_doc; + $line->fk_docdet = $obj->fk_docdet; + $line->code_tiers = $obj->code_tiers; + $line->numero_compte = $obj->numero_compte; + $line->label_compte = $obj->label_compte; + $line->debit = $obj->debit; + $line->credit = $obj->credit; + $line->montant = $obj->montant; + $line->sens = $obj->sens; + $line->code_journal = $obj->code_journal; + $line->piece_num = $obj->piece_num; + + $this->linesexport[] = $line; + } + $this->db->free($resql); + + return $num; + } + else + { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::export_bookkeping " . $this->error, LOG_ERR); + return - 1; + } + } +} + +/** + * Class BookKeepingLine + */ +class BookKeepingLine +{ + var $id; + var $doc_date; + var $doc_type; + var $doc_ref; + var $fk_doc; + var $fk_docdet; + var $code_tiers; + var $numero_compte; + var $label_compte; + var $debit; + var $credit; + var $montant; + var $sens; + var $fk_user_author; + var $code_journal; + var $piece_num; +} \ No newline at end of file diff --git a/htdocs/accountancy/class/html.formventilation.class.php b/htdocs/accountancy/class/html.formventilation.class.php new file mode 100644 index 00000000000..33bb33a2353 --- /dev/null +++ b/htdocs/accountancy/class/html.formventilation.class.php @@ -0,0 +1,263 @@ + + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/class/html.formventilation.class.php + * \ingroup Accounting Expert + * \brief File of class with all html predefined components + */ + +/** + * Class to manage generation of HTML components for bank module + */ +class FormVentilation extends Form +{ + var $db; + var $error; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + /** + * Return select filter with date of transaction + * + * @param string $htmlname Name of select field + * @param string $selectedkey Value + * @return string HTML edit field + */ + function select_bookkeeping_importkey($htmlname = 'importkey', $selectedkey='') + { + global $langs; + + $date_array = array (); + + $sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping'; + $sql .= ' ORDER BY import_key DESC'; + + $out = ''; + + return $out; + } + + /** + * Return list of accounts with label by chart of accounts + * + * @param string $selectid Preselected chart of accounts + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * + * @return string String with HTML select + */ + function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array()) + { + global $conf, $user, $langs; + + $out = ''; + + $sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version"; + $sql .= " FROM " . MAIN_DB_PREFIX . "accountingaccount as aa"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS; + $sql .= " AND aa.active = 1"; + $sql .= " ORDER BY aa.account_number"; + + dol_syslog(get_class($this) . "::select_account sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + + $out .= ajax_combobox($htmlname, $event); + $out .= ''; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR); + return - 1; + } + $this->db->free($resql); + return $out; + } + + /** + * Return list of accounts with label by class of accounts + * + * @param string $selectid Preselected pcg_type + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * + * @return string String with HTML select + */ + function select_pcgtype($selectid, $htmlname = 'pcg_type', $showempty = 0, $event = array()) + { + global $conf, $user, $langs; + + $out = ''; + + $sql = "SELECT DISTINCT pcg_type "; + $sql .= " FROM " . MAIN_DB_PREFIX . "accountingaccount as aa"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS; + $sql .= " ORDER BY pcg_type"; + + dol_syslog(get_class($this) . "::select_pcgtype sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + + $out .= ajax_combobox($htmlname, $event); + + $out .= ''; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::select_pcgtype " . $this->error, LOG_ERR); + return - 1; + } + $this->db->free($resql); + return $out; + } + + /** + * Return list of accounts with label by sub_class of accounts + * + * @param string $selectid Preselected pcg_type + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * + * @return string String with HTML select + */ + function select_pcgsubtype($selectid, $htmlname = 'pcg_subtype', $showempty = 0, $event = array()) + { + global $conf, $user, $langs; + + $out = ''; + + $sql = "SELECT DISTINCT pcg_subtype "; + $sql .= " FROM " . MAIN_DB_PREFIX . "accountingaccount as aa"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; + $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS; + $sql .= " ORDER BY pcg_subtype"; + + dol_syslog(get_class($this) . "::select_pcgsubtype sql=" . $sql, LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + + $out .= ajax_combobox($htmlname, $event); + + $out .= ''; + } else { + $this->error = "Error " . $this->db->lasterror(); + dol_syslog(get_class($this) . "::select_pcgsubtype " . $this->error, LOG_ERR); + return - 1; + } + $this->db->free($resql); + return $out; + } +} diff --git a/htdocs/accountancy/class/index.html b/htdocs/accountancy/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/customer/card.php b/htdocs/accountancy/customer/card.php new file mode 100644 index 00000000000..28d3d0c1f79 --- /dev/null +++ b/htdocs/accountancy/customer/card.php @@ -0,0 +1,145 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/customer/card.php + * \ingroup Accounting Expert + * \brief Card customer ventilation + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("bills"); +$langs->load("accountancy"); + +$action = GETPOST('action', 'alpha'); +$codeventil = GETPOST('codeventil'); +$id = GETPOST('id'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +/* + * Actions + */ + +if ($action == 'ventil' && $user->rights->accounting->ventilation->dispatch) +{ + if (! GETPOST('cancel', 'alpha')) + { + $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; + $sql .= " SET fk_code_ventilation = " . $codeventil; + $sql .= " WHERE rowid = " . $id; + + dol_syslog("/accounting/customer/card.php sql=" . $sql, LOG_DEBUG); + $resql = $db->query($sql); + if (! $resql) { + setEventMessage($db->lasterror(), 'errors'); + } + } else { + header("Location: ./lines.php"); + exit(); + } +} + +llxHeader("", "", "FicheVentilation"); + +if ($cancel == $langs->trans("Cancel")) { + $action = ''; +} + +/* + * Create + */ +$form = new Form($db); +$facture_static = new Facture($db); +$formventilation = new FormVentilation($db); + +if (! empty($id)) { + $sql = "SELECT f.facnumber, f.rowid as facid, l.fk_product, l.description, l.price,"; + $sql .= " l.qty, l.rowid, l.tva_tx, l.remise_percent, l.subprice, p.accountancy_code_sell as code_sell,"; + $sql .= " l.fk_code_ventilation, aa.account_number, aa.label"; + $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as l"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON l.fk_code_ventilation = aa.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = l.fk_facture"; + $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; + + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; + } + + dol_syslog("/accounting/customer/card.php sql=" . $sql, LOG_DEBUG); + $result = $db->query($sql); + + if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + if ($num_lines) { + + $objp = $db->fetch_object($result); + + print '
' . "\n"; + print ''; + print ''; + + $linkback=''.$langs->trans("Back").''; + print_fiche_titre($langs->trans('CustomersVentilation'),$linkback,'setup'); + + print ''; + + // Ref facture + print ''; + $facture_static->ref = $objp->facnumber; + $facture_static->id = $objp->facid; + print ''; + print ''; + + print ''; + print ''; + print ''; + print '
' . $langs->trans("Invoice") . '' . $facture_static->getNomUrl(1) . '
' . $langs->trans("Line") . '' . nl2br($objp->description) . '
' . $langs->trans("Account") . ''; + print $objp->account_number . '-' . $objp->label; + print '
' . $langs->trans("NewAccount") . ''; + print $formventilation->select_account($objp->fk_code_ventilation, 'codeventil', 1); + print '
'; + + print '
    '; + print ''; + } else { + print "Error"; + } + } else { + print "Error"; + } +} else { + print "Error ID incorrect"; +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/customer/index.html b/htdocs/accountancy/customer/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php new file mode 100644 index 00000000000..663e763a9d3 --- /dev/null +++ b/htdocs/accountancy/customer/index.php @@ -0,0 +1,342 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/customer/index.php + * \ingroup Accounting Expert + * \brief Page accueil clients ventilation comptable + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->read) + accessforbidden(); + +// Filter +$year = $_GET["year"]; +if ($year == 0) { + $year_current = strftime("%Y", time()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} + +// Validate History +$action = GETPOST('action'); +if ($action == 'validatehistory') { + + $error = 0; + $db->begin(); + + if ($db->type == 'pgsql') { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd"; + $sql1 .= " SET fd.fk_code_ventilation = accnt.rowid"; + $sql1 .= " FROM " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accountingaccount as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " WHERE fd.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_sell=accnt.account_number"; + $sql1 .= " AND fd.fk_code_ventilation = 0"; + } else { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as fd, " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accountingaccount as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " SET fd.fk_code_ventilation = accnt.rowid"; + $sql1 .= " WHERE fd.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_sell=accnt.account_number"; + $sql1 .= " AND fd.fk_code_ventilation = 0"; + } + + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } else { + $db->commit(); + setEventMessage($langs->trans('Dispatched'), 'mesgs'); + } +} + +/* + * View + */ +llxHeader('', $langs->trans("CustomersVentilation")); + +$textprevyear = '' . img_previous() . ''; +$textnextyear = ' ' . img_next() . ''; + +print_fiche_titre($langs->trans("CustomersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear); + +print '' . $langs->trans("DescVentilCustomer") . ''; +print ''; + +$sql = "SELECT count(*) FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " , " . MAIN_DB_PREFIX . "facture as f"; +$sql .= " WHERE fd.fk_code_ventilation = 0"; +$sql .= " AND f.rowid = fd.fk_facture AND f.fk_statut = 1;"; + +$result = $db->query($sql); +if ($result) { + $row = $db->fetch_row($result); + $nbfac = $row[0]; + $db->free($result); +} + +$y = $year_current; + +$var = true; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$sql = "SELECT IF(aa.account_number IS NULL, 'Non pointe', aa.account_number) AS 'code comptable',"; +$sql .= " IF(aa.label IS NULL, 'Non pointe', aa.label) AS 'Intitulé',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=1,fd.total_ht,0)),2) AS 'Janvier',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=2,fd.total_ht,0)),2) AS 'Fevrier',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=3,fd.total_ht,0)),2) AS 'Mars',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=4,fd.total_ht,0)),2) AS 'Avril',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=5,fd.total_ht,0)),2) AS 'Mai',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=6,fd.total_ht,0)),2) AS 'Juin',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=7,fd.total_ht,0)),2) AS 'Juillet',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=8,fd.total_ht,0)),2) AS 'Aout',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=9,fd.total_ht,0)),2) AS 'Septembre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=10,fd.total_ht,0)),2) AS 'Octobre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=11,fd.total_ht,0)),2) AS 'Novembre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=12,fd.total_ht,0)),2) AS 'Decembre',"; +$sql .= " ROUND(SUM(fd.total_ht),2) as 'Total'"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON aa.rowid = fd.fk_code_ventilation"; +$sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$sql .= " GROUP BY fd.fk_code_ventilation"; + +$resql = $db->query($sql); +if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i ++; + } + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . '' . $langs->trans("Total") . '
' . length_accountg($row[0]) . '' . $row[1] . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '' . price($row[14]) . '
\n"; + +print "
\n"; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$sql = "SELECT '" . $langs->trans("TotalVente") . "' AS 'Total',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=1,fd.total_ht,0)),2) AS 'Janvier',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=2,fd.total_ht,0)),2) AS 'Fevrier',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=3,fd.total_ht,0)),2) AS 'Mars',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=4,fd.total_ht,0)),2) AS 'Avril',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=5,fd.total_ht,0)),2) AS 'Mai',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=6,fd.total_ht,0)),2) AS 'Juin',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=7,fd.total_ht,0)),2) AS 'Juillet',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=8,fd.total_ht,0)),2) AS 'Aout',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=9,fd.total_ht,0)),2) AS 'Septembre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=10,fd.total_ht,0)),2) AS 'Octobre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=11,fd.total_ht,0)),2) AS 'Novembre',"; +$sql .= " ROUND(SUM(IF(MONTH(f.datef)=12,fd.total_ht,0)),2) AS 'Decembre',"; +$sql .= " ROUND(SUM(fd.total_ht),2) as 'Total'"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; +$sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$resql = $db->query($sql); +if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i ++; + } + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Total") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . '' . $langs->trans("Total") . '
' . $row[0] . '' . price($row[1]) . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '
\n"; + +if (! empty($conf->margin->enabled)) { + print "
\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $sql = "SELECT '" . $langs->trans("Vide") . "' AS 'Marge',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=1,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Janvier',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=2,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Fevrier',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=3,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Mars',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=4,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Avril',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=5,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Mai',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=6,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Juin',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=7,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Juillet',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=8,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Aout',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=9,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Septembre',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=10,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Octobre',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=11,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Novembre',"; + $sql .= " ROUND(SUM(IF(MONTH(f.datef)=12,(fd.total_ht-(fd.qty * fd.buy_price_ht)),0)),2) AS 'Decembre',"; + $sql .= " ROUND(SUM((fd.total_ht-(fd.qty * fd.buy_price_ht))),2) as 'Total'"; + $sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; + $sql .= " WHERE f.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; + $sql .= " AND f.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; + + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; + } + + $resql = $db->query($sql); + if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i ++; + } + $db->free($resql); + } else { + print $db->lasterror(); // Show last sql error + } + print "
' . $langs->trans("TotalMarge") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . '' . $langs->trans("Total") . '
' . $row[0] . '' . price($row[1]) . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '
\n"; +} +print "\n"; +print ''; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php new file mode 100644 index 00000000000..9215d5a9d98 --- /dev/null +++ b/htdocs/accountancy/customer/lines.php @@ -0,0 +1,224 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Ari Elbaz (elarifr) + * Copyright (C) 2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/customer/lines.php + * \ingroup Accounting Expert + * \brief Page of detail of the lines of ventilation of invoices customers + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + +// langs +$langs->load("bills"); +$langs->load("compta"); +$langs->load("main"); +$langs->load("accountancy"); + +$account_parent = GETPOST('account_parent'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->dispatch) + accessforbidden(); + +$formventilation = new FormVentilation($db); + +// change account + +$changeaccount = GETPOST('changeaccount'); + +$is_search = GETPOST('button_search_x'); + +if (is_array($changeaccount) && count($changeaccount) > 0 && empty($is_search)) { + $error = 0; + + $db->begin(); + + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facturedet as l"; + $sql1 .= " SET l.fk_code_ventilation=" . $account_parent; + $sql1 .= ' WHERE l.rowid IN (' . implode(',', $changeaccount) . ')'; + + dol_syslog('accountancy/customer/lines.php::changeaccount sql= ' . $sql1); + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + setEventMessage($db->lasterror(), 'errors'); + } + if (! $error) { + $db->commit(); + setEventMessage($langs->trans('Save'), 'mesgs'); + } else { + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } +} + +/* + * View + */ + +llxHeader('', $langs->trans("CustomersVentilation") . ' - ' . $langs->trans("Dispatched")); + +$page = GETPOST("page"); +if ($page < 0) + $page = 0; + +if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { + $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; +} elseif ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { + $limit = $conf->liste_limit; +} else { + $limit = $conf->liste_limit; +} + +$offset = $limit * $page; + +$sql = "SELECT l.rowid , f.facnumber, f.rowid as facid, l.fk_product, l.description, l.total_ht, l.qty, l.tva_tx, l.fk_code_ventilation, aa.label, aa.account_number,"; +$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture as f"; +$sql .= " , " . MAIN_DB_PREFIX . "accountingaccount as aa"; +$sql .= " , " . MAIN_DB_PREFIX . "facturedet as l"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; +$sql .= " WHERE f.rowid = l.fk_facture AND f.fk_statut >= 1 AND l.fk_code_ventilation <> 0 "; +$sql .= " AND aa.rowid = l.fk_code_ventilation"; +if (strlen(trim(GETPOST("search_facture")))) { + $sql .= " AND f.facnumber like '%" . GETPOST("search_facture") . "%'"; +} +if (strlen(trim(GETPOST("search_ref")))) { + $sql .= " AND p.ref like '%" . GETPOST("search_ref") . "%'"; +} +if (strlen(trim(GETPOST("search_label")))) { + $sql .= " AND p.label like '%" . GETPOST("search_label") . "%'"; +} +if (strlen(trim(GETPOST("search_desc")))) { + $sql .= " AND l.description like '%" . GETPOST("search_desc") . "%'"; +} +if (strlen(trim(GETPOST("search_account")))) { + $sql .= " AND aa.account_number like '%" . GETPOST("search_account") . "%'"; +} + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$sql .= " ORDER BY l.rowid"; +if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) { + $sql .= " DESC "; +} +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog("/accountancy/customer/linges.php sql=" . $sql, LOG_DEBUG); +$result = $db->query($sql); +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + // TODO : print_barre_liste always use $conf->liste_limit and do not care about custom limit in list... + print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + + print '' . $langs->trans("DescVentilDoneCustomer") . ''; + + print ''; + print ''; + + print '

' . $langs->trans("ChangeAccount"); + print $formventilation->select_account($account_parent, 'account_parent', 1); + print '
'; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $facture_static = new Facture($db); + $product_static = new Product($db); + + $var = True; + while ( $objp = $db->fetch_object($result) ) { + $var = ! $var; + $codeCompta = $objp->account_number . ' ' . $objp->label; + + print ""; + + // Ref facture + $facture_static->ref = $objp->facnumber; + $facture_static->id = $objp->facid; + print ''; + + // Ref produit + $product_static->ref = $objp->product_ref; + $product_static->id = $objp->product_id; + $product_static->type = $objp->type; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + + print ""; + $i ++; + } +} else { + print $db->error(); +} + +print "
' . $langs->trans("Invoice") . '' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("Description") . '' . $langs->trans("Amount") . '' . $langs->trans("Account") . '  
  '; + print ''; + print ' 
' . $facture_static->getNomUrl(1) . ''; + if ($product_static->id) + print $product_static->getNomUrl(1); + else + print ' '; + print '' . dol_trunc($objp->product_label, 24) . '' . nl2br(dol_trunc($objp->description, 32)) . '' . price($objp->total_ht) . '' . $codeCompta . '' . $objp->rowid . ''; + print img_edit(); + print '
"; + +$db->close(); +llxFooter(); \ No newline at end of file diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php new file mode 100644 index 00000000000..3b68bd6b69e --- /dev/null +++ b/htdocs/accountancy/customer/list.php @@ -0,0 +1,238 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Ari Elbaz (elarifr) + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/customer/list.php + * \ingroup Accounting Expert + * \brief Ventilation page from customers invoices + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("main"); +$langs->load("accountancy"); + +$action = GETPOST('action'); +$codeventil = GETPOST('codeventil', 'array'); +$mesCasesCochees = GETPOST('mesCasesCochees', 'array'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->dispatch) + accessforbidden(); + +$formventilation = new FormVentilation($db); + +llxHeader('', $langs->trans("Ventilation")); + +/* + * Action +*/ + +if ($action == 'ventil') { + print '
' . $langs->trans("Processing") . '...
'; + if (! empty($codeventil) && ! empty($mesCasesCochees)) { + print '
' . count($mesCasesCochees) . ' ' . $langs->trans("SelectedLines") . '
'; + $mesCodesVentilChoisis = $codeventil; + $cpt = 0; + foreach ( $mesCasesCochees as $maLigneCochee ) { + // print '
id selectionnee : '.$monChoix."
"; + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monNumLigne = $maLigneCourante[1]; + $monCompte = $mesCodesVentilChoisis[$monNumLigne]; + + $sql = " UPDATE " . MAIN_DB_PREFIX . "facturedet"; + $sql .= " SET fk_code_ventilation = " . $monCompte; + $sql .= " WHERE rowid = " . $monId; + + dol_syslog("/accountancy/customer/list.php sql=" . $sql, LOG_DEBUG); + if ($db->query($sql)) { + print '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' ' . $langs->trans("VentilatedinAccount") . ' : ' . $monCompte . '
'; + } else { + print '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' ' . $langs->trans("NotVentilatedinAccount") . ' : ' . $monCompte . '
' . $sql . '
'; + } + + $cpt ++; + } + } else { + print '
' . $langs->trans("AnyLineVentilate") . '
'; + } + print '
' . $langs->trans("EndProcessing") . '
'; +} + +/* + * Customer Invoice lines + */ +$page = GETPOST('page'); +if ($page < 0) + $page = 0; + +if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { + $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; +} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { + $limit = $conf->liste_limit; +} else { + $limit = $conf->liste_limit; +} + +$offset = $limit * $page; + +$sql = "SELECT f.facnumber, f.rowid as facid, l.fk_product, l.description, l.total_ht, l.rowid, l.fk_code_ventilation,"; +$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"; +$sql .= " , aa.rowid as aarowid"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture as f"; +$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facturedet as l ON f.rowid = l.fk_facture"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON p.accountancy_code_sell = aa.account_number"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_system as accsys ON accsys.pcg_version = aa.fk_pcg_version"; +$sql .= " WHERE f.fk_statut > 0 AND fk_code_ventilation = 0"; +$sql .= " AND (accsys.rowid='".$conf->global->CHARTOFACCOUNTS."' OR p.accountancy_code_sell IS NULL)"; +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$sql .= " ORDER BY l.rowid"; +if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) { + $sql .= " DESC "; +} +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog("/accountancy/customer/list.php sql=" . $sql, LOG_DEBUG); +$result = $db->query($sql); +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + // TODO : print_barre_liste always use $conf->liste_limit and do not care about custom limit in list... + print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + + print '
' . $langs->trans("DescVentilTodoCustomer") . '
'; + + print '
' . "\n"; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $facture_static = new Facture($db); + $product_static = new Product($db); + $form = new Form($db); + + $var = True; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + + // product_type: 0 = service ? 1 = product + // if product does not exist we use the value of product_type provided in facturedet to define if this is a product or service + // issue : if we change product_type value in product DB it should differ from the value stored in facturedet DB ! + $code_sell_notset = ''; + + if (empty($objp->code_sell)) { + $code_sell_notset = 'color:red'; + + if (! empty($objp->type)) { + if ($objp->type == 1) { + $objp->code_sell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } else { + $objp->code_sell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } + } else { + $code_sell_notset = 'color:blue'; + + if ($objp->type == 1) { + $objp->code_sell = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } else { + $objp->code_sell = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } + } + } + + print ""; + + // Ref facture + $facture_static->ref = $objp->facnumber; + $facture_static->id = $objp->facid; + print ''; + + // Ref produit + $product_static->ref = $objp->product_ref; + $product_static->id = $objp->product_id; + $product_static->type = $objp->type; + print ''; + + print ''; + print ''; + + print ''; + + print ''; + + // Colonne choix du compte + print ''; + + // Colonne choix ligne a ventiler + print ''; + + print ''; + $i ++; + } + + print '
' . $langs->trans("Invoice") . '' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("Description") . '' . $langs->trans("Amount") . '' . $langs->trans("AccountAccounting") . '' . $langs->trans("IntoAccount") . '' . $langs->trans("Ventilate") . '
' . $facture_static->getNomUrl(1) . ''; + if ($product_static->id) + print $product_static->getNomUrl(1); + else + print ' '; + print '' . dol_trunc($objp->product_label, 24) . '' . nl2br(dol_trunc($objp->description, 32)) . ''; + print price($objp->total_ht); + print ''; + print $objp->code_sell; + print ''; + print $formventilation->select_account($objp->aarowid, 'codeventil[]', 1); + print ''; + print 'aarowid ? "checked" : "") . '/>'; + print '
'; + print '
'; + print '
'; +} else { + print $db->error(); +} + +$db->close(); +llxFooter(); \ No newline at end of file diff --git a/htdocs/accountancy/index.html b/htdocs/accountancy/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/accountancy/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php new file mode 100644 index 00000000000..1f9b0549121 --- /dev/null +++ b/htdocs/accountancy/journal/bankjournal.php @@ -0,0 +1,590 @@ + + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013 Christophe Battarel + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Olivier Geffroy + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/journal/bankjournal.php + * \ingroup Accounting Expert + * \brief Page with sells journal + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; + +// Langs +$langs->load("companies"); +$langs->load("other"); +$langs->load("compta"); +$langs->load("bank"); +$langs->load('bills'); +$langs->load("accountancy"); + +$id_accountancy_journal = GETPOST('id_account'); + +$date_startmonth = GETPOST('date_startmonth'); +$date_startday = GETPOST('date_startday'); +$date_startyear = GETPOST('date_startyear'); +$date_endmonth = GETPOST('date_endmonth'); +$date_endday = GETPOST('date_endday'); +$date_endyear = GETPOST('date_endyear'); +$action = GETPOST('action'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +/* + * View + */ +if (empty($id_accountancy_journal)) +{ + accessforbidden(); +} + +$year_current = strftime("%Y", dol_now()); +$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonthyear = $year_current; +if ($pastmonth == 0) { + $pastmonth = 12; + $pastmonthyear --; +} + +$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); +} + +$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$idpays = $p[0]; + +$sql = "SELECT b.rowid , b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, soc.code_compta, ba.courant,"; +$sql .= " soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, ba.account_number, bu1.type as typeop"; +$sql .= " FROM " . MAIN_DB_PREFIX . "bank b"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "bank_account ba on b.fk_account=ba.rowid"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe soc on bu1.url_id=soc.rowid"; +// To isolate the cash of the other accounts +$sql .= " WHERE ba.courant <> 2"; +$sql .= " AND ba.rowid=".$id_accountancy_journal; +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND ba.entity = " . $conf->entity; +} +if ($date_start && $date_end) + $sql .= " AND b.dateo >= '" . $db->idate($date_start) . "' AND b.dateo <= '" . $db->idate($date_end) . "'"; +$sql .= " ORDER BY b.datev"; + +$object = new Account($db); +$paymentstatic = new Paiement($db); +$paymentsupplierstatic = new PaiementFourn($db); +$societestatic = new Societe($db); +$chargestatic = new ChargeSociales($db); +$paymentvatstatic = new TVA($db); +$paymentsalstatic = new PaymentSalary($db); + +dol_syslog("accountancy/journal/bankjournal.php:: sql=" . $sql, LOG_DEBUG); +$result = $db->query($sql); +if ($result) { + + $num = $db->num_rows($result); + // Variables + $cptfour = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef")); + $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); + $cpttva = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) ? $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE : $langs->trans("CodeNotDef")); + $accountancy_account_salary = (! empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : $langs->trans("CodeNotDef")); + + $tabpay = array (); + $tabbq = array (); + $tabtp = array (); + $tabtype = array (); + + $i = 0; + while ( $i < $num ) + { + $obj = $db->fetch_object($result); + + $tabcompany[$obj->rowid] = array( + 'id' => $obj->socid, + 'name' => $obj->name, + 'code_client' => $obj->code_compta + ); + + // Controls + $compta_bank = $obj->account_number; + if ($obj->label == '(SupplierInvoicePayment)') + $compta_soc = (! empty($obj->code_compta_fournisseur) ? $obj->code_compta_fournisseur : $cptfour); + if ($obj->label == '(CustomerInvoicePayment)') + $compta_soc = (! empty($obj->code_compta) ? $obj->code_compta : $cptcli); + if ($obj->typeop == '(BankTransfert)') + $compta_soc = $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH; + + // Variable bookkeeping + $tabpay[$obj->rowid]["date"] = $obj->do; + $tabpay[$obj->rowid]["type_payment"] = $obj->fk_type; + $tabpay[$obj->rowid]["ref"] = $obj->label; + $tabpay[$obj->rowid]["fk_bank"] = $obj->rowid; + if (preg_match('/^\((.*)\)$/i', $obj->label, $reg)) { + $tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]); + } else { + $tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60); + } + $links = $object->get_url($obj->rowid); + + foreach ( $links as $key => $val ) + { + $tabtype[$obj->rowid] = $links[$key]['type']; + + if ($links[$key]['type'] == 'payment') + { + $paymentstatic->id = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentstatic->getNomUrl(2); + } + else if ($links[$key]['type'] == 'payment_supplier') + { + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsupplierstatic->getNomUrl(2); + } + else if ($links[$key]['type'] == 'company') + { + $societestatic->id = $links[$key]['url_id']; + $societestatic->name = $links[$key]['label']; + $tabpay[$obj->rowid]["soclib"] = $societestatic->getNomUrl(1, '', 30); + $tabtp[$obj->rowid][$compta_soc] += $obj->amount; + } + else if ($links[$key]['type'] == 'sc') + { + $chargestatic->id = $links[$key]['url_id']; + $chargestatic->ref = $links[$key]['url_id']; + + $tabpay[$obj->rowid]["lib"] .= ' ' . $chargestatic->getNomUrl(2); + if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) { + if ($reg[1] == 'socialcontribution') + $reg[1] = 'SocialContribution'; + $chargestatic->lib = $langs->trans($reg[1]); + } + else + { + $chargestatic->lib = $links[$key]['label']; + } + $chargestatic->ref = $chargestatic->lib; + $tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30); + + $sqlmid = 'SELECT cchgsoc.accountancy_code'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "c_chargesociales cchgsoc "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "chargesociales as chgsoc ON chgsoc.fk_type=cchgsoc.id"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementcharge as paycharg ON paycharg.fk_charge=chgsoc.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "bank_url as bkurl ON bkurl.url_id=paycharg.rowid"; + $sqlmid .= " WHERE bkurl.fk_bank=" . $obj->rowid; + + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) + { + $objmid = $db->fetch_object($resultmid); + $tabtp[$obj->rowid][$objmid->accountancy_code] += $obj->amount; + } + } + else if ($links[$key]['type'] == 'payment_vat') + { + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvatstatic->getNomUrl(2); + $tabtp[$obj->rowid][$cpttva] += $obj->amount; + } + else if ($links[$key]['type'] == 'payment_salary') + { + $paymentsalstatic->id = $links[$key]['url_id']; + $paymentsalstatic->ref = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsalstatic->getNomUrl(2); + $tabtp[$obj->rowid][$accountancy_account_salary] += $obj->amount; + } + else if ($links[$key]['type'] == 'banktransfert') + { + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvatstatic->getNomUrl(2); + $tabtp[$obj->rowid][$cpttva] += $obj->amount; + } + /*else { + $tabtp [$obj->rowid] [$accountancy_account_salary] += $obj->amount; + }*/ + } + $tabbq[$obj->rowid][$compta_bank] += $obj->amount; + + // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount; + + $i ++; + } +} else { + dol_print_error($db); +} + +/* + * Actions + */ + +// Write bookkeeping +if ($action == 'writeBookKeeping') +{ + $error = 0; + foreach ( $tabpay as $key => $val ) + { + // Bank + foreach ( $tabbq[$key] as $k => $mt ) + { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'bank'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = $compte->label; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt >= 0 ? $mt : 0); + $bookkeeping->credit = ($mt < 0 ? - $mt : 0); + $bookkeeping->code_journal = $conf->global->ACCOUNTING_BANK_JOURNAL; + + if ($tabtype[$key] == 'payment') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + } else if ($tabtype[$key] == 'payment_supplier') { + + $sqlmid = 'SELECT facf.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + } + + $result = $bookkeeping->create(); + if ($result < 0) { + $error ++; + setEventMessage($object->errors, 'errors'); + } + } + // Third party + foreach ( $tabtp[$key] as $k => $mt ) + { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'banque'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0 ? - $mt : 0); + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_BANK_JOURNAL; + + if ($tabtype[$key] == 'sc') { + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + } else if ($tabtype[$key] == 'payment') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } else if ($tabtype[$key] == 'payment_supplier') { + + $sqlmid = 'SELECT facf.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER; + } else if ($tabtype[$key] == 'company') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/bankjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } else { + + $bookkeeping->doc_ref = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } + + $result = $bookkeeping->create(); + if ($result < 0) { + $error ++; + setEventMessage($object->errors, 'errors'); + } + } + } + + if (empty($error)) { + setEventMessage($langs->trans('Success'), 'mesgs'); + } +} +// export csv +if ($action == 'export_csv') +{ + $sep = $conf->global->ACCOUNTING_SEPARATORCSV; + + header('Content-Type: text/csv'); + header('Content-Disposition: attachment;filename=journal_banque.csv'); + + $companystatic = new Client($db); + + if ($conf->global->ACCOUNTING_MODELCSV == 1) // Modèle Export Cegid Expert + { + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), '%d%m%Y'); + + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + + // Bank + print $date . $sep; + print $conf->global->ACCOUNTING_BANK_JOURNAL . $sep; + foreach ( $tabbq[$key] as $k => $mt ) { + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $val["type_payment"] . $sep; + print $sep; + } + print "\n"; + + // Third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_BANK_JOURNAL . $sep; + if ($val["lib"] == '(SupplierInvoicePayment)') { + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) . $sep; + } else { + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) . $sep; + } + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $val["type_payment"] . $sep; + print $sep; + print "\n"; + } + } + } + } else // Modèle Export Classique + { + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + + print '"' . $date . '"' . $sep; + print '"' . $val["type_payment"] . '"' . $sep; + + // Bank + foreach ( $tabbq[$key] as $k => $mt ) { + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . $langs->trans("Bank") . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + } + print "\n"; + + // Third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["type_payment"] . '"' . $sep; + + print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; + print '"' . $companystatic->name . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + print "\n"; + } + } + } + } +} +else +{ + + $form = new Form($db); + + llxHeader('', $langs->trans("BankJournal")); + + $namereport = $langs->trans("BankJournal"); + $namelink = ''; + $periodlink = ''; + $exportlink = ''; + $builddate = time(); + $description = $langs->trans("DescBankJournal") . '
'; + $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); + report_header($namereport, $namelink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => '')); + + print ''; + + print ''; + + print ' + '; + + /* + * Show result array + */ + print '

'; + + $i = 0; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print "\n"; + + $var = true; + $r = ''; + + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + if ($val["lib"] == '(SupplierInvoicePayment)') + $reflabel = $langs->trans('SupplierInvoicePayment'); + if ($val["lib"] == '(CustomerInvoicePayment)') + $reflabel = $langs->trans('CustomerInvoicePayment'); + + // Bank + foreach ( $tabbq[$key] as $k => $mt ) { + if (1) { + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + } + } + + // Third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($k != 'type') { + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + } + } + + $var = ! $var; + } + + print "
" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("Type") . "" . $langs->trans("PaymentMode") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $reflabel . "" . length_accountg($k) . "" . $langs->trans('Bank') . "" . $val["type_payment"] . "" . ($mt >= 0 ? price($mt) : '') . "" . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $val["soclib"] . "" . length_accounta($k) . "" . $langs->trans('ThirdParty') . " (" . $val['soclib'] . ")" . $val["type_payment"] . "" . ($mt < 0 ? price(- $mt) : '') . "" . ($mt >= 0 ? price($mt) : '') . "
"; + + // End of page + llxFooter(); +} + +$db->close(); diff --git a/htdocs/accountancy/journal/cashjournal.php b/htdocs/accountancy/journal/cashjournal.php new file mode 100644 index 00000000000..fb5a15a513c --- /dev/null +++ b/htdocs/accountancy/journal/cashjournal.php @@ -0,0 +1,531 @@ + + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013 Christophe Battarel + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Olivier Geffroy + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/journal/cashjournal.php + * \ingroup Accounting Expert + * \brief Page with cash journal + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; + +// Langs +$langs->load("companies"); +$langs->load("other"); +$langs->load("compta"); +$langs->load("bank"); +$langs->load("accountancy"); + +$date_startmonth = GETPOST('date_startmonth'); +$date_startday = GETPOST('date_startday'); +$date_startyear = GETPOST('date_startyear'); +$date_endmonth = GETPOST('date_endmonth'); +$date_endday = GETPOST('date_endday'); +$date_endyear = GETPOST('date_endyear'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +$action = GETPOST('action'); + +/* + * View + */ + +$year_current = strftime("%Y", dol_now()); +$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonthyear = $year_current; +if ($pastmonth == 0) { + $pastmonth = 12; + $pastmonthyear --; +} + +$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); +} + +$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$idpays = $p[0]; + +$sql = "SELECT b.rowid , b.dateo as do, b.datev as dv, b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, soc.code_compta, ba.courant,"; +$sql .= " soc.code_compta_fournisseur, soc.rowid as socid, soc.nom as name, ba.account_number, bu1.type as typeop"; +$sql .= " FROM " . MAIN_DB_PREFIX . "bank b"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "bank_account ba on b.fk_account=ba.rowid"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "bank_url bu1 ON bu1.fk_bank = b.rowid AND bu1.type='company'"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe soc on bu1.url_id=soc.rowid"; + +// Code opération type caisse +$sql .= " WHERE ba.courant = 2"; +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND ba.entity = " . $conf->entity; +} + +if ($date_start && $date_end) + $sql .= " AND b.dateo >= '" . $db->idate($date_start) . "' AND b.dateo <= '" . $db->idate($date_end) . "'"; +$sql .= " ORDER BY b.datev"; + +$object = new Account($db); +$paymentstatic = new Paiement($db); +$paymentsupplierstatic = new PaiementFourn($db); +$societestatic = new Societe($db); +$chargestatic = new ChargeSociales($db); +$paymentvatstatic = new TVA($db); + +dol_syslog("accountancy/journal/cashjournal.php:: sql=" . $sql, LOG_DEBUG); +$result = $db->query($sql); +if ($result) { + + $num = $db->num_rows($result); + // les variables + $cptfour = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef")); + $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); + $cpttva = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) ? $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE : $langs->trans("CodeNotDef")); + $cptsociale = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE) ? $conf->global->ACCOUNTING_ACCOUNT_SUSPENSE : $langs->trans("CodeNotDef")); + + $tabpay = array (); + $tabbq = array (); + $tabtp = array (); + $tabcompany = array (); + $tabtype = array (); + + $i = 0; + while ( $i < $num ) { + $obj = $db->fetch_object($result); + + // controls + $compta_bank = $obj->account_number; + if ($obj->label == '(SupplierInvoicePayment)') + $compta_soc = (! empty($obj->code_compta_fournisseur) ? $obj->code_compta_fournisseur : $cptfour); + if ($obj->label == '(CustomerInvoicePayment)') + $compta_soc = (! empty($obj->code_compta) ? $obj->code_compta : $cptcli); + if ($obj->typeop == '(BankTransfert)') + $compta_soc = $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH; + + // variable bookkeeping + + $tabpay[$obj->rowid]["date"] = $obj->do; + $tabpay[$obj->rowid]["ref"] = $obj->label; + $tabpay[$obj->rowid]["fk_bank"] = $obj->rowid; + if (preg_match('/^\((.*)\)$/i', $obj->label, $reg)) { + $tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]); + } else { + $tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60); + } + $links = $object->get_url($obj->rowid); + + foreach ( $links as $key => $val ) { + + $tabtype[$obj->rowid] = $links[$key]['type']; + + if ($links[$key]['type'] == 'payment') { + $paymentstatic->id = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentstatic->getNomUrl(2); + } else if ($links[$key]['type'] == 'payment_supplier') { + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentsupplierstatic->getNomUrl(2); + } else if ($links[$key]['type'] == 'company') { + + $societestatic->id = $links[$key]['url_id']; + $societestatic->name = $links[$key]['label']; + $tabpay[$obj->rowid]["soclib"] = $societestatic->getNomUrl(1, '', 30); + $tabtp[$obj->rowid][$compta_soc] += $obj->amount; + } else if ($links[$key]['type'] == 'sc') { + + $chargestatic->id = $links[$key]['url_id']; + $chargestatic->ref = $links[$key]['url_id']; + + $tabpay[$obj->rowid]["lib"] .= ' ' . $chargestatic->getNomUrl(2); + if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) { + if ($reg[1] == 'socialcontribution') + $reg[1] = 'SocialContribution'; + $chargestatic->lib = $langs->trans($reg[1]); + } else { + $chargestatic->lib = $links[$key]['label']; + } + $chargestatic->ref = $chargestatic->lib; + $tabpay[$obj->rowid]["soclib"] = $chargestatic->getNomUrl(1, 30); + + $sqlmid = 'SELECT cchgsoc.accountancy_code'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "c_chargesociales cchgsoc "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "chargesociales as chgsoc ON chgsoc.fk_type=cchgsoc.id"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementcharge as paycharg ON paycharg.fk_charge=chgsoc.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "bank_url as bkurl ON bkurl.url_id=paycharg.rowid"; + $sqlmid .= " WHERE bkurl.fk_bank=" . $obj->rowid; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $tabtp[$obj->rowid][$objmid->accountancy_code] += $obj->amount; + } + } else if ($links[$key]['type'] == 'payment_vat') { + + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $links[$key]['url_id']; + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvatstatic->getNomUrl(2); + $tabtp[$obj->rowid][$cpttva] += $obj->amount; + } else if ($links[$key]['type'] == 'banktransfert') { + $tabpay[$obj->rowid]["lib"] .= ' ' . $paymentvatstatic->getNomUrl(2); + $tabtp[$obj->rowid][$cpttva] += $obj->amount; + } + /*else { + $tabtp [$obj->rowid] [$cptsociale] += $obj->amount; + }*/ + } + $tabbq[$obj->rowid][$compta_bank] += $obj->amount; + + // if($obj->socid)$tabtp[$obj->rowid][$compta_soc] += $obj->amount; + + $i ++; + } +} else { + dol_print_error($db); +} + +/* + * Actions +*/ + +// write bookkeeping +if ($action == 'writeBookKeeping') { + $error = 0; + foreach ( $tabpay as $key => $val ) { + // cash + foreach ( $tabbq[$key] as $k => $mt ) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'cash'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = $compte->label; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt >= 0 ? $mt : 0); + $bookkeeping->credit = ($mt < 0 ? - $mt : 0); + $bookkeeping->code_journal = $conf->global->ACCOUNTING_CASH_JOURNAL; + + if ($tabtype[$key] == 'payment') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + } else if ($tabtype[$key] == 'payment_supplier') { + + $sqlmid = 'SELECT facf.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + } + + $result = $bookkeeping->create(); + if ($result < 0) { + $error ++; + setEventMessage($object->errors, 'errors'); + } + } + // third party + foreach ( $tabtp[$key] as $k => $mt ) { + + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->doc_type = 'cash'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_bank"]; + $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->montant = ($mt < 0 ? - $mt : $mt); + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0 ? - $mt : 0); + $bookkeeping->credit = ($mt >= 0 ? $mt : 0); + $bookkeeping->code_journal = $conf->global->ACCOUNTING_CASH_JOURNAL; + + if ($tabtype[$key] == 'sc') { + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + } else if ($tabtype[$key] == 'payment') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } else if ($tabtype[$key] == 'payment_supplier') { + + $sqlmid = 'SELECT facf.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture_fourn facf "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid"; + $sqlmid .= " WHERE payf.fk_bank=" . $key; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER; + } else if ($tabtype[$key] == 'company') { + + $sqlmid = 'SELECT fac.facnumber'; + $sqlmid .= " FROM " . MAIN_DB_PREFIX . "facture fac "; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement_facture as payfac ON payfac.fk_facture=fac.rowid"; + $sqlmid .= " INNER JOIN " . MAIN_DB_PREFIX . "paiement as pay ON payfac.fk_paiement=pay.rowid"; + $sqlmid .= " WHERE pay.fk_bank=" . $key; + dol_syslog("accountancy/journal/cashjournal.php:: sqlmid=" . $sqlmid, LOG_DEBUG); + $resultmid = $db->query($sqlmid); + if ($resultmid) { + $objmid = $db->fetch_object($resultmid); + $bookkeeping->doc_ref = $objmid->facnumber; + } + $bookkeeping->code_tiers = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } else { + + $bookkeeping->doc_ref = $k; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + } + + $result = $bookkeeping->create(); + if ($result < 0) { + $error ++; + setEventMessage($object->errors, 'errors'); + } + } + } + + if (empty($error)) { + setEventMessage($langs->trans('Success'), 'mesgs'); + } +} +// export csv +if ($action == 'export_csv') { + $sep = $conf->global->ACCOUNTING_SEPARATORCSV; + + header('Content-Type: text/csv'); + header('Content-Disposition:attachment;filename=journal_caisse.csv'); + + if ($conf->global->ACCOUNTING_MODELCSV == 1) // Modèle Export Cegid Expert + { + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), '%d%m%Y'); + + // Cash + print $date . $sep; + print $conf->global->ACCOUNTING_CASH_JOURNAL . $sep; + + foreach ( $tabbq[$key] as $k => $mt ) { + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print price($mt) . $sep; + } + print utf8_decode($langs->trans("CashPayment")) . $sep; + print $val["ref"] . $sep; + print "\n"; + + // Third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_CASH_JOURNAL . $sep; + if ($obj->label == '(SupplierInvoicePayment)') { + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) . $sep; + } else { + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) . $sep; + } + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print price($mt) . $sep; + print $langs->trans("ThirdParty") . $sep; + print $val["ref"] . $sep; + print "\n"; + } + } + } + } else // Modèle Export Classique + { + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), 'day'); + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + + // Cash + foreach ( $tabbq[$key] as $k => $mt ) { + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . $langs->trans("Cash") . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + } + print "\n"; + + // Third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; + print '"' . $langs->trans("ThirdParty") . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + print "\n"; + } + } + } + } +} else { + + $form = new Form($db); + + llxHeader('', $langs->trans("CashJournal"), ''); + + $name = $langs->trans("CashJournal"); + $nomlink = ''; + $periodlink = ''; + $exportlink = ''; + $builddate = time(); + $description = $langs->trans("DescCashJournal") . '
'; + $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); + report_header($name, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => '')); + + print ''; + + print ''; + + print ' + '; + + /* + * Show result array + */ + print '

'; + + $i = 0; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print "\n"; + + $var = true; + $r = ''; + + foreach ( $tabpay as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + // Cash + foreach ( $tabbq[$key] as $k => $mt ) { + if (1) { + print ""; + print ""; + print ""; + print ""; + print '"; + print '"; + print ""; + } + } + + // third party + foreach ( $tabtp[$key] as $k => $mt ) { + if ($k != 'type') { + print ""; + + print ""; + print ""; + + print ""; + print '"; + print '"; + } + } + + $var = ! $var; + } + + print "
" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $val["lib"] . "" . length_accountg($k) . "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $val["soclib"] . "" . length_accounta($k) . "' . ($mt < 0 ? price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; + + // End of page + llxFooter(); +} +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/journal/index.html b/htdocs/accountancy/journal/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/journal/index.php b/htdocs/accountancy/journal/index.php new file mode 100644 index 00000000000..36286ce265e --- /dev/null +++ b/htdocs/accountancy/journal/index.php @@ -0,0 +1,46 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/** + * \file htdocs/accountancy/journal/index.php + * \ingroup Accounting Expert + * \brief Index + */ + +require '../../main.inc.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +llxHeader('', 'Journaux', ''); + +$form = new Form($db); + +// End of page +$db->close(); +llxFooter(); \ No newline at end of file diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php new file mode 100644 index 00000000000..d2f204c6b8c --- /dev/null +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -0,0 +1,472 @@ + + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/journal/purchasesjournal.php + * \ingroup Accounting Expert + * \brief Page with purchases journal + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +$date_startmonth = GETPOST('date_startmonth'); +$date_startday = GETPOST('date_startday'); +$date_startyear = GETPOST('date_startyear'); +$date_endmonth = GETPOST('date_endmonth'); +$date_endday = GETPOST('date_endday'); +$date_endyear = GETPOST('date_endyear'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +$action = GETPOST('action'); + + + +/* + * Actions + */ + +$year_current = strftime("%Y", dol_now()); +$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonthyear = $year_current; +if ($pastmonth == 0) { + $pastmonth = 12; + $pastmonthyear --; +} + +$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); +} + +$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$idpays = $p[0]; + +$sql = "SELECT f.rowid, f.ref, f.type, f.datef as df, f.libelle,"; +$sql .= " fd.rowid as fdid, fd.description, fd.total_ttc, fd.tva_tx, fd.total_ht, fd.tva as total_tva, fd.product_type,"; +$sql .= " s.rowid as socid, s.nom as name, s.code_compta_fournisseur, s.fournisseur,"; +$sql .= " s.code_compta_fournisseur, p.accountancy_code_buy , ct.accountancy_code_buy as account_tva, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva as ct ON fd.tva_tx = ct.taux AND ct.fk_pays = '" . $idpays . "'"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON aa.rowid = fd.fk_code_ventilation"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = fd.fk_facture_fourn"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; +$sql .= " WHERE f.fk_statut > 0 "; +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = " . $conf->entity; +} +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql .= " AND f.type IN (0,1,2)"; +else + $sql .= " AND f.type IN (0,1,2,3)"; +if ($date_start && $date_end) + $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'"; +$sql .= " ORDER BY f.datef"; + +dol_syslog('accountancy/journal/purchasesjournal.php:: $sql=' . $sql); +$result = $db->query($sql); +if ($result) { + $num = $db->num_rows($result); + // les variables + $cptfour = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER)) ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef"); + $cpttva = (! empty($conf->global->ACCOUNTING_VAT_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_ACCOUNT : $langs->trans("CodeNotDef"); + + $tabfac = array (); + $tabht = array (); + $tabtva = array (); + $tabttc = array (); + $tabcompany = array (); + + $i = 0; + while ( $i < $num ) { + $obj = $db->fetch_object($result); + // contrôles + $compta_soc = (! empty($obj->code_compta_fournisseur)) ? $obj->code_compta_fournisseur : $cptfour; + $compta_prod = $obj->compte; + if (empty($compta_prod)) { + if ($obj->product_type == 0) + $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef"); + else + $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : $langs->trans("CodeNotDef"); + } + $compta_tva = (! empty($obj->account_tva) ? $obj->account_tva : $cpttva); + + $tabfac[$obj->rowid]["date"] = $obj->df; + $tabfac[$obj->rowid]["ref"] = $obj->ref; + $tabfac[$obj->rowid]["type"] = $obj->type; + $tabfac[$obj->rowid]["description"] = $obj->description; + $tabfac[$obj->rowid]["fk_facturefourndet"] = $obj->fdid; + $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc; + $tabht[$obj->rowid][$compta_prod] += $obj->total_ht; + $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva; + $tabcompany[$obj->rowid] = array ( + 'id' => $obj->socid, + 'name' => $obj->name, + 'code_fournisseur' => $obj->code_compta_fournisseur + ); + + $i ++; + } +} else { + dol_print_error($db); +} + +// Bookkeeping Write +if ($action == 'writebookkeeping') { + $now = dol_now(); + + foreach ( $tabfac as $key => $val ) { + foreach ( $tabttc[$key] as $k => $mt ) { + // get compte id and label + + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'supplier_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturefourndet"]; + $bookkeeping->code_tiers = $tabcompany[$key]['code_fournisseur']; + $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D'; + $bookkeeping->debit = ($mt <= 0) ? $mt : 0; + $bookkeeping->credit = ($mt > 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; + + $bookkeeping->create(); + } + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + // get compte id and label + $compte = new AccountingAccount($db); + if ($compte->fetch(null, $k)) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'supplier_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturefourndet"]; + $bookkeeping->code_tiers = ''; + $bookkeeping->label_compte = dol_trunc($val["description"], 128); + $bookkeeping->numero_compte = $k; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'C' : 'D'; + $bookkeeping->debit = ($mt > 0) ? $mt : 0; + $bookkeeping->credit = ($mt <= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; + + $bookkeeping->create(); + } + } + } + + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + // get compte id and label + + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'supplier_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturefourndet"]; + $bookkeeping->code_tiers = ''; + $bookkeeping->label_compte = $langs->trans("VAT"); + $bookkeeping->numero_compte = $k; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'C' : 'D'; + $bookkeeping->debit = ($mt > 0) ? $mt : 0; + $bookkeeping->credit = ($mt <= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_PURCHASE_JOURNAL; + + $bookkeeping->create(); + } + } + } +} + + +/* + * View + */ + +$companystatic = new Societe($db); + +// export csv +if ($action == 'export_csv') +{ + $sep = $conf->global->ACCOUNTING_SEPARATORCSV; + + header('Content-Type: text/csv'); + header('Content-Disposition: attachment;filename=journal_achats.csv'); + + if ($conf->global->ACCOUNTING_MODELCSV == 1) // Modèle Export Cegid Expert + { + foreach ( $tabfac as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), '%d%m%Y'); + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_PURCHASE_JOURNAL . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($val["description"], 32) . $sep; + print $val["ref"]; + print "\n"; + } + } + + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_PURCHASE_JOURNAL . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $langs->trans("VAT") . $sep; + print $val["ref"]; + print "\n"; + } + } + print $date . $sep; + print $conf->global->ACCOUNTING_PURCHASE_JOURNAL . $sep; + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER) . $sep; + + foreach ( $tabttc[$key] as $k => $mt ) { + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print utf8_decode($companystatic->name) . $sep; + print $val["ref"]; + } + print "\n"; + } + } else // Modèle Export Classique + { + foreach ( $tabfac as $key => $val ) { + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . dol_trunc($val["description"], 32) . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + print "\n"; + } + } + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . $langs->trans("VAT") . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + print "\n"; + } + } + + // Third party + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + foreach ( $tabttc[$key] as $k => $mt ) { + print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; + print '"' . utf8_decode($companystatic->name) . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + } + print "\n"; + } + } +} else { + + llxHeader('', '', ''); + + $form = new Form($db); + + $nom = $langs->trans("PurchasesJournal"); + $nomlink = ''; + $periodlink = ''; + $exportlink = ''; + $builddate = time(); + $description = $langs->trans("DescPurchasesJournal") . '
'; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $description .= $langs->trans("DepositsAreNotIncluded"); + else + $description .= $langs->trans("DepositsAreIncluded"); + $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); + report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => '')); + + print ''; + + print ''; + + print ' + '; + + /* + * Show result array + */ + print '

'; + + $i = 0; + print ""; + print ""; + // /print ""; + print ""; + print ""; + print ""; + print ""; + print "\n"; + + $var = true; + $r = ''; + + $invoicestatic = new FactureFournisseur($db); + $companystatic = new Fournisseur($db); + + foreach ( $tabfac as $key => $val ) { + $invoicestatic->id = $key; + $invoicestatic->ref = $val["ref"]; + $invoicestatic->type = $val["type"]; + $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32)); + + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + print ""; + print ""; + print ""; + print ""; + print ""; + print '"; + print '"; + print ""; + } + } + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print ""; + print ""; + print ""; + print ""; + print '"; + print '"; + print ""; + } + } + print ""; + + // Third party + print ""; + print ""; + + foreach ( $tabttc[$key] as $k => $mt ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + + print ""; + print '"; + print '"; + } + print ""; + + $var = ! $var; + } + + print "
".$langs->trans("JournalNum")."" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("Type") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . "" . $invoicestatic->description . "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . "" . $langs->trans("VAT") . "' . ($mt >= 0 ? price($mt) : '') . "' . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accounta($k); + print "" . $langs->trans("ThirdParty"); + print ' (' . $companystatic->getNomUrl(0, 'supplier', 16) . ')'; + print "' . ($mt < 0 ? - price(- $mt) : '') . "' . ($mt >= 0 ? price($mt) : '') . "
"; + + // End of page + llxFooter(); +} +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php new file mode 100644 index 00000000000..5bb1f989a92 --- /dev/null +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -0,0 +1,474 @@ + + * Copyright (C) 2007-2010 Jean Heimburger + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013 Christophe Battarel + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Olivier Geffroy + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/journal/sellsjournal.php + * \ingroup Accounting Expert + * \brief Page with sells journal + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +$date_startmonth = GETPOST('date_startmonth'); +$date_startday = GETPOST('date_startday'); +$date_startyear = GETPOST('date_startyear'); +$date_endmonth = GETPOST('date_endmonth'); +$date_endday = GETPOST('date_endday'); +$date_endyear = GETPOST('date_endyear'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +$action = GETPOST('action'); + +/* + * View + */ + +$year_current = strftime("%Y", dol_now()); +$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonthyear = $year_current; +if ($pastmonth == 0) { + $pastmonth = 12; + $pastmonthyear --; +} + +$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); +$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); + +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); + $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); +} + +$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$idpays = $p[0]; + +$sql = "SELECT f.rowid, f.facnumber, f.type, f.datef as df, f.ref_client,"; +$sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc,"; +$sql .= " s.rowid as socid, s.nom as name, s.code_compta, s.code_client,"; +$sql .= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte, "; +$sql .= " ct.accountancy_code_sell as account_tva"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facturedet as fd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = fd.fk_product"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON aa.rowid = fd.fk_code_ventilation"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "facture as f ON f.rowid = fd.fk_facture"; +$sql .= " JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_tva ct ON fd.tva_tx = ct.taux AND ct.fk_pays = '" . $idpays . "'"; +$sql .= " WHERE fd.fk_code_ventilation > 0 "; +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = " . $conf->entity; +} +$sql .= " AND f.fk_statut > 0"; +if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $sql .= " AND f.type IN (0,1,2)"; +else + $sql .= " AND f.type IN (0,1,2,3)"; +$sql .= " AND fd.product_type IN (0,1)"; +if ($date_start && $date_end) + $sql .= " AND f.datef >= '" . $db->idate($date_start) . "' AND f.datef <= '" . $db->idate($date_end) . "'"; +$sql .= " ORDER BY f.datef"; + +dol_syslog('accountancy/journal/sellsjournal.php:: $sql=' . $sql); +$result = $db->query($sql); +if ($result) { + $tabfac = array (); + $tabht = array (); + $tabtva = array (); + $tabttc = array (); + $tabcompany = array (); + + $num = $db->num_rows($result); + $i = 0; + + while ( $i < $num ) { + $obj = $db->fetch_object($result); + // les variables + $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)) ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef"); + $compta_soc = (! empty($obj->code_compta)) ? $obj->code_compta : $cptcli; + + $compta_prod = $obj->compte; + if (empty($compta_prod)) { + if ($obj->product_type == 0) + $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); + else + $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef"); + } + $cpttva = (! empty($conf->global->ACCOUNTING_VAT_ACCOUNT)) ? $conf->global->ACCOUNTING_VAT_ACCOUNT : $langs->trans("CodeNotDef"); + $compta_tva = (! empty($obj->account_tva) ? $obj->account_tva : $cpttva); + + // Invoice lines + $tabfac[$obj->rowid]["date"] = $obj->df; + $tabfac[$obj->rowid]["ref"] = $obj->facnumber; + $tabfac[$obj->rowid]["type"] = $obj->type; + $tabfac[$obj->rowid]["description"] = $obj->description; + $tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid; + if (! isset($tabttc[$obj->rowid][$compta_soc])) + $tabttc[$obj->rowid][$compta_soc] = 0; + if (! isset($tabht[$obj->rowid][$compta_prod])) + $tabht[$obj->rowid][$compta_prod] = 0; + if (! isset($tabtva[$obj->rowid][$compta_tva])) + $tabtva[$obj->rowid][$compta_tva] = 0; + $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc; + $tabht[$obj->rowid][$compta_prod] += $obj->total_ht; + $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva; + $tabcompany[$obj->rowid] = array ( + 'id' => $obj->socid, + 'name' => $obj->name, + 'code_client' => $obj->code_compta + ); + + $i ++; + } +} else { + dol_print_error($db); +} + +/* + * Action + */ + +// Bookkeeping Write +if ($action == 'writebookkeeping') { + $now = dol_now(); + + foreach ( $tabfac as $key => $val ) { + foreach ( $tabttc[$key] as $k => $mt ) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->code_tiers = $tabcompany[$key]['code_client']; + $bookkeeping->numero_compte = $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER; + $bookkeeping->label_compte = $tabcompany[$key]['name']; + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt >= 0) ? $mt : 0; + $bookkeeping->credit = ($mt < 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + + $bookkeeping->create(); + } + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + // get compte id and label + $compte = new AccountingAccount($db); + if ($compte->fetch(null, $k)) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = dol_trunc($val["description"], 128); + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0) ? $mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + + $bookkeeping->create(); + } + } + } + + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + $bookkeeping = new BookKeeping($db); + $bookkeeping->doc_date = $val["date"]; + $bookkeeping->doc_ref = $val["ref"]; + $bookkeeping->date_create = $now; + $bookkeeping->doc_type = 'customer_invoice'; + $bookkeeping->fk_doc = $key; + $bookkeeping->fk_docdet = $val["fk_facturedet"]; + $bookkeeping->fk_compte = $compte->id; + $bookkeeping->code_tiers = ''; + $bookkeeping->numero_compte = $k; + $bookkeeping->label_compte = $langs->trans("VAT"); + $bookkeeping->montant = $mt; + $bookkeeping->sens = ($mt < 0) ? 'D' : 'C'; + $bookkeeping->debit = ($mt < 0) ? $mt : 0; + $bookkeeping->credit = ($mt >= 0) ? $mt : 0; + $bookkeeping->code_journal = $conf->global->ACCOUNTING_SELL_JOURNAL; + + $bookkeeping->create(); + } + } + } +} +// export csv +if ($action == 'export_csv') { + $sep = $conf->global->ACCOUNTING_SEPARATORCSV; + + header('Content-Type: text/csv'); + header('Content-Disposition: attachment;filename=journal_ventes.csv'); + + $companystatic = new Client($db); + + if ($conf->global->ACCOUNTING_MODELCSV == 1) // Modèle Export Cegid Expert + { + foreach ( $tabfac as $key => $val ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + + $date = dol_print_date($db->jdate($val["date"]), '%d%m%Y'); + + print $date . $sep; + print $conf->global->ACCOUNTING_SELL_JOURNAL . $sep; + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER) . $sep; + foreach ( $tabttc[$key] as $k => $mt ) { + print length_accounta(html_entity_decode($k)) . $sep; + print ($mt < 0 ? 'C' : 'D') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print utf8_decode($companystatic->name) . $sep; + } + print $val["ref"]; + print "\n"; + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_SELL_JOURNAL . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print dol_trunc($val["description"], 32) . $sep; + print $val["ref"]; + print "\n"; + } + } + // TVA + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print $date . $sep; + print $conf->global->ACCOUNTING_SELL_JOURNAL . $sep; + print length_accountg(html_entity_decode($k)) . $sep; + print $sep; + print ($mt < 0 ? 'D' : 'C') . $sep; + print ($mt <= 0 ? price(- $mt) : $mt) . $sep; + print $langs->trans("VAT") . $sep; + print $val["ref"]; + print "\n"; + } + } + } + } else // Modèle Export Classique + { + foreach ( $tabfac as $key => $val ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + + $date = dol_print_date($db->jdate($val["date"]), 'day'); + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + foreach ( $tabttc[$key] as $k => $mt ) { + print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep; + print '"' . utf8_decode($companystatic->name) . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"'; + } + print "\n"; + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . dol_trunc($val["description"], 32) . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + print "\n"; + } + } + + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print '"' . $date . '"' . $sep; + print '"' . $val["ref"] . '"' . $sep; + print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep; + print '"' . $langs->trans("VAT") . '"' . $sep; + print '"' . ($mt < 0 ? price(- $mt) : '') . '"' . $sep; + print '"' . ($mt >= 0 ? price($mt) : '') . '"'; + print "\n"; + } + } + } + } +} else { + + $form = new Form($db); + + llxHeader('', $langs->trans("SellsJournal")); + + $nom = $langs->trans("SellsJournal"); + $nomlink = ''; + $periodlink = ''; + $exportlink = ''; + $builddate = time(); + $description = $langs->trans("DescSellsJournal") . '
'; + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) + $description .= $langs->trans("DepositsAreNotIncluded"); + else + $description .= $langs->trans("DepositsAreIncluded"); + $period = $form->select_date($date_start, 'date_start', 0, 0, 0, '', 1, 0, 1) . ' - ' . $form->select_date($date_end, 'date_end', 0, 0, 0, '', 1, 0, 1); + report_header($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => '')); + + print ''; + + print ''; + + print ' + '; + + /* + * Show result array + */ + print '

'; + + $i = 0; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print "\n"; + + $var = true; + $r = ''; + + $invoicestatic = new Facture($db); + $companystatic = new Client($db); + + foreach ( $tabfac as $key => $val ) { + $invoicestatic->id = $key; + $invoicestatic->ref = $val["ref"]; + $invoicestatic->type = $val["type"]; + $invoicestatic->description = html_entity_decode(dol_trunc($val["description"], 32)); + + $date = dol_print_date($db->jdate($val["date"]), 'day'); + + print ""; + + // Third party + print ""; + print ""; + foreach ( $tabttc[$key] as $k => $mt ) { + $companystatic->id = $tabcompany[$key]['id']; + $companystatic->name = $tabcompany[$key]['name']; + $companystatic->client = $tabcompany[$key]['code_client']; + print ""; + print ""; + } + print ""; + + // Product / Service + foreach ( $tabht[$key] as $k => $mt ) { + if ($mt) { + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + } + } + + // VAT + // var_dump($tabtva); + foreach ( $tabtva[$key] as $k => $mt ) { + if ($mt) { + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + print ""; + } + } + + $var = ! $var; + } + + print "
" . $langs->trans("Date") . "" . $langs->trans("Piece") . ' (' . $langs->trans("InvoiceRef") . ")" . $langs->trans("Account") . "" . $langs->trans("Type") . "" . $langs->trans("Debit") . "" . $langs->trans("Credit") . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accounta($k); + print "" . $langs->trans("ThirdParty"); + print ' (' . $companystatic->getNomUrl(0, 'customer', 16) . ')'; + print "" . ($mt >= 0 ? price($mt) : '') . "" . ($mt < 0 ? price(- $mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . "" . $invoicestatic->description . "" . ($mt < 0 ? price(- $mt) : '') . "" . ($mt >= 0 ? price($mt) : '') . "
" . $date . "" . $invoicestatic->getNomUrl(1) . "" . length_accountg($k) . "" . $langs->trans("VAT") . "" . ($mt < 0 ? price(- $mt) : '') . "" . ($mt >= 0 ? price($mt) : '') . "
"; + + // End of page + llxFooter(); +} +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/supplier/card.php b/htdocs/accountancy/supplier/card.php new file mode 100644 index 00000000000..45c8de9b165 --- /dev/null +++ b/htdocs/accountancy/supplier/card.php @@ -0,0 +1,140 @@ + + * Copyright (C) 2005 Simon TOSSER + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent s + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +/** + * \file htdocs/accountancy/supplier/card.php + * \ingroup Accounting Expert + * \brief Card supplier ventilation + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +$action = GETPOST('action'); +$id = GETPOST('id', 'int'); +$codeventil = GETPOST('codeventil'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); + +if ($action == 'ventil' && $user->rights->accounting->ventilation->dispatch) +{ + $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det"; + $sql .= " SET fk_code_ventilation = " . $codeventil; + $sql .= " WHERE rowid = " . $id; + + dol_syslog('accountancy/journal/sellsjournal.php:: $sql=' . $sql); + + $resql = $db->query($sql); + if (! $resql) { + setEventMessage($db->lasterror(), 'errors'); + } +} + +/* + * View + */ +llxHeader("", "", "FicheVentilation"); + +if ($cancel == $langs->trans("Cancel")) { + $action = ''; +} + +/* + * Create + */ +$form = new Form($db); +$facturefournisseur_static = new FactureFournisseur($db); +$formventilation = new FormVentilation($db); + +if ($_GET["id"]) { + $sql = "SELECT f.ref as facnumber, f.rowid as facid, l.fk_product, l.description, l.rowid, l.fk_code_ventilation, "; + $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label"; + $sql .= ", aa.account_number, aa.label"; + $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as l"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; + $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON l.fk_code_ventilation = aa.rowid"; + $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = l.fk_facture_fourn "; + $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . $id; + if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; + } + + $result = $db->query($sql); + if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + if ($num_lines) { + $objp = $db->fetch_object($result); + + print '
' . "\n"; + print ''; + print ''; + + print_fiche_titre($langs->trans("SuppliersVentilation")); + + print ''; + + // ref invoice + print ''; + $facturefournisseur_static->ref = $objp->facnumber; + $facturefournisseur_static->id = $objp->facid; + print ''; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print '
' . $langs->trans("BillsSuppliers") . '' . $facturefournisseur_static->getNomUrl(1) . '
Ligne' . stripslashes(nl2br($objp->description)) . '
' . $langs->trans("ProductLabel") . '' . dol_trunc($objp->product_label, 24) . '
' . $langs->trans("Account") . ''; + print $objp->account_number . '-' . $objp->label; + print '
' . $langs->trans("NewAccount") . ''; + print $formventilation->select_account($objp->fk_code_ventilation, 'codeventil', 1); + print '
 
'; + print '
'; + } else { + print "Error 1"; + } + } else { + print "Error 2"; + } +} else { + print "Error ID incorrect"; +} + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/supplier/index.html b/htdocs/accountancy/supplier/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php new file mode 100644 index 00000000000..edebcfd9d46 --- /dev/null +++ b/htdocs/accountancy/supplier/index.php @@ -0,0 +1,262 @@ + + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/supplier/index.php + * \ingroup Accounting Expert + * \brief Page accueil ventilation + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->read) + accessforbidden(); + +// Filter +$year = $_GET["year"]; +if ($year == 0) { + $year_current = strftime("%Y", time()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} + +// Validate History +$action = GETPOST('action'); +if ($action == 'validatehistory') { + + $error = 0; + $db->begin(); + + if ($db->type == 'pgsql') { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd"; + $sql1 .= " SET fd.fk_code_ventilation = accnt.rowid"; + $sql1 .= " FROM " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accountingaccount as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " WHERE fd.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_buy=accnt.account_number"; + $sql1 .= " AND fd.fk_code_ventilation = 0"; + } else { + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as fd, " . MAIN_DB_PREFIX . "product as p, " . MAIN_DB_PREFIX . "accountingaccount as accnt , " . MAIN_DB_PREFIX . "accounting_system as syst"; + $sql1 .= " SET fd.fk_code_ventilation = accnt.rowid"; + $sql1 .= " WHERE fd.fk_product = p.rowid AND accnt.fk_pcg_version = syst.pcg_version AND syst.rowid=" . $conf->global->CHARTOFACCOUNTS; + $sql1 .= " AND accnt.active = 1 AND p.accountancy_code_buy=accnt.account_number"; + $sql1 .= " AND fd.fk_code_ventilation = 0"; + } + + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } else { + $db->commit(); + setEventMessage($langs->trans('Dispatched'), 'mesgs'); + } +} + +/* + * View + */ + +llxHeader('', $langs->trans("SuppliersVentilation")); + +$textprevyear = '' . img_previous() . ''; +$textnextyear = ' ' . img_next() . ''; + +print_fiche_titre($langs->trans("SuppliersVentilation") . " " . $textprevyear . " " . $langs->trans("Year") . " " . $year_start . " " . $textnextyear); + +print '' . $langs->trans("DescVentilSupplier") . ''; +print ''; + +$y = $year_current; + +$var = true; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$sql = "SELECT IF(aa.account_number IS NULL, 'Non pointe', aa.account_number) AS 'code comptable',"; +$sql .= " IF(aa.label IS NULL, 'Non pointe', aa.label) AS 'Intitulé',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=1,ffd.total_ht,0)),2) AS 'Janvier',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=2,ffd.total_ht,0)),2) AS 'Fevrier',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=3,ffd.total_ht,0)),2) AS 'Mars',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=4,ffd.total_ht,0)),2) AS 'Avril',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=5,ffd.total_ht,0)),2) AS 'Mai',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=6,ffd.total_ht,0)),2) AS 'Juin',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=7,ffd.total_ht,0)),2) AS 'Juillet',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=8,ffd.total_ht,0)),2) AS 'Aout',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=9,ffd.total_ht,0)),2) AS 'Septembre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=10,ffd.total_ht,0)),2) AS 'Octobre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=11,ffd.total_ht,0)),2) AS 'Novembre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=12,ffd.total_ht,0)),2) AS 'Decembre',"; +$sql .= " ROUND(SUM(ffd.total_ht),2) as 'Total'"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as ffd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accountingaccount as aa ON aa.rowid = ffd.fk_code_ventilation"; +$sql .= " WHERE ff.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND ff.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " AND ff.fk_statut > 0 "; + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND ff.entity = '" . $conf->entity . "'"; +} + +$sql .= " GROUP BY ffd.fk_code_ventilation"; + +dol_syslog('/accountancy/supplier/index.php:: sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + $i ++; + } + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Account") . '' . $langs->trans("Label") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . '' . $langs->trans("Total") . '
' . length_accountg($row[0]) . '' . $row[1] . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '' . price($row[14]) . '
\n"; + +print "
\n"; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$sql = "SELECT '" . $langs->trans("CAHTF") . "' AS 'Total',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=1,ffd.total_ht,0)),2) AS 'Janvier',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=2,ffd.total_ht,0)),2) AS 'Fevrier',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=3,ffd.total_ht,0)),2) AS 'Mars',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=4,ffd.total_ht,0)),2) AS 'Avril',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=5,ffd.total_ht,0)),2) AS 'Mai',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=6,ffd.total_ht,0)),2) AS 'Juin',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=7,ffd.total_ht,0)),2) AS 'Juillet',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=8,ffd.total_ht,0)),2) AS 'Aout',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=9,ffd.total_ht,0)),2) AS 'Septembre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=10,ffd.total_ht,0)),2) AS 'Octobre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=11,ffd.total_ht,0)),2) AS 'Novembre',"; +$sql .= " ROUND(SUM(IF(MONTH(ff.datef)=12,ffd.total_ht,0)),2) AS 'Decembre',"; +$sql .= " ROUND(SUM(ffd.total_ht),2) as 'Total'"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as ffd"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn"; +$sql .= " WHERE ff.datef >= '" . $db->idate(dol_get_first_day($y, 1, false)) . "'"; +$sql .= " AND ff.datef <= '" . $db->idate(dol_get_last_day($y, 12, false)) . "'"; +$sql .= " AND ff.fk_statut > 0 "; + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND ff.entity = '" . $conf->entity . "'"; +} + +dol_syslog('/accountancy/supplier/index.php:: sql=' . $sql); +$resql = $db->query($sql); +if ($resql) { + $i = 0; + $num = $db->num_rows($resql); + + while ( $i < $num ) { + $row = $db->fetch_row($resql); + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + $i ++; + } + + $db->free($resql); +} else { + print $db->lasterror(); // Show last sql error +} +print "
' . $langs->trans("Total") . '' . $langs->trans("JanuaryMin") . '' . $langs->trans("FebruaryMin") . '' . $langs->trans("MarchMin") . '' . $langs->trans("AprilMin") . '' . $langs->trans("MayMin") . '' . $langs->trans("JuneMin") . '' . $langs->trans("JulyMin") . '' . $langs->trans("AugustMin") . '' . $langs->trans("SeptemberMin") . '' . $langs->trans("OctoberMin") . '' . $langs->trans("NovemberMin") . '' . $langs->trans("DecemberMin") . '' . $langs->trans("Total") . '
' . $row[0] . '' . $row[1] . '' . price($row[2]) . '' . price($row[3]) . '' . price($row[4]) . '' . price($row[5]) . '' . price($row[6]) . '' . price($row[7]) . '' . price($row[8]) . '' . price($row[9]) . '' . price($row[10]) . '' . price($row[11]) . '' . price($row[12]) . '' . price($row[13]) . '
\n"; + +llxFooter(); +$db->close(); \ No newline at end of file diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php new file mode 100644 index 00000000000..8b2a870220d --- /dev/null +++ b/htdocs/accountancy/supplier/lines.php @@ -0,0 +1,224 @@ + + * Copyright (C) 2005 Simon TOSSER + * Copyright (C) 2013-2014 Olivier Geffroy + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Ari Elbaz (elarifr) + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/supplier/lines.php + * \ingroup Accounting Expert + * \brief Page of detail of the lines of ventilation of invoices suppliers + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->dispatch) + accessforbidden(); + +$formventilation = new FormVentilation($db); + +$changeaccount = GETPOST('changeaccount'); + +$is_search = GETPOST('button_search_x'); + +if (is_array($changeaccount) && count($changeaccount) > 0 && empty($is_search)) { + $error = 0; + + $db->begin(); + + $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det as l"; + $sql1 .= " SET l.fk_code_ventilation=" . GETPOST('account_parent'); + $sql1 .= ' WHERE l.rowid IN (' . implode(',', $changeaccount) . ')'; + + dol_syslog('accountancy/supplier/lines.php::changeaccount sql= ' . $sql1); + $resql1 = $db->query($sql1); + if (! $resql1) { + $error ++; + setEventMessage($db->lasterror(), 'errors'); + } + if (! $error) { + $db->commit(); + setEventMessage($langs->trans('Save'), 'mesgs'); + } else { + $db->rollback(); + setEventMessage($db->lasterror(), 'errors'); + } +} + +/* + * View + */ + +llxHeader('', $langs->trans("SuppliersVentilation") . ' - ' . $langs->trans("Dispatched")); + +$page = $_GET["page"]; +if ($page < 0) + $page = 0; + +if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { + $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; +} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { + $limit = $conf->liste_limit; +} else { + $limit = $conf->liste_limit; +} + +$offset = $limit * $page; + +$sql = "SELECT f.ref as facnumber, f.rowid as facid, l.fk_product, l.description, l.total_ht , l.qty, l.rowid, l.tva_tx, aa.label, aa.account_number, "; +$sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f"; +$sql .= " , " . MAIN_DB_PREFIX . "accountingaccount as aa"; +$sql .= " , " . MAIN_DB_PREFIX . "facture_fourn_det as l"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product"; +$sql .= " WHERE f.rowid = l.fk_facture_fourn and f.fk_statut >= 1 AND l.fk_code_ventilation <> 0 "; +$sql .= " AND aa.rowid = l.fk_code_ventilation"; +if (strlen(trim($_GET["search_facture"]))) { + $sql .= " AND f.facnumber like '%" . $_GET["search_facture"] . "%'"; +} +if (strlen(trim($_GET["search_ref"]))) { + $sql .= " AND p.ref like '%" . $_GET["search_ref"] . "%'"; +} +if (strlen(trim($_GET["search_label"]))) { + $sql .= " AND p.label like '%" . $_GET["search_label"] . "%'"; +} +if (strlen(trim($_GET["search_desc"]))) { + $sql .= " AND l.description like '%" . $_GET["search_desc"] . "%'"; +} +if (strlen(trim($_GET["search_account"]))) { + $sql .= " AND aa.account_number like '%" . $_GET["search_account"] . "%'"; +} +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$sql .= " ORDER BY l.rowid"; +if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_DONE > 0) { + $sql .= " DESC "; +} +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/supplier/lines.php::list sql= ' . $sql1); +$result = $db->query($sql); + +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + // TODO : print_barre_liste always use $conf->liste_limit and do not care about custom limit in list... + print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + + print '' . $langs->trans("DescVentilDoneSupplier") . ''; + + print '
'; + print ''; + + print '

'. $langs->trans("ChangeAccount"); + print $formventilation->select_account(GETPOST('account_parent'), 'account_parent', 1); + print '
'; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $facturefournisseur_static = new FactureFournisseur($db); + $product_static = new Product($db); + + $var = True; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + $codeCompta = $objp->account_number . ' ' . $objp->label; + + print ""; + + // Ref Invoice + $facturefournisseur_static->ref = $objp->facnumber; + $facturefournisseur_static->id = $objp->facid; + print ''; + + // Ref Product + $product_static->ref = $objp->product_ref; + $product_static->id = $objp->product_id; + $product_static->type = $objp->type; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + + print ""; + $i ++; + } +} else { + print $db->error(); +} + +print "
' . $langs->trans("Invoice") . '' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("Description") . '' . $langs->trans("Amount") . '' . $langs->trans("Account") . '  
  '; + print ''; + print ' 
' . $facturefournisseur_static->getNomUrl(1) . ''; + if ($product_static->id) + print $product_static->getNomUrl(1); + else + print ' '; + print '' . dol_trunc($objp->product_label, 24) . '' . nl2br(dol_trunc($objp->description, 32)) . '' . price($objp->total_ht) . '' . $codeCompta . '' . $objp->rowid . ''; + print img_edit(); + print '
"; + +$db->close(); +llxFooter(); \ No newline at end of file diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php new file mode 100644 index 00000000000..f932fbfc8af --- /dev/null +++ b/htdocs/accountancy/supplier/list.php @@ -0,0 +1,219 @@ + + * Copyright (C) 2013-2014 Alexandre Spangaro + * Copyright (C) 2014 Ari Elbaz (elarifr) + * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Juanjo Menent s + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/accountancy/supplier/list.php + * \ingroup Accounting Expert + * \brief Page de ventilation des lignes de facture + */ + +require '../../main.inc.php'; + +// Class +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/html.formventilation.class.php'; + +// Langs +$langs->load("compta"); +$langs->load("bills"); +$langs->load("other"); +$langs->load("main"); +$langs->load("accountancy"); + +$action = GETPOST('action'); +$codeventil = GETPOST('codeventil', 'array'); +$mesCasesCochees = GETPOST('mesCasesCochees', 'array'); + +// Security check +if ($user->societe_id > 0) + accessforbidden(); +if (! $user->rights->accounting->ventilation->dispatch) + accessforbidden(); + +$formventilation = new FormVentilation($db); + +llxHeader('', $langs->trans("Ventilation")); + +/* + * Action + */ + +if ($action == 'ventil') { + print '
' . $langs->trans("Processing") . '...
'; + if ($_POST['codeventil'] && $_POST["mesCasesCochees"]) { + print '
' . count($_POST["mesCasesCochees"]) . ' ' . $langs->trans("SelectedLines") . '
'; + $mesCodesVentilChoisis = $codeventil; + $cpt = 0; + + foreach ( $mesCasesCochees as $maLigneCochee ) { + // print '
id selectionnee : '.$monChoix."
"; + $maLigneCourante = explode("_", $maLigneCochee); + $monId = $maLigneCourante[0]; + $monNumLigne = $maLigneCourante[1]; + $monCompte = $mesCodesVentilChoisis[$monNumLigne]; + + $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det"; + $sql .= " SET fk_code_ventilation = " . $monCompte; + $sql .= " WHERE rowid = " . $monId; + + dol_syslog('accountancy/supplier/list.php:: sql=' . $sql); + if ($db->query($sql)) { + print '
' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' ' . $langs->trans("VentilatedinAccount") . ' : ' . $monCompte . '
'; + } else { + print '
' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' ' . $langs->trans("NotVentilatedinAccount") . ' : ' . $monCompte . '
' . $sql . '
'; + } + + $cpt ++; + } + } else { + print '
' . $langs->trans("AnyLineVentilate") . '
'; + } + print '
' . $langs->trans("EndProcessing") . '
'; +} + +/* + * Supplier Invoice Lines + * + */ +$page = GETPOST('page'); +if ($page < 0) + $page = 0; + +if (! empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION)) { + $limit = $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION; +} else if ($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION <= 0) { + $limit = $conf->liste_limit; +} else { + $limit = $conf->liste_limit; +} + +$offset = $limit * $page; + +$sql = "SELECT f.ref, f.rowid as facid, f.ref_supplier, l.fk_product, l.description, l.total_ht as price, l.rowid, l.fk_code_ventilation, "; +$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"; +$sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f"; +$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 . "accountingaccount as aa ON p.accountancy_code_buy = aa.account_number"; +$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_system as accsys ON accsys.pcg_version = aa.fk_pcg_version"; +$sql .= " WHERE f.fk_statut > 0 AND fk_code_ventilation = 0"; +$sql .= " AND (accsys.rowid='".$conf->global->CHARTOFACCOUNTS."' OR p.accountancy_code_sell IS NULL)"; + +if (! empty($conf->multicompany->enabled)) { + $sql .= " AND f.entity = '" . $conf->entity . "'"; +} + +$sql .= " ORDER BY l.rowid"; +if ($conf->global->ACCOUNTING_LIST_SORT_VENTILATION_TODO > 0) { + $sql .= " DESC "; +} +$sql .= $db->plimit($limit + 1, $offset); + +dol_syslog('accountancy/supplier/list.php:: $sql=' . $sql); +$result = $db->query($sql); +if ($result) { + $num_lines = $db->num_rows($result); + $i = 0; + + // TODO : print_barre_liste always use $conf->liste_limit and do not care about custom limit in list... + print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER["PHP_SELF"], "", $sortfield, $sortorder, '', $num_lines); + + print '
' . $langs->trans("DescVentilTodoSupplier") . '
'; + + print '
' . "\n"; + print ''; + + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $facturefourn_static = new FactureFournisseur($db); + $productfourn_static = new ProductFournisseur($db); + $form = new Form($db); + + $var = True; + while ( $i < min($num_lines, $limit) ) { + $objp = $db->fetch_object($result); + $var = ! $var; + print ""; + + // Ref facture + $facturefourn_static->ref = $objp->ref; + $facturefourn_static->id = $objp->facid; + print ''; + + // Ref facture supplier + $productfourn_static->ref = $objp->product_ref; + $productfourn_static->id = $objp->product_id; + $productfourn_static->type = $objp->type; + print ''; + + // print ''; + + // print ''; + + print ''; + + print ''; + + print ''; + + print ''; + + // Colonne choix du compte + print ''; + // Colonne choix ligne a ventiler + print ''; + + print ""; + $i ++; + } + + print '
Facture' . $langs->trans("Ref") . '' . $langs->trans("Label") . '' . $langs->trans("Description") . '' . $langs->trans("Amount") . '' . $langs->trans("Compte") . '' . $langs->trans("IntoAccount") . '' . $langs->trans("Ventilate") . '
' . $facturefourn_static->getNomUrl(1) . ''; + if ($productfourn_static->id) + print $productfourn_static->getNomUrl(1); + else + print ' '; + print ''.$objp->ref.''.$objp->ref_supplier.'' . dol_trunc($objp->product_label, 24) . '' . stripslashes(nl2br($objp->description)) . ''; + print price($objp->price); + print ''; + print $objp->code_buy; + print ''; + print $formventilation->select_account($objp->aarowid, 'codeventil[]', 1); + print ''; + print 'aarowid ? "checked" : "") . '/>'; + print '
'; + print '
'; + print '
'; +} else { + print $db->error(); +} + +llxFooter(); +$db->close(); diff --git a/htdocs/adherents/admin/adherent.php b/htdocs/adherents/admin/adherent.php index 0a251536ff6..f86e19050e4 100644 --- a/htdocs/adherents/admin/adherent.php +++ b/htdocs/adherents/admin/adherent.php @@ -53,7 +53,7 @@ if ($action == 'update' || $action == 'add') $constname=GETPOST('constname','alpha'); $constvalue=(GETPOST('constvalue_'.$constname) ? GETPOST('constvalue_'.$constname) : GETPOST('constvalue')); - if (($constname=='ADHERENT_CARD_TYPE' || $constname=='ADHERENT_ETIQUETTE_TYPE') && $constvalue == -1) $constvalue=''; + if (($constname=='ADHERENT_CARD_TYPE' || $constname=='ADHERENT_ETIQUETTE_TYPE' || $constname=='ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && $constvalue == -1) $constvalue=''; if ($constname=='ADHERENT_LOGIN_NOT_REQUIRED') // Invert choice { if ($constvalue) $constvalue=0; @@ -68,11 +68,11 @@ if ($action == 'update' || $action == 'add') if (! $error) { - $mesg = '
'.$langs->trans("SetupSaved").'
'; + setEventMessage($langs->trans("SetupSaved")); } else { - $mesg = '
'.$langs->trans("Error").'
'; + setEventMessage($langs->trans("Error"), 'errors'); } } @@ -117,10 +117,6 @@ $head = member_admin_prepare_head(); dol_fiche_head($head, 'general', $langs->trans("Members"), 0, 'user'); - -dol_htmloutput_mesg($mesg); - - print_fiche_titre($langs->trans("MemberMainOptions"),'',''); print ''; print ''; @@ -213,6 +209,23 @@ if ($conf->facture->enabled) } print "\n"; print ''; + + if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) + { + $var=!$var; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + print "\n"; + print ''; } print '
'.$langs->trans("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS").''; + print $form->select_produits($conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS, 'constvalue_ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS'); + print ''; + print ''; + print '
'; diff --git a/htdocs/adherents/admin/adherent_extrafields.php b/htdocs/adherents/admin/adherent_extrafields.php index 059e42d50f5..1c98c2c16ba 100644 --- a/htdocs/adherents/admin/adherent_extrafields.php +++ b/htdocs/adherents/admin/adherent_extrafields.php @@ -35,7 +35,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); diff --git a/htdocs/adherents/admin/adherent_type_extrafields.php b/htdocs/adherents/admin/adherent_type_extrafields.php index aa5e8cfa8d9..627d96acf17 100644 --- a/htdocs/adherents/admin/adherent_type_extrafields.php +++ b/htdocs/adherents/admin/adherent_type_extrafields.php @@ -37,7 +37,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); diff --git a/htdocs/adherents/admin/public.php b/htdocs/adherents/admin/public.php index 8a520a55c4e..740a5c97879 100644 --- a/htdocs/adherents/admin/public.php +++ b/htdocs/adherents/admin/public.php @@ -60,11 +60,11 @@ if ($action == 'update') if (! $error) { - $mesg = "".$langs->trans("SetupSaved").""; + setEventMessage($langs->trans("SetupSaved")); } else { - $mesg = "".$langs->trans("Error").""; + setEventMessage($langs->trans("Error"), 'errors'); } } @@ -86,8 +86,6 @@ $head = member_admin_prepare_head(); dol_fiche_head($head, 'public', $langs->trans("Members"), 0, 'user'); -dol_htmloutput_mesg($mesg); - if ($conf->use_javascript_ajax) { print "\n".''; +} + + // Cryptage mot de passe print '
'; $var=true; diff --git a/htdocs/admin/security_other.php b/htdocs/admin/security_other.php index 54bc933374c..c7ad04c322c 100644 --- a/htdocs/admin/security_other.php +++ b/htdocs/admin/security_other.php @@ -80,32 +80,19 @@ else if (preg_match('/del_(.*)/',$action,$reg)) } } -else if ($action == 'MAIN_SESSION_TIMEOUT') +else if ($action == 'updateform') { - if (! dolibarr_set_const($db, "MAIN_SESSION_TIMEOUT", $_POST["MAIN_SESSION_TIMEOUT"],'chaine',0,'',$conf->entity)) dol_print_error($db); - else setEventMessage($langs->trans("RecordModifiedSuccessfully")); -} -else if ($action == 'MAIN_UPLOAD_DOC') -{ - if (! dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',$_POST["MAIN_UPLOAD_DOC"],'chaine',0,'',$conf->entity)) dol_print_error($db); - else setEventMessage($langs->trans("RecordModifiedSuccessfully")); -} -else if ($action == 'MAIN_UMASK') -{ - if (! dolibarr_set_const($db, "MAIN_UMASK", $_POST["MAIN_UMASK"],'chaine',0,'',$conf->entity)) dol_print_error($db); - else setEventMessage($langs->trans("RecordModifiedSuccessfully")); -} -else if ($action == 'MAIN_ANTIVIRUS_COMMAND') -{ - if (! dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", $_POST["MAIN_ANTIVIRUS_COMMAND"],'chaine',0,'',$conf->entity)) dol_print_error($db); - else setEventMessage($langs->trans("RecordModifiedSuccessfully")); -} -else if ($action == 'MAIN_ANTIVIRUS_PARAM') -{ - if (! dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", $_POST["MAIN_ANTIVIRUS_PARAM"],'chaine',0,'',$conf->entity)) dol_print_error($db); - else setEventMessage($langs->trans("RecordModifiedSuccessfully")); + $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); + $res3=dolibarr_set_const($db, 'MAIN_UPLOAD_DOC',$_POST["MAIN_UPLOAD_DOC"],'chaine',0,'',$conf->entity); + $res4=dolibarr_set_const($db, "MAIN_UMASK", $_POST["MAIN_UMASK"],'chaine',0,'',$conf->entity); + $res5=dolibarr_set_const($db, "MAIN_ANTIVIRUS_COMMAND", $_POST["MAIN_ANTIVIRUS_COMMAND"],'chaine',0,'',$conf->entity); + $res6=dolibarr_set_const($db, "MAIN_ANTIVIRUS_PARAM", $_POST["MAIN_ANTIVIRUS_PARAM"],'chaine',0,'',$conf->entity); + if ($res1 && $res2 && $res3 && $res4 && $res5 && $res6) setEventMessage($langs->trans("RecordModifiedSuccessfully")); } + + // Delete file else if ($action == 'delete') { @@ -131,42 +118,17 @@ print_fiche_titre($langs->trans("SecuritySetup"),'','setup'); print $langs->trans("MiscellaneousDesc")."
\n"; print "
\n"; + + +print '
'; +print ''; +print ''; + $head=security_prepare_head(); dol_fiche_head($head, 'misc', $langs->trans("Security")); -// Timeout -$var=true; - -print ''; -print ''; -print ''; -print ''; -print ''; -print "\n"; - -$var=!$var; -$sessiontimeout=ini_get("session.gc_maxlifetime"); -if (empty($conf->global->MAIN_SESSION_TIMEOUT)) $conf->global->MAIN_SESSION_TIMEOUT=$sessiontimeout; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; - -print '
'.$langs->trans("Parameters").''.$langs->trans("Value").' 
'.$langs->trans("SessionTimeOut").''; -print $form->textwithpicto('',$langs->trans("SessionExplanation",ini_get("session.gc_probability"),ini_get("session.gc_divisor"))); -print ''; -print ' '.strtolower($langs->trans("Seconds")); -print ''; -print ''; -print '
'; - -print '
'; - // Other Options $var=true; @@ -231,6 +193,44 @@ print ""; print ''; + +print '
'; + + +// Timeout +$var=true; + +print ''; +print ''; +print ''; +print ''; +print "\n"; + +$var=!$var; +$sessiontimeout=ini_get("session.gc_maxlifetime"); +if (empty($conf->global->MAIN_SESSION_TIMEOUT)) $conf->global->MAIN_SESSION_TIMEOUT=$sessiontimeout; +print ''; +print ''; +print ''; +print ''; + +$var=!$var; +$sessiontimeout=ini_get("session.gc_maxlifetime"); +if (empty($conf->global->MAIN_APPLICATION_TITLE)) $conf->global->MAIN_APPLICATION_TITLE=""; +print ''; +print ''; +print ''; +print ''; + +print '
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'.$langs->trans("SessionTimeOut").''; +print $form->textwithpicto('',$langs->trans("SessionExplanation",ini_get("session.gc_probability"),ini_get("session.gc_divisor"))); +print ''; +print ' '.strtolower($langs->trans("Seconds")); +print '
'.$langs->trans("MAIN_APPLICATION_TITLE").''; +print ''; +print ' '; +print '
'; + print '
'; // Upload options @@ -240,11 +240,8 @@ print ''; print ''; print ''; print ''; -print ''; print ''; -print ''; -print ''; print ''; print ''; print ''; -print ''; -print ''; +print ''; $var=!$var; -print ''; -print ''; print ''; print ''; print ''; -print ''; -print ''; +print ''; // Use anti virus $var=!$var; -print ''; -print ''; print ""; print '"; -print ''; print ''; -print ''; // Use anti virus $var=!$var; -print ''; -print ''; print ""; print ''; print '"; -print ''; print ''; -print ''; print '
'.$langs->trans("Parameters").''.$langs->trans("Value").' 
'.$langs->trans("MaxSizeForUploadedFiles").'.'; $max=@ini_get('upload_max_filesize'); @@ -254,14 +251,9 @@ print ''; print ' '.$langs->trans("Kb"); print ''; -print ''; -print '
'.$langs->trans("UMask").''; print $form->textwithpicto('',$langs->trans("UMaskExplanation")); @@ -269,15 +261,10 @@ print ''; print ''; print ''; -print ''; -print '
'.$langs->trans("AntiVirusCommand").'
'; print $langs->trans("AntiVirusCommandExample"); @@ -297,16 +284,10 @@ if (ini_get('safe_mode') && ! empty($conf->global->MAIN_ANTIVIRUS_COMMAND)) } print ''; print "
'; -print ''; -print '
'.$langs->trans("AntiVirusParam").'
'; print $langs->trans("AntiVirusParamExample"); @@ -314,16 +295,18 @@ print '
'; print ''; print "'; -print ''; -print '
'; dol_fiche_end(); +print '
'; + +print ''; + + + // Form to test upload print '
'; $formfile=new FormFile($db); @@ -333,6 +316,5 @@ $formfile->form_attach_new_file($_SERVER['PHP_SELF'], $langs->trans("FormToTestF $filearray=dol_dir_list($upload_dir, "files", 0, '', '', 'name', SORT_ASC, 1); $formfile->list_of_documents($filearray, '', 'admin_temp', ''); - llxFooter(); $db->close(); diff --git a/htdocs/admin/spip.php b/htdocs/admin/spip.php index af46c074bb9..9c81338562e 100644 --- a/htdocs/admin/spip.php +++ b/htdocs/admin/spip.php @@ -117,10 +117,11 @@ $head = mailmanspip_admin_prepare_head(); dol_fiche_head($head, 'spip', $langs->trans("Setup"), 0, 'user'); +$var=true; + /* * Spip */ -$var=!$var; if (! empty($conf->global->ADHERENT_USE_SPIP)) { //$lien=img_picto($langs->trans("Active"),'tick').' '; diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index 3cc9e70ca31..6b2c626da39 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -113,35 +113,20 @@ $linkback=''.$langs->trans("BackToM print_fiche_titre($langs->trans("StockSetup"),$linkback,'setup'); $form=new Form($db); -$var=true; -print ''; -print ''; -print " \n"; -print " \n"; -print ''."\n"; -/* - * Formulaire parametres divers - */ +$disabled=''; +if (! empty($conf->productbatch->enabled)) +{ + $langs->load("productbatch"); + $disabled=' disabled="disabled"'; + print info_admin($langs->trans("WhenProductBatchModuleOnOptionAreForced")); +} -$var=!$var; - -print ""; -print ''; - -print '\n"; -print "\n"; -print '
'; -print '
".$langs->trans("Parameters")." 
'.$langs->trans("UserWarehouseAutoCreate").''; -print "
"; -print ''; -print ""; -print $form->selectyesno("STOCK_USERSTOCK_AUTOCREATE",$conf->global->STOCK_USERSTOCK_AUTOCREATE,1); -print ''; -print '
'; -print "
'; -print '
'; +//if (! empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) || ! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) +//{ +print info_admin($langs->trans("IfYouUsePointOfSaleCheckModule")); +//} // Title rule for stock decrease print ''; @@ -160,8 +145,8 @@ if (! empty($conf->facture->enabled)) print ""; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_BILL",$conf->global->STOCK_CALCULATE_ON_BILL,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_BILL",$conf->global->STOCK_CALCULATE_ON_BILL,1,$disabled); + print ''; print "\n\n\n"; } @@ -174,8 +159,8 @@ if (! empty($conf->commande->enabled)) print ""; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_VALIDATE_ORDER",$conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_VALIDATE_ORDER",$conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER,1,$disabled); + print ''; print "\n\n\n"; } @@ -188,11 +173,12 @@ if (! empty($conf->expedition->enabled)) print ""; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_SHIPMENT",$conf->global->STOCK_CALCULATE_ON_SHIPMENT,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_SHIPMENT",$conf->global->STOCK_CALCULATE_ON_SHIPMENT,1,$disabled); + print ''; print "\n\n\n"; } print '
'; + print '
'; // Title rule for stock increase @@ -212,8 +198,8 @@ if (! empty($conf->fournisseur->enabled)) print "
"; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_BILL",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_BILL",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL,1,$disabled); + print ''; print "
\n\n\n"; } @@ -226,8 +212,8 @@ if (! empty($conf->fournisseur->enabled)) print "
"; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER,1,$disabled); + print ''; print "
\n\n\n"; } if (! empty($conf->fournisseur->enabled)) @@ -239,8 +225,8 @@ if (! empty($conf->fournisseur->enabled)) print "
"; print ''; print ""; - print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER,1); - print ''; + print $form->selectyesno("STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER",$conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER,1,$disabled); + print ''; print "
\n\n\n"; } @@ -330,6 +316,33 @@ if ($virtualdiffersfromphysical) } +$var=true; +print ''; + +print ''; +print " \n"; +print " \n"; +print ''."\n"; + +$var=!$var; + +print ""; +print ''; + +print '\n"; +print "\n"; +print '
'; +print '
".$langs->trans("Other")." 
'.$langs->trans("UserWarehouseAutoCreate").''; +print "
"; +print ''; +print ""; +print $form->selectyesno("STOCK_USERSTOCK_AUTOCREATE",$conf->global->STOCK_USERSTOCK_AUTOCREATE,1); +print ''; +print '
'; +print "
'; +print '
'; + + llxFooter(); $db->close(); diff --git a/htdocs/admin/supplier_invoice.php b/htdocs/admin/supplier_invoice.php index 5745c5f82ba..2f48eb2be79 100644 --- a/htdocs/admin/supplier_invoice.php +++ b/htdocs/admin/supplier_invoice.php @@ -198,7 +198,7 @@ print_fiche_titre($langs->trans("SuppliersSetup"),$linkback,'setup'); print "
"; -$head = supplierorder_admin_prepare_head(null); +$head = supplierorder_admin_prepare_head(); dol_fiche_head($head, 'invoice', $langs->trans("Suppliers"), 0, 'company'); diff --git a/htdocs/admin/supplier_order.php b/htdocs/admin/supplier_order.php index ac2ab824233..2d4be98f34a 100644 --- a/htdocs/admin/supplier_order.php +++ b/htdocs/admin/supplier_order.php @@ -199,7 +199,7 @@ print_fiche_titre($langs->trans("SuppliersSetup"),$linkback,'setup'); print "
"; -$head = supplierorder_admin_prepare_head(null); +$head = supplierorder_admin_prepare_head(); dol_fiche_head($head, 'order', $langs->trans("Suppliers"), 0, 'company'); diff --git a/htdocs/admin/supplierinvoice_extrafields.php b/htdocs/admin/supplierinvoice_extrafields.php index 85131440646..79dc0637b46 100644 --- a/htdocs/admin/supplierinvoice_extrafields.php +++ b/htdocs/admin/supplierinvoice_extrafields.php @@ -44,7 +44,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -75,7 +75,7 @@ $linkback='
'.$langs->trans("BackToM print_fiche_titre($langs->trans("SuppliersSetup"),$linkback,'setup'); print "
\n"; -$head = supplierorder_admin_prepare_head(null); +$head = supplierorder_admin_prepare_head(); dol_fiche_head($head, 'supplierinvoice', $langs->trans("Suppliers"), 0, 'company'); diff --git a/htdocs/admin/supplierorder_extrafields.php b/htdocs/admin/supplierorder_extrafields.php index 9cb2dc65880..96e20b92f17 100644 --- a/htdocs/admin/supplierorder_extrafields.php +++ b/htdocs/admin/supplierorder_extrafields.php @@ -42,7 +42,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -73,7 +73,7 @@ $linkback='
'.$langs->trans("BackToM print_fiche_titre($langs->trans("SuppliersSetup"),$linkback,'setup'); print "
\n"; -$head = supplierorder_admin_prepare_head(null); +$head = supplierorder_admin_prepare_head(); dol_fiche_head($head, 'supplierorder', $langs->trans("Suppliers"), 0, 'company'); diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index b69e8a4cacf..18de8bf6bfc 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -183,8 +183,9 @@ foreach ($syslogModules as $moduleName) { $module = new $moduleName; - $moduleactive=$module->isActive(); - if ($moduleactive == -1 && empty($conf->global->MAIN_FEATURES_LEVEL)) continue; // Some modules are hidden if not activable and not into debug mode (end user must not see them) + $moduleactive=(int) $module->isActive(); + //print $moduleName." = ".$moduleactive." - ".$module->getName()." ".($moduleactive == -1)."
\n"; + if (($moduleactive == -1) && empty($conf->global->MAIN_FEATURES_LEVEL)) continue; // Some modules are hidden if not activable and not into debug mode (end user must not see them) $var=!$var; print ''; @@ -199,7 +200,7 @@ foreach ($syslogModules as $moduleName) { foreach ($setuparray as $option) { - if (isset($_POST[$option['constant']])) $value=$_POST[$option['constant']]; + if (isset($_POST[$option['constant']])) $value=$_POST[$option['constant']]; else if (defined($option['constant'])) $value = constant($option['constant']); else $value = (isset($option['default']) ? $option['default'] : ''); @@ -220,7 +221,7 @@ foreach ($syslogModules as $moduleName) print "\n"; print "\n"; -print '
'; +print '
'."\n\n"; print_titre($langs->trans("SyslogLevel")); diff --git a/htdocs/admin/system/browser.php b/htdocs/admin/system/browser.php new file mode 100644 index 00000000000..58601c6e998 --- /dev/null +++ b/htdocs/admin/system/browser.php @@ -0,0 +1,80 @@ + + * Copyright (C) 2007 Rodolphe Quiedeville + * Copyright (C) 2007-2012 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/admin/system/browser.php + * \brief Page to show Dolibarr informations + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + +$langs->load("admin"); +$langs->load("install"); +$langs->load("other"); + +if (! $user->admin) + accessforbidden(); + + +/* + * View + */ + +$form=new Form($db); + +llxHeader(); + +print_fiche_titre($langs->trans("InfoBrowser"),'','setup'); + +$tmp=getBrowserInfo(); + +// Browser +$var=true; +print ''; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; +print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("UserAgent").''.$_SERVER['HTTP_USER_AGENT'].'
'.$langs->trans("BrowserName").''.$tmp['browsername'].'
'.$langs->trans("BrowserOS").''.$tmp['browseros'].'
'.$langs->trans("Version").''.$tmp['browserversion'].'
'.$langs->trans("Layout").' (phone/tablet/classic)'.$tmp['layout'].'
'.$langs->trans("IPAddress").''.$_SERVER['REMOTE_ADDR'].'
'.$langs->trans("SessionName").''.session_name().'
'.$langs->trans("SessionId").''.session_id().'
'.$langs->trans("Screen").''; +print $_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; +print '
'; +print '
'; + + + +llxFooter(); + +$db->close(); diff --git a/htdocs/admin/system/database.php b/htdocs/admin/system/database.php index d9833a13d01..1cacc757971 100644 --- a/htdocs/admin/system/database.php +++ b/htdocs/admin/system/database.php @@ -44,7 +44,7 @@ print_fiche_titre($langs->trans("InfoDatabase"),'','setup'); // Database print ''; print ''."\n"; -print ''."\n"; +print ''."\n"; print ''."\n"; print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/system/dbtable.php b/htdocs/admin/system/dbtable.php index 0990d89acd0..3102248bc0a 100644 --- a/htdocs/admin/system/dbtable.php +++ b/htdocs/admin/system/dbtable.php @@ -129,4 +129,5 @@ else } llxFooter(); + $db->close(); diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index fe9bde59cec..641a3166c04 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -90,6 +90,20 @@ $var=!$var; print ''."\n"; +$var=!$var; +print ''."\n"; +$var=!$var; +print ''."\n"; print '
'.$langs->trans("Database").'
'.$langs->trans("Version").''.getStaticMember(get_class($db),'label').' '.$db->getVersion().'
'.$langs->trans("Version").''.$db::LABEL.' '.$db->getVersion().'
'.$langs->trans("DatabaseServer").''.$conf->db->host.'
'.$langs->trans("DatabasePort").''.(empty($conf->db->port)?$langs->trans("Default"):$conf->db->port).'
'.$langs->trans("DatabaseName").''.$conf->db->name.'
'.$langs->trans("CurrentMenuHandler").''; print $conf->standard_menu; print '
'.$langs->trans("Screen").''; +print $_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; +print '
'.$langs->trans("Session").''; +$i=0; +foreach($_SESSION as $key => $val) +{ + if ($i > 0) print ', '; + print $key.' => '.$val; + $i++; +} +print '
'; print '
'; @@ -310,6 +324,22 @@ foreach($configfileparameters as $key => $value) print ""; if ($newkey == 'dolibarr_main_db_pass') print preg_replace('/./i','*',${$newkey}); else if ($newkey == 'dolibarr_main_url_root' && preg_match('/__auto__/',${$newkey})) print ${$newkey}.' => '.constant('DOL_MAIN_URL_ROOT'); + else if ($newkey == 'dolibarr_main_document_root_alt') + { + $tmparray=explode(',',${$newkey}); + $i=0; + foreach($tmparray as $value2) + { + if ($i > 0) print ', '; + print $value2; + if (! is_readable($value2)) + { + $langs->load("errors"); + print ' '.img_warning($langs->trans("ErrorCantReadDir",$value2)); + } + ++$i; + } + } else print ${$newkey}; if ($newkey == 'dolibarr_main_url_root' && $newkey != DOL_MAIN_URL_ROOT) print ' (currently overwritten by autodetected value: '.DOL_MAIN_URL_ROOT.')'; print ""; diff --git a/htdocs/admin/system/index.php b/htdocs/admin/system/index.php index 1f95dce57cf..64df9432e82 100644 --- a/htdocs/admin/system/index.php +++ b/htdocs/admin/system/index.php @@ -86,7 +86,7 @@ print "
\n"; // Database print ''; print "\n"; -$dblabel=getStaticMember(get_class($db),'label'); +$dblabel=$db::LABEL; $dbversion=$db->getVersion(); print "\n"; print '
".$langs->trans("Database")."
".$langs->trans("Version")."" .$dblabel." ".$dbversion."
'; @@ -95,11 +95,10 @@ if ($db->type == 'pgsql') { // Check option standard_conforming_strings is on $paramarray=$db->getServerParametersValues('standard_conforming_strings'); - if ($paramarray['standard_conforming_strings'] != 'on' && $paramarray['standard_conforming_strings'] != 1) - { - $langs->load("errors"); - //print '
'.$langs->trans("ErrorDatabaseParameterWrong",'standard_conforming_strings','on').'
'; - } +// if ($paramarray['standard_conforming_strings'] != 'on' && $paramarray['standard_conforming_strings'] != 1) +// { +// $langs->load("errors"); +// } } print '
'; diff --git a/htdocs/admin/tools/dolibarr_export.php b/htdocs/admin/tools/dolibarr_export.php index 8154cfffb08..9d5317fdd88 100644 --- a/htdocs/admin/tools/dolibarr_export.php +++ b/htdocs/admin/tools/dolibarr_export.php @@ -65,7 +65,7 @@ if ($action == 'delete') $form=new Form($db); $formfile = new FormFile($db); -$label=getStaticMember($db, 'label'); +$label=$db::LABEL; $help_url='EN:Backups|FR:Sauvegardes|ES:Copias_de_seguridad'; llxHeader('','',$help_url); @@ -366,9 +366,11 @@ print $langs->trans("BackupDescY").'

'; id="filename_template" value="" />

@@ -376,16 +378,19 @@ echo $file; array('function' => '', 'id' => 'radio_compression_none', 'label' => $langs->trans("None")), - 'gz' => array('function' => 'gzopen', 'id' => 'radio_compression_gzip', 'label' => $langs->trans("Gzip")), -); +$compression=array(); if ($label == 'MySQL') { -// $compression['zip']= array('function' => 'dol_compress', 'id' => 'radio_compression_zip', 'label' => $langs->trans("FormatZip")); // Not open source format. Must implement dol_compress function + $compression['none'] = array('function' => '', 'id' => 'radio_compression_none', 'label' => $langs->trans("None")); + $compression['gz'] = array('function' => 'gzopen', 'id' => 'radio_compression_gzip', 'label' => $langs->trans("Gzip")); + // $compression['zip']= array('function' => 'dol_compress', 'id' => 'radio_compression_zip', 'label' => $langs->trans("FormatZip")); // Not open source format. Must implement dol_compress function $compression['bz'] = array('function' => 'bzopen', 'id' => 'radio_compression_bzip', 'label' => $langs->trans("Bzip2")); } - +else +{ + $compression['none'] = array('function' => '', 'id' => 'radio_compression_none', 'label' => $langs->trans("Default")); + $compression['gz'] = array('function' => 'gzopen', 'id' => 'radio_compression_gzip', 'label' => $langs->trans("Gzip")); +} // Show compression choices print '
'; diff --git a/htdocs/admin/tools/dolibarr_import.php b/htdocs/admin/tools/dolibarr_import.php index 61e7e1e68a1..0cd1ae19fa9 100644 --- a/htdocs/admin/tools/dolibarr_import.php +++ b/htdocs/admin/tools/dolibarr_import.php @@ -38,7 +38,7 @@ $showpass=GETPOST('showpass'); * View */ -$label=getStaticMember($db, 'label'); +$label=$db::LABEL; $help_url='EN:Restores|FR:Restaurations|ES:Restauraciones'; llxHeader('','',$help_url); @@ -94,7 +94,7 @@ print $langs->trans("RestoreDesc3",DOL_DATA_ROOT).'

'; ?>
/> - +
trans("ImportPostgreSqlDesc"); print '
'; diff --git a/htdocs/admin/tools/export.php b/htdocs/admin/tools/export.php index 8dccf89de09..203776bc7f9 100644 --- a/htdocs/admin/tools/export.php +++ b/htdocs/admin/tools/export.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2006-2014 Laurent Destailleur * Copyright (C) 2011 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -289,7 +289,9 @@ if ($what == 'postgresql') if (preg_match("/\s/",$command)) $command=$command=escapeshellarg($command); // Use quotes on command //$param=escapeshellarg($dolibarr_main_db_name)." -h ".escapeshellarg($dolibarr_main_db_host)." -u ".escapeshellarg($dolibarr_main_db_user)." -p".escapeshellarg($dolibarr_main_db_pass); - $param=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host; + //$param="-F c"; + $param="-F p"; + $param.=" --no-tablespaces --inserts -h ".$dolibarr_main_db_host; $param.=" -U ".$dolibarr_main_db_user; if (! empty($dolibarr_main_db_port)) $param.=" -p ".$dolibarr_main_db_port; if (GETPOST("sql_compat") && GETPOST("sql_compat") == 'ANSI') $param.=" --disable-dollar-quoting"; @@ -416,7 +418,7 @@ function backup_tables($outputfile, $tables='*') // Print headers and global mysql config vars $sqlhead = ''; - $sqlhead .= "-- ".getStaticMember($db, 'label')." dump via php + $sqlhead .= "-- ".$db::LABEL." dump via php -- -- Host: ".$db->db->host_info." Database: ".$db->database_name." -- ------------------------------------------------------ @@ -464,11 +466,11 @@ function backup_tables($outputfile, $tables='*') fwrite($handle, "\n--\n-- Dumping data for table `".$table."`\n--\n"); if (!GETPOST("nobin_nolocks")) fwrite($handle, "LOCK TABLES `".$table."` WRITE;\n"); // Lock the table before inserting data (when the data will be imported back) if (GETPOST("nobin_disable_fk")) fwrite($handle, "ALTER TABLE `".$table."` DISABLE KEYS;\n"); - + $sql='SELECT * FROM '.$table; $result = $db->query($sql); $num_fields = $db->num_rows($result); - while($row = $db->fetch_row($result)) + while($row = $db->fetch_row($result)) { // For each row of data we print a line of INSERT fwrite($handle,'INSERT '.$delayed.$ignore.'INTO `'.$table.'` VALUES ('); @@ -497,7 +499,7 @@ function backup_tables($outputfile, $tables='*') fwrite($handle,"\n\n\n"); } } - + /* Backup Procedure structure*/ /* $result = $db->query('SHOW PROCEDURE STATUS'); diff --git a/htdocs/admin/tools/listevents.php b/htdocs/admin/tools/listevents.php index 10bd42d9590..fe577419eaf 100644 --- a/htdocs/admin/tools/listevents.php +++ b/htdocs/admin/tools/listevents.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -78,7 +78,7 @@ if ($action == 'confirm_purge' && $confirm == 'yes' && $user->admin) $sql = "DELETE FROM ".MAIN_DB_PREFIX."events"; $sql.= " WHERE entity = ".$conf->entity; - dol_syslog("listevents purge sql=".$sql); + dol_syslog("listevents purge", LOG_DEBUG); $resql = $db->query($sql); if (! $resql) { @@ -229,10 +229,11 @@ if ($result) // Description print ''; $text=$langs->trans($obj->description); - if (preg_match('/\((.*)\)/i',$obj->description,$reg)) + if (preg_match('/\((.*)\)(.*)/i',$obj->description,$reg)) { $val=explode(',',$reg[1]); $text=$langs->trans($val[0], isset($val[1])?$val[1]:'', isset($val[2])?$val[2]:'', isset($val[3])?$val[3]:'', isset($val[4])?$val[4]:''); + if (! empty($reg[2])) $text.=$reg[2]; } print $text; print ''; diff --git a/htdocs/admin/tools/purge.php b/htdocs/admin/tools/purge.php index 30c7ba4dd43..4f3f14302fd 100644 --- a/htdocs/admin/tools/purge.php +++ b/htdocs/admin/tools/purge.php @@ -165,4 +165,5 @@ if (preg_match('/^confirm/i',$choice)) llxFooter(); + $db->close(); diff --git a/htdocs/admin/tools/update.php b/htdocs/admin/tools/update.php index 8b0b105d0f0..40683bdc747 100644 --- a/htdocs/admin/tools/update.php +++ b/htdocs/admin/tools/update.php @@ -30,7 +30,9 @@ $langs->load("other"); if (! $user->admin) accessforbidden(); -if (GETPOST('msg','alpha')) $message='
'.GETPOST('msg','alpha').'
'; +if (GETPOST('msg','alpha')) { + setEventMessage(GETPOST('msg','alpha'), 'errors'); +} $urldolibarr='http://www.dolibarr.org/downloads/'; @@ -54,7 +56,7 @@ if (GETPOST('action','alpha')=='install') if (! $original_file) { $langs->load("Error"); - $mesg = '
'.$langs->trans("ErrorFileRequired").'
'; + setEventMessage($langs->trans("ErrorFileRequired"), 'warnings'); $error++; } else @@ -62,7 +64,7 @@ if (GETPOST('action','alpha')=='install') if (! preg_match('/\.zip/i',$original_file)) { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorFileMustBeADolibarrPackage",$original_file).'
'; + setEventMessage($langs->trans("ErrorFileMustBeADolibarrPackage",$original_file), 'errors'); $error++; } } @@ -80,12 +82,11 @@ if (GETPOST('action','alpha')=='install') if (! empty($result['error'])) { $langs->load("errors"); - $mesg = '
'.$langs->trans($result['error'],$original_file).'
'; - + setEventMessage($langs->trans($result['error'],$original_file), 'errors'); } else { - $mesg = '
'.$langs->trans("SetupIsReadyForUse").'
'; + setEventMessage($langs->trans("SetupIsReadyForUse")); } } } @@ -107,9 +108,6 @@ print $langs->trans("CurrentVersion").' : '.DOL_VERSION.'
'; print $langs->trans("LastStableVersion").' : '.$langs->trans("FeatureNotYetAvailable").'
'; print '
'; -//dol_htmloutput_errors($mesg); -dol_htmloutput_mesg($mesg); - print $langs->trans("Upgrade").'
'; print '
'; print $langs->trans("ThisIsProcessToFollow").'
'; @@ -152,7 +150,7 @@ if (! empty($conf->global->MAIN_ONLINE_INSTALL_MODULE)) else { $message=info_admin($langs->trans("NotExistsDirect",$dirins).$langs->trans("InfDirAlt").$langs->trans("InfDirExample")); - print '
'.$message.'
'; + setEventMessage($message, 'warnings'); } } else @@ -173,4 +171,5 @@ if (! empty($result['return'])) } llxFooter(); + $db->close(); diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 66bc4fb22ba..95e3f555b6d 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -57,8 +57,6 @@ print_fiche_titre($langs->trans("TranslationSetup"),'','setup'); print $langs->trans("TranslationDesc")."
\n"; print "
\n"; -dol_htmloutput_mesg($message); - print $langs->trans("CurrentUserLanguage").': '.$langs->defaultlang.'
'; print img_warning().' '.$langs->trans("SomeTranslationAreUncomplete").'
'; diff --git a/htdocs/admin/triggers.php b/htdocs/admin/triggers.php index fc9d0489e9a..85139b56ba9 100644 --- a/htdocs/admin/triggers.php +++ b/htdocs/admin/triggers.php @@ -50,7 +50,7 @@ print "
\n"; $template_dir = DOL_DOCUMENT_ROOT.'/core/tpl/'; $interfaces = new Interfaces($db); -$triggers = $interfaces->getTriggersList(0,'priority'); +$triggers = $interfaces->getTriggersList(); print ' diff --git a/htdocs/asterisk/index.html b/htdocs/asterisk/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/asterisk/index.php b/htdocs/asterisk/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/asterisk/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/barcode/codeinit.php b/htdocs/barcode/codeinit.php index d6ca6a7d66f..19fb5c193bb 100644 --- a/htdocs/barcode/codeinit.php +++ b/htdocs/barcode/codeinit.php @@ -37,8 +37,6 @@ $forbarcode=GETPOST('forbarcode'); $fk_barcode_type=GETPOST('fk_barcode_type'); $eraseallbarcode=GETPOST('eraseallbarcode'); -$mesg=''; - $action=GETPOST('action'); $producttmp=new Product($db); @@ -126,7 +124,7 @@ if ($action == 'initbarcodeproducts') $sql.=$db->order("datec","ASC"); $sql.=$db->plimit($maxperinit); - dol_syslog("codeinit sql=".$sql, LOG_DEBUG); + dol_syslog("codeinit", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -198,8 +196,6 @@ print '
'; print $langs->trans("MassBarcodeInitDesc").'
'; print '
'; -dol_htmloutput_errors($mesg); - //print img_picto('','puce').' '.$langs->trans("PrintsheetForOneBarCode").'
'; //print '
'; @@ -291,7 +287,7 @@ if ($conf->product->enabled || $conf->product->service) { print $langs->trans("BarCodeNumberManager").": "; $objproduct=new Product($db); - print ''.$modBarCodeProduct->nom.' - '.$langs->trans("NextValue").': '.$modBarCodeProduct->getNextValue($objproduct).'
'; + print ''.(isset($modBarCodeProduct->name)?$modBarCodeProduct->name:$modBarCodeProduct->nom).' - '.$langs->trans("NextValue").': '.$modBarCodeProduct->getNextValue($objproduct).'
'; $disabled=0; } else diff --git a/htdocs/barcode/index.html b/htdocs/barcode/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php index d862cb5da8f..0ce692674b1 100644 --- a/htdocs/barcode/printsheet.php +++ b/htdocs/barcode/printsheet.php @@ -121,8 +121,8 @@ if ($action == 'builddoc') if (! $error) { $code=$forbarcode; - $generator=$stdobject->barcode_type_coder; - $encoding=strtoupper($stdobject->barcode_type_code); + $generator=$stdobject->barcode_type_coder; // coder (loaded by fetch_barcode). Engine. + $encoding=strtoupper($stdobject->barcode_type_code); // code (loaded by fetch_barcode). Example 'ean', 'isbn', ... $barcodeimage=$conf->barcode->dir_temp.'/barcode_'.$code.'_'.$encoding.'.png'; $diroutput=$conf->barcode->dir_temp; diff --git a/htdocs/bookmarks/admin/bookmark.php b/htdocs/bookmarks/admin/bookmark.php index ad480f6cf7f..68adb30f7ab 100644 --- a/htdocs/bookmarks/admin/bookmark.php +++ b/htdocs/bookmarks/admin/bookmark.php @@ -42,12 +42,12 @@ if ($action == 'setvalue') if (! $error) { $db->commit(); - $mesg = "".$langs->trans("SetupSaved").""; + setEventMessage($langs->trans("SetupSaved")); } else { $db->rollback(); - $mesg = "".$langs->trans("Error").""; + setEventMessage($langs->trans("Error"), 'errors'); } } @@ -82,8 +82,6 @@ print ''; -dol_htmloutput_mesg($mesg); - $db->close(); llxFooter(); diff --git a/htdocs/bookmarks/admin/index.html b/htdocs/bookmarks/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/bookmarks/bookmarks.lib.php b/htdocs/bookmarks/bookmarks.lib.php index ebfe7e78db6..a9d2d7eb6c0 100644 --- a/htdocs/bookmarks/bookmarks.lib.php +++ b/htdocs/bookmarks/bookmarks.lib.php @@ -48,11 +48,11 @@ function printBookmarksList($aDb, $aLangs) // Menu bookmark $ret.= '
'; - $ret.= ''.$langs->trans('Bookmarks').''; + $ret.= ''.$langs->trans('Bookmarks').''; $ret.= ''; if ($user->rights->bookmark->creer) { - $ret.= ''; + $ret.= ''; //$ret.=img_picto($langs->trans('AddThisPageToBookmarks'),'edit_add').' '; $ret.=img_object($langs->trans('AddThisPageToBookmarks'),'bookmark'); $ret.= ''; diff --git a/htdocs/bookmarks/fiche.php b/htdocs/bookmarks/card.php similarity index 81% rename from htdocs/bookmarks/fiche.php rename to htdocs/bookmarks/card.php index 6167d6cd669..6bb6367171a 100644 --- a/htdocs/bookmarks/fiche.php +++ b/htdocs/bookmarks/card.php @@ -1,6 +1,7 @@ * Copyright (C) 2005-2013 Laurent Destailleur + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -17,7 +18,7 @@ */ /** - * \file htdocs/bookmarks/fiche.php + * \file htdocs/bookmarks/card.php * \brief Page display/creation of bookmarks * \ingroup bookmark */ @@ -43,6 +44,8 @@ $userid=GETPOST("userid","int"); $position=GETPOST("position","int"); $backtopage=GETPOST('backtopage','alpha'); +$bookmark=new Bookmark($db); + /* * Actions @@ -50,16 +53,15 @@ $backtopage=GETPOST('backtopage','alpha'); if ($action == 'add' || $action == 'addproduct' || $action == 'update') { + $error = 0; + if (GETPOST("cancel")) { - if (empty($backtopage)) $backtopage=(GETPOST("urlsource")?GETPOST("urlsource"):((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/liste.php')); + if (empty($backtopage)) $backtopage=(GETPOST("urlsource")?GETPOST("urlsource"):((! empty($url))?$url:DOL_URL_ROOT.'/bookmarks/list.php')); header("Location: ".$backtopage); exit; } - $mesg=''; - - $bookmark=new Bookmark($db); if ($action == 'update') $bookmark->fetch($_POST["id"]); $bookmark->fk_user=$userid; $bookmark->title=$title; @@ -67,10 +69,17 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') $bookmark->target=$target; $bookmark->position=$position; - if (! $title) $mesg.=($mesg?'
':'').$langs->trans("ErrorFieldRequired",$langs->trans("BookmarkTitle")); - if (! $url) $mesg.=($mesg?'
':'').$langs->trans("ErrorFieldRequired",$langs->trans("UrlOrLink")); + if (! $title) { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("BookmarkTitle")), 'errors'); + } - if (! $mesg) + if (! $url) { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("UrlOrLink")), 'errors'); + } + + if (! $error) { $bookmark->favicon='none'; @@ -79,7 +88,7 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') if ($res > 0) { - if (empty($backtopage)) $backtopage=(GETPOST("urlsource")?GETPOST("urlsource"):DOL_URL_ROOT.'/bookmarks/liste.php'); + if (empty($backtopage)) $backtopage=(GETPOST("urlsource")?GETPOST("urlsource"):DOL_URL_ROOT.'/bookmarks/list.php'); header("Location: ".$backtopage); exit; } @@ -88,44 +97,21 @@ if ($action == 'add' || $action == 'addproduct' || $action == 'update') if ($bookmark->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg='
'.$langs->trans("WarningBookmarkAlreadyExists").'
'; + setEventMessage($langs->trans("WarningBookmarkAlreadyExists"), 'warnings'); } else { - $mesg='
'.$bookmark->error.'
'; + setEventMessage($bookmark->error, 'errors'); } $action='create'; } } else { - $mesg='
'.$mesg.'
'; $action='create'; } } -if ($action == 'delete') -{ - $bookmark=new Bookmark($db); - $bookmark->id=$_GET["bid"]; - $bookmark->url=$user->id; - $bookmark->target=$user->id; - $bookmark->title='xxx'; - $bookmark->favicon='xxx'; - - $res=$bookmark->remove(); - if ($res > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } - else - { - $mesg='
'.$bookmark->error.'
'; - } -} - - /* * View */ @@ -135,6 +121,17 @@ llxHeader(); $form=new Form($db); +$head = array(); +$h=1; + +$head[$h][0] = $_SERVER["PHP_SELF"].($bookmark->id?'id='.$bookmark->id:''); +$head[$h][1] = $langs->trans("Card"); +$head[$h][2] = 'card'; +$h++; + +$hselected='card'; + + if ($action == 'create') { /* @@ -144,12 +141,10 @@ if ($action == 'create') print '
'."\n"; print ''; print ''; - + print_fiche_titre($langs->trans("NewBookmark")); dol_fiche_head($head, $hselected, $langs->trans("Bookmark"),0,'bookmark'); - - dol_htmloutput_mesg($mesg); print ''; @@ -171,16 +166,16 @@ if ($action == 'create') print 'position).'">'; print ''; - print '
 

'; - + print '
'; + + dol_fiche_end(); + print '
'; print '   '; print ''; print '
'; print ''; - - dol_fiche_end(); } @@ -189,32 +184,50 @@ if ($id > 0 && ! preg_match('/^add/i',$action)) /* * Fact bookmark mode or visually edition */ - $bookmark=new Bookmark($db); $bookmark->fetch($id); - dol_fiche_head($head, $hselected, $langs->trans("Bookmark"),0,'bookmark'); - if ($action == 'edit') { print '
'; print ''; print ''; print ''; - print ''; + print ''; print ''; } + dol_fiche_head($head, $hselected, $langs->trans("Bookmark"),0,'bookmark'); + print ''; print ''; - print ''; - print ''; @@ -263,12 +276,14 @@ if ($id > 0 && ! preg_match('/^add/i',$action)) print '
'.$langs->trans("Ref").''.$bookmark->ref.'
'.$langs->trans("BookmarkTitle").''; + print '
'; + if ($action == 'edit') { + print ''; + } + + print $langs->trans("BookmarkTitle"); + + if ($action == 'edit') { + print ''; + } + + print ''; if ($action == 'edit') print 'title).'">'; else print $bookmark->title; print '
'.$langs->trans("UrlOrLink").''; + print '
'; + if ($action == 'edit') { + print ''; + } + print $langs->trans("UrlOrLink"); + if ($action == 'edit') { + print ''; + } + print ''; if ($action == 'edit') print 'url).'">'; else print 'target?' target="_blank"':'').'>'.$bookmark->url.''; print '
'; - if ($action == 'edit') print '
   
'; - - if ($action == 'edit') print '
'; - dol_fiche_end(); + if ($action == 'edit') + { + print '
   
'; + print ''; + } + print "
'; diff --git a/htdocs/bookmarks/class/bookmark.class.php b/htdocs/bookmarks/class/bookmark.class.php index 2aa86c5db20..aa92d2bedb9 100644 --- a/htdocs/bookmarks/class/bookmark.class.php +++ b/htdocs/bookmarks/class/bookmark.class.php @@ -65,7 +65,7 @@ class Bookmark $sql.= " WHERE rowid = ".$id; $sql.= " AND entity = ".$conf->entity; - dol_syslog("Bookmark::fetch sql=".$sql, LOG_DEBUG); + dol_syslog("Bookmark::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -123,7 +123,7 @@ class Bookmark if ($this->fk_soc) $sql.=",".$this->fk_soc; $sql.= ")"; - dol_syslog("Bookmark::update sql=".$sql, LOG_DEBUG); + dol_syslog("Bookmark::update", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -173,7 +173,7 @@ class Bookmark $sql.= " ,position = '".$this->position."'"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog("Bookmark::update sql=".$sql, LOG_DEBUG); + dol_syslog("Bookmark::update", LOG_DEBUG); if ($this->db->query($sql)) { return 1; @@ -196,7 +196,7 @@ class Bookmark $sql = "DELETE FROM ".MAIN_DB_PREFIX."bookmark"; $sql .= " WHERE rowid = ".$id; - dol_syslog("Bookmark::remove sql=".$sql, LOG_DEBUG); + dol_syslog("Bookmark::remove", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/bookmarks/class/index.html b/htdocs/bookmarks/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/bookmarks/index.html b/htdocs/bookmarks/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/bookmarks/index.php b/htdocs/bookmarks/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/bookmarks/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/bookmarks/liste.php b/htdocs/bookmarks/list.php similarity index 91% rename from htdocs/bookmarks/liste.php rename to htdocs/bookmarks/list.php index c3524ae5d43..748a4d9b7fa 100644 --- a/htdocs/bookmarks/liste.php +++ b/htdocs/bookmarks/list.php @@ -16,7 +16,7 @@ */ /** - * \file htdocs/bookmarks/liste.php + * \file htdocs/bookmarks/list.php * \brief Page to display list of bookmarks * \ingroup bookmark */ @@ -25,6 +25,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/bookmarks/class/bookmark.class.php'; $langs->load("bookmarks"); +$langs->load("admin"); // Security check if (! $user->rights->bookmark->lire) { @@ -58,7 +59,7 @@ if ($_GET["action"] == 'delete') } else { - $mesg='
'.$bookmark->error.'
'; + setEventMessage($bookmark->error, 'errors'); } } @@ -73,8 +74,6 @@ llxHeader(); print_fiche_titre($langs->trans("Bookmarks")); -if ($mesg) print $mesg; - $sql = "SELECT b.fk_soc as rowid, b.dateb, b.rowid as bid, b.fk_user, b.url, b.target, b.title, b.favicon, b.position,"; $sql.= " u.login, u.lastname, u.firstname"; $sql.= " FROM ".MAIN_DB_PREFIX."bookmark as b LEFT JOIN ".MAIN_DB_PREFIX."user as u ON b.fk_user=u.rowid"; @@ -114,7 +113,7 @@ if ($resql) // Id print ''; - print "bid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->bid.""; + print "bid."\">".img_object($langs->trans("ShowBookmark"),"bookmark").' '.$obj->bid.""; print ''; $lieninterne=0; @@ -180,7 +179,7 @@ if ($resql) print ''; if ($user->rights->bookmark->creer) { - print "bid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; + print "bid."&backtopage=".urlencode($_SERVER["PHP_SELF"])."\">".img_edit()." "; } if ($user->rights->bookmark->supprimer) { @@ -208,7 +207,7 @@ print "
\n"; if ($user->rights->bookmark->creer) { - print ''.$langs->trans("NewBookmark").''; + print ''.$langs->trans("NewBookmark").''; } print '
'; diff --git a/htdocs/boutique/admin/boutique.php b/htdocs/boutique/admin/boutique.php deleted file mode 100644 index 65dab22f813..00000000000 --- a/htdocs/boutique/admin/boutique.php +++ /dev/null @@ -1,206 +0,0 @@ - - * Copyright (C) 2004 Sebastien Di Cintio - * Copyright (C) 2004 Benoit Mortier - * Copyright (C) 2006 Laurent Destailleur - * Copyright (C) 2012 Juanjo Menent - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/admin/boutique.php - * \ingroup boutique - * \brief Page d'administration/configuration du module OsCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; - -$langs->load("admin"); -$langs->load("oscommerce"); - -if (!$user->admin) accessforbidden(); - - - -/* - * Actions - */ - -if (GETPOST('save','alpha')) -{ - $db->begin(); - - $i=0; - - $i+=dolibarr_set_const($db,'OSC_DB_HOST',trim(GETPOST('oscommerce_dbhost','alpha')),'chaine',0,'',$conf->entity); - $i+=dolibarr_set_const($db,'OSC_DB_NAME',trim(GETPOST('oscommerce_dbname','alpha')),'chaine',0,'',$conf->entity); - $i+=dolibarr_set_const($db,'OSC_DB_USER',trim(GETPOST('oscommerce_dbuser','alpha')),'chaine',0,'',$conf->entity); - $i+=dolibarr_set_const($db,'OSC_DB_PASS',trim(GETPOST('oscommerce_dbpass','alpha')),'chaine',0,'',$conf->entity); - $i+=dolibarr_set_const($db,'OSC_DB_TABLE_PREFIX',trim(GETPOST('oscommerce_db_table_prefix','alpha')),'chaine',0,'',$conf->entity); - $i+=dolibarr_set_const($db,'OSC_LANGUAGE_ID',1,'chaine',0,'',$conf->entity); - - if ($i >= 4) - { - $db->commit(); - $mesg = "".$langs->trans("OSCommerceSetupSaved").""; - } - else - { - $db->rollback(); - header("Location: ".$_SERVER["PHP_SELF"]); - exit; - } -} -elseif (GETPOST('test','alpha')) -{ - //$resql=$db->query("select count(*) from ".MAIN_DB_PREFIX."const"); - //print "< ".$db." - ".$db->db." - ".$resql." - ".$db->error().">
\n"; - - // Test de la connexion a la database webcalendar - $conf->oscommerce->db->type=$dolibarr_main_db_type; - $conf->oscommerce->db->host=GETPOST('oscommerce_dbhost','alpha'); - $conf->oscommerce->db->port=GETPOST('oscommerce_dbport','alpha'); - $conf->oscommerce->db->name=GETPOST('oscommerce_dbname','alpha'); - $conf->oscommerce->db->user=GETPOST('oscommerce_dbuser','alpha'); - $conf->oscommerce->db->pass=GETPOST('oscommerce_dbpass','alpha'); - - $oscommercedb=getDoliDBInstance($conf->oscommerce->db->type,$conf->oscommerce->db->host,$conf->oscommerce->db->user,$conf->oscommerce->db->pass,$conf->oscommerce->db->name,$conf->oscommerce->db->port); - - if ($oscommercedb->connected == 1 && $oscommercedb->database_selected == 1) - { - // Verifie si bonne base par requete sur une table OSCommerce - $sql ="SELECT configuration_value"; - $sql.=" FROM ".$_POST["oscommerce_db_table_prefix"]."configuration"; - $sql.=" WHERE configuration_key='STORE_NAME'"; - $resql=$oscommercedb->query($sql); - if ($resql) { - $mesg ="
".$langs->trans("OSCommerceTestOk",GETPOST('oscommerce_dbhost','alpha'),GETPOST('oscommerce_dbname','alpha'),GETPOST('oscommerce_dbuser','alpha')); - $mesg.="
"; - } - else { - $mesg ="
".$langs->trans("OSCommerceErrorConnectOkButWrongDatabase",'STORE_NAME',GETPOST('oscommerce_db_table_prefix','alpha')."configuration"); - $mesg.="
"; - } - - //$oscommercedb->close(); Ne pas fermer car la conn de webcal est la meme que dolibarr si parametre host/user/pass identique - } - elseif ($oscommercedb->connected == 1 && $oscommercedb->database_selected != 1) - { - $mesg ="
".$langs->trans("OSCommerceTestKo1",GETPOST('oscommerce_dbhost','alpha'),GETPOST('oscommerce_dbname','alpha')); - $mesg.="
".$oscommercedb->error(); - $mesg.="
"; - //$oscommercedb->close(); Ne pas fermer car la conn de webcal est la meme que dolibarr si parametre host/user/pass identique - } - else - { - $mesg ="
".$langs->trans("OSCommerceTestKo2",GETPOST('oscommerce_dbhost','alpha'),GETPOST('oscommerce_dbuser','alpha')); - $mesg.="
".$oscommercedb->error(); - $mesg.="
"; - } - - //$resql=$db->query("select count(*) from ".MAIN_DB_PREFIX."const"); - //print "< ".$db." - ".$db->db." - ".$resql." - ".$db->error().">
\n"; -} - - - -/* - * Affichage page - */ - -llxHeader(); - -$linkback=''.$langs->trans("BackToModuleList").''; -print_fiche_titre($langs->trans("OSCommerceSetup"),$linkback,'setup'); - - - -print '
'; - -$var=true; -print '
'; -print ''; -print ""; -print ""; -print ""; -print ""; -print ""; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ""; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ""; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ""; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ""; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ''; -print ""; -$var=!$var; -print ""; -print ""; -print ""; -print ''; -print ""; -print "
".$langs->trans("Parameter")."".$langs->trans("Value")."".$langs->trans("Examples")."
".$langs->trans("OSCommerceServer")."global->OSC_DB_HOST) . "\" size=\"30\">localhost"; -//print "
__dolibarr_main_db_host__ (".$dolibarr_main_db_host.")" -print "
".$langs->trans("OSCommerceDatabaseName")."global->OSC_DB_NAME) . "\" size=\"30\">oscommerce"; -//print "
__dolibarr_main_db_name__ (".$dolibarr_main_db_name.")"; -print "
".$langs->trans("OSCommercePrefix")."global->DB_TABLE_PREFIX) . "\" size=\"30\">osc_"; -print "
".$langs->trans("OSCommerceUser")."global->OSC_DB_USER) . "\" size=\"30\">oscommerceuser"; -//print "
__dolibarr_main_db_user__ (".$dolibarr_main_db_user.")"; -print "
".$langs->trans("Password")."global->OSC_DB_PASS) . "\" size=\"30\">'; -//if ($dolibarr_main_db_pass) print '__dolibarr_main_db_pass__ ('.preg_replace('/./i','*',$dolibarr_main_db_pass).')'; -print ' 
".$langs->trans("PasswordRetype")."global->OSC_DB_PASS) ."\" size=\"30\">'; -//if ($dolibarr_main_db_pass) print '__dolibarr_main_db_pass__ ('.preg_replace('/./i','*',$dolibarr_main_db_pass).')'; -print ' 
"; - - -print '
'; -print "trans("TestConnection")."\">"; -print "   "; -print "trans("Save")."\">"; -print "
"; - -print "
\n"; - - -dol_htmloutput_mesg($mesg); - -$db->close(); - -llxFooter(); diff --git a/htdocs/boutique/client/class/boutiqueclient.class.php b/htdocs/boutique/client/class/boutiqueclient.class.php deleted file mode 100644 index fdf393043b0..00000000000 --- a/htdocs/boutique/client/class/boutiqueclient.class.php +++ /dev/null @@ -1,77 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/client/class/boutiqueclient.class.php - * \brief Classe permettant de gerer des clients de la boutique online - * \author Rodolphe Quiedeville - */ - -/** - * \class BoutiqueClient - * \brief Classe permettant de gerer des clients de la boutique online - */ -class BoutiqueClient -{ - var $db ; - - var $id ; - var $nom; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } - - /** - * Fonction permettant de recuperer les informations d'un clients de la boutique - * - * @param int $id Id du client - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $conf; - - $sql = "SELECT customers_id, customers_lastname, customers_firstname FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."customers WHERE customers_id = ".$id; - - $resql = $this->db->query($sql); - if ( $resql ) - { - $result = $this->db->fetch_array($resql); - - $this->id = $result["customers_id"]; - $this->name = $result["customers_firstname"] . " " . $result["customers_lastname"]; - - $this->db->free($resql); - return 1; - } - else - { - print $this->db->error(); - return -1; - } - } - -} diff --git a/htdocs/boutique/client/fiche.php b/htdocs/boutique/client/fiche.php deleted file mode 100644 index 895eea66e79..00000000000 --- a/htdocs/boutique/client/fiche.php +++ /dev/null @@ -1,126 +0,0 @@ - - * Copyright (C) 2003-2005 Eric Seigne - * Copyright (C) 2006-2010 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/client/fiche.php - * \ingroup boutique - * \brief Page fiche client OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; -include_once DOL_DOCUMENT_ROOT.'/boutique/client/class/boutiqueclient.class.php'; - -$id=GETPOST('id', 'int'); - - -/* - * Actions - */ - -// None - - - -/* - * View - */ - -llxHeader(); - -if ($id > 0) -{ - $client = new BoutiqueClient($dbosc); - $result = $client->fetch($id); - if ( $result ) - { - print '
'.$langs->trans("CustomerCard").': '.$client->name.'

'; - - print ''; - print ""; - print ''; - print "
Nom'.$client->name.'
"; - - - /* - * Commandes - */ - $sql = "SELECT o.orders_id, o.customers_id, date_purchased, t.value as total"; - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t"; - $sql .= " WHERE o.customers_id = " . $client->id; - $sql .= " AND o.orders_id = t.orders_id AND t.class = 'ot_total'"; - //echo $sql; - $resql=$dbosc->query($sql); - if ($resql) - { - $num = $dbosc->num_rows($resql); - $i = 0; - print ''; - print ""; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - - print '\n"; - print "\n"; - $i++; - } - print "
Commandes
Fiche '; - - print dol_print_date($dbosc->jdate($objp->date_purchased),'dayhour')."\n"; - print $objp->total . "
"; - $dbosc->free($resql); - } - else - { - print "

ERROR 1

\n"; - dol_print_error($dbosc); - } - - } - else - { - print "

ERROR 1

\n"; - dol_print_error($dbosc); - } -} -else -{ - print "

ERROR 1

\n"; - print "Error"; -} - - -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - -// Pas d'action - - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/client/index.php b/htdocs/boutique/client/index.php deleted file mode 100644 index 358a74a750f..00000000000 --- a/htdocs/boutique/client/index.php +++ /dev/null @@ -1,91 +0,0 @@ - - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/client/index.php - * \ingroup boutique - * \brief Page gestion client OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - -$langs->load("companies"); - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") { - $sortfield="lower(c.customers_lastname)"; -} -if ($sortorder == "") { - $sortorder="ASC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des clients", $page, "index.php"); - -$sql = "SELECT c.customers_id, c.customers_lastname, c.customers_firstname, c.customers_email_address, c.customers_newsletter"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."customers as c"; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print ""; - print ""; - print_liste_field_titre($langs->trans("Firstname"),"index.php", "c.customers_firstname"); - print_liste_field_titre($langs->trans("Lastname"),"index.php", "c.customers_lastname"); - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print '\n"; - print '\n"; - print "\n"; - print "\n"; - print "\n"; - $i++; - } - print "
'.$langs->trans("EMail").''.$langs->trans("Newsletter").'
'.$objp->customers_firstname."'.$objp->customers_lastname."$objp->customers_email_address$objp->customers_newsletter
"; - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/commande/ca.php b/htdocs/boutique/commande/ca.php deleted file mode 100644 index 5030e5ac559..00000000000 --- a/htdocs/boutique/commande/ca.php +++ /dev/null @@ -1,115 +0,0 @@ - - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/commande/ca.php - * \ingroup boutique - * \brief Page ca commandes du module OsCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") -{ - $sortfield="date_purchased"; -} -if ($sortorder == "") -{ - $sortorder="DESC"; -} - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des commandes", $page, "ca.php"); - -print ''; -print ''; -print ''; - -$sql = "SELECT sum(t.value) as value"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t"; -$sql .= " WHERE t.class = 'ot_subtotal'"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - - $var=True; - if ($num > 0) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print ''; - print ''; - - print "\n"; - $i++; - } - - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -$sql = "SELECT sum(t.value) as value"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t"; -$sql .= " WHERE t.class = 'ot_shipping'"; -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - - $var=True; - if ($num > 0) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print ''; - print ''; - $i++; - } - - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - - -print "
'.$langs->trans("Description").''.$langs->trans("Lastname").'
Somme des commandes'.price($objp->value).'
Somme des frais de port'.price($objp->value).'
"; - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/commande/class/boutiquecommande.class.php b/htdocs/boutique/commande/class/boutiquecommande.class.php deleted file mode 100644 index 0a3383a33a3..00000000000 --- a/htdocs/boutique/commande/class/boutiquecommande.class.php +++ /dev/null @@ -1,138 +0,0 @@ - - * Copyright (C) 2008 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/boutique/commande/class/boutiquecommande.class.php - * \ingroup osc - * \brief Fichier de la classe des commandes de la boutique online - */ - -require_once DOL_DOCUMENT_ROOT .'/societe/class/address.class.php'; -include_once DOL_DOCUMENT_ROOT.'/boutique/commande/class/boutiquecommande.class.php'; - - -/** - * Class to manage orders OSC - */ -class BoutiqueCommande -{ - var $db; - - var $id; - var $nom; - - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->billing_adr = new Address(); - $this->delivry_adr = new Address(); - - $this->total_ot_subtotal = 0; - $this->total_ot_shipping = 0; - } - - /** - * Get object and lines from database - * - * @param int $id id of object to load - * @param string $ref Ref of order - * @return int >0 if OK, <0 if KO - */ - function fetch($id,$ref='') - { - global $conf; - - $sql = "SELECT orders_id, customers_id, customers_name, customers_company, customers_street_address, customers_suburb, customers_city, customers_postcode, customers_state, customers_country, customers_telephone, customers_email_address, customers_address_format_id, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_zipcode, delivery_state, delivery_country, delivery_address_format_id, billing_name, billing_company, billing_street_address, billing_suburb, billing_city, billing_zipcode, billing_state, billing_country, billing_address_format_id, payment_method, cc_type, cc_owner, cc_number, cc_expires, last_modified, date_purchased, orders_status, orders_date_finished, currency, currency_value"; - $sql.= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders"; - $sql.= " WHERE orders_id = ".$id; - - $result = $this->db->query($sql); - if ( $result ) - { - $array = $this->db->fetch_array($result); - - $this->id = $array["orders_id"]; - $this->client_id = $array["customers_id"]; - $this->client_name = $array["customers_name"]; - - $this->payment_method = $array["payment_method"]; - - $this->date = $this->db->jdate($array["date_purchased"]); - - $this->delivery_adr->name = $array["delivery_name"]; - $this->delivery_adr->street = $array["delivery_street_address"]; - $this->delivery_adr->zip = $array["delivery_zipcode"]; - $this->delivery_adr->city = $array["delivery_city"]; - $this->delivery_adr->country = $array["delivery_country"]; - - $this->billing_adr->name = $array["billing_name"]; - $this->billing_adr->street = $array["billing_street_address"]; - $this->billing_adr->zip = $array["billing_zipcode"]; - $this->billing_adr->city = $array["billing_city"]; - $this->billing_adr->country = $array["billing_country"]; - - $this->db->free(); - - /* - * Totaux - */ - $sql = "SELECT value, class "; - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total WHERE orders_id = $id"; - - $result = $this->db->query($sql); - if ( $result ) - { - $num = $this->db->num_rows($result); - - $i=0; - while ($i < $num) - { - $array = $this->db->fetch_array($result); - if ($array["class"] == 'ot_total') - { - $this->total_ot_total = $array["value"]; - } - if ($array["class"] == 'ot_shipping') - { - $this->total_ot_shipping = $array["value"]; - } - $i++; - } - } - else - { - print $this->db->error(); - } - - } - else - { - print $this->db->error(); - } - - return $result; - } - -} diff --git a/htdocs/boutique/commande/fiche.php b/htdocs/boutique/commande/fiche.php deleted file mode 100644 index 1e2e90dd41c..00000000000 --- a/htdocs/boutique/commande/fiche.php +++ /dev/null @@ -1,155 +0,0 @@ - - * Copyright (C) 2003-2005 Eric Seigne - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/commande/fiche.php - * \ingroup boutique - * \brief Page fiche commande OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; -include_once DOL_DOCUMENT_ROOT.'/boutique/commande/class/boutiquecommande.class.php'; - -$langs->load("products"); - -$id=GETPOST('id', 'int'); - -/* - * View - */ - -llxHeader(); - - -if ($id > 0) -{ - $commande = new BoutiqueCommande($db); - $result = $commande->fetch($id); - if ($result) - { - print '
'.$langs->trans("OrderCard").': '.$commande->id.'

'; - - print ''; - print ''; - print ''; - - print ''; - - print ""; - - print ""; - print ""; - print ""; - - print "
Date'.$commande->date.'
Client'.$commande->client_name.'
Paiement'.$commande->payment_method.'
".$langs->trans("Address")."".$langs->trans("Delivery")."".$langs->trans("Invoice")."
 ".$commande->delivery_adr->name."
".$commande->delivery_adr->street."
".$commande->delivery_adr->zip."
".$commande->delivery_adr->city."
".$commande->delivery_adr->country."
".$commande->billing_adr->name."
".$commande->billing_adr->street."
".$commande->billing_adr->zip."
".$commande->billing_adr->city."
".$commande->billing_adr->country."
"; - - print "
"; - - /* - * Produits - * - */ - $sql = "SELECT orders_id, products_id, products_model, products_name, products_price, final_price, products_quantity"; - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_products"; - $sql .= " WHERE orders_id = " . $commande->id; - //$commande->id; - // echo $sql; - $resql=$dbosc->query($sql); - if ($resql) - { - $num = $dbosc->num_rows($resql); - $i = 0; - print ''; - print ''; - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print '"; - - print '\n"; - print "\n"; - print "\n"; - - print "\n"; - $i++; - } - print "
'.$langs->trans("Products").''.$langs->trans("Number").''.$langs->trans("Price").'Prix final
'; - print 'Fiche livre'; - - print ''.$objp->products_name.''; - print "$objp->products_quantityrowid\">".price($objp->products_price)."rowid\">".price($objp->final_price)."
"; - $dbosc->free(); - } - else - { - print $dbosc->error(); - } - - /* - * - * - */ - print "
"; - - print ''; - print ""; - print ''; - print ''; - print "
Frais d\'expeditions'.price($commande->total_ot_shipping).' EUR
'.$langs->trans("Lastname").''.price($commande->total_ot_total).' EUR
"; - - - - } - else - { - print "Fetch failed"; - } -} -else -{ - print "Error"; -} - - -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - -print '
'; -print ''; -print ''; -print ''; -print ''; -print ''; -print '
-----

'; - - - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/commande/index.php b/htdocs/boutique/commande/index.php deleted file mode 100644 index cc683994565..00000000000 --- a/htdocs/boutique/commande/index.php +++ /dev/null @@ -1,92 +0,0 @@ - - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/commande/index.php - * \ingroup boutique - * \brief Page gestion commandes OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - - -llxHeader(); - -if ($sortfield == "") -{ - $sortfield="date_purchased"; -} -if ($sortorder == "") -{ - $sortorder="DESC"; -} - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des commandes", $page, "commande.php"); - - $sql = "SELECT o.orders_id, customers_id, customers_name, customers_company, customers_street_address, customers_suburb, customers_city, customers_postcode, customers_state, customers_country, customers_telephone, customers_email_address, customers_address_format_id, delivery_name, delivery_company, delivery_street_address, delivery_suburb, delivery_city, delivery_postcode, delivery_state, delivery_country, delivery_address_format_id, billing_name, billing_company, billing_street_address, billing_suburb, billing_city, billing_postcode, billing_state, billing_country, billing_address_format_id, payment_method, cc_type, cc_owner, cc_number, cc_expires, last_modified, date_purchased, orders_status, orders_date_finished, currency, currency_value, t.value"; - -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t"; -$sql .= " WHERE o.orders_id = t.orders_id AND t.class = 'ot_total'"; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print ""; - print ""; - print ""; - print ""; - print_liste_field_titre("Client","commande.php", "customers_name"); - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - - print ''; - print '\n"; - print ''; - print "\n"; - $i++; - } - print "
".$langs->trans("Ref")."".$langs->trans("Date")."'.$langs->trans("Total").'
Fiche '; - print $objp->orders_id .""; - print dol_print_date($dbosc->jdate($objp->date_purchased),'dayhour').''.$objp->customers_name."'.price($objp->value).'
"; - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/critiques/bestproduct.php b/htdocs/boutique/critiques/bestproduct.php deleted file mode 100644 index 1b7b9ff0669..00000000000 --- a/htdocs/boutique/critiques/bestproduct.php +++ /dev/null @@ -1,97 +0,0 @@ - - * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/critiques/bestproduct.php - * \ingroup boutique - * \brief Page affichage meilleures critiques OS Commerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") { - $sortfield="rat"; -} -if ($sortorder == "") { - $sortorder="DESC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - - -print_barre_liste("Liste des produits classes par critiques", $page, "bestproduct.php"); - -$sql = "SELECT sum(r.reviews_rating)/count(r.reviews_rating) as rat, r.products_id, p.products_model, p.products_quantity, p.products_status"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."reviews as r,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products as p "; -$sql .= " WHERE r.products_id = p.products_id"; -$sql .= " GROUP BY r.products_id, p.products_model, p.products_quantity, p.products_status"; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -print "

"; -print "'; -print ''; -print "\n"; - - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - - $var=True; - while ($i < $num) { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; - $i++; - } - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -print "
".$langs->trans("Ref"); -print 'Indice critiquesQuantite'; -print 'Status
'.$objp->products_model.''.$objp->rat."'.$objp->products_quantity."'.$objp->products_status."
"; - - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/critiques/class/critique.class.php b/htdocs/boutique/critiques/class/critique.class.php deleted file mode 100644 index cd3a72088ad..00000000000 --- a/htdocs/boutique/critiques/class/critique.class.php +++ /dev/null @@ -1,84 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/boutique/critiques/class/critique.class.php - * \ingroup osc - * \brief Fichier de la classe des critiques OSCommerce - */ - - -/** - * Classe permettant la gestion des critiques OSCommerce - */ -class Critique -{ - var $db; - - var $id; - var $nom; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } - - /** - * Load instance - * - * @param int $id Id to load - * @return int <0 if KO, >0 if OK - */ - function fetch ($id) - { - global $conf; - - $sql = "SELECT r.reviews_id, r.reviews_rating, d.reviews_text, p.products_name"; - - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."reviews as r, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."reviews_description as d"; - $sql .= " ,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as p"; - - $sql .= " WHERE r.reviews_id = d.reviews_id AND r.products_id=p.products_id"; - $sql .= " AND p.language_id = ".$conf->global->OSC_LANGUAGE_ID. " AND d.languages_id=".$conf->global->OSC_LANGUAGE_ID; - $sql .= " AND r.reviews_id=$id"; - - $result = $this->db->query($sql); - - if ( $result ) - { - $result = $this->db->fetch_array($result); - - $this->id = $result["reviews_id"]; - $this->product_name = stripslashes($result["products_name"]); - $this->text = stripslashes($result["reviews_text"]); - - $this->db->free($result); - } - else - { - print $this->db->lasterror(); - } - - return $result; - } - -} diff --git a/htdocs/boutique/critiques/fiche.php b/htdocs/boutique/critiques/fiche.php deleted file mode 100644 index a5ea716ed8c..00000000000 --- a/htdocs/boutique/critiques/fiche.php +++ /dev/null @@ -1,82 +0,0 @@ - - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/critiques/fiche.php - * \ingroup boutique - * \brief Page fiche critique OS Commerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - -$id=$_GET["id"]; - - - -llxHeader(); - -if ($id) -{ - - $critique = new Critique($dbosc); - $result = $critique->fetch($id); - - if ( $result ) - { - - print '

Fiche Critique

'; - - print ''; - print ""; - print ''; - - print ''; - print "
Produit'.$critique->product_name.'
Texte'.nl2br($critique->text).'
"; - - - - } - else - { - print "Fetch failed"; - } - -} - -/* ************************************************************************** */ -/* */ -/* Barre d'action */ -/* */ -/* ************************************************************************** */ - -print '
'; -print ''; -print ''; -print ''; -print ''; -print ''; -print '
-----

'; - - - -$dbosc->close(); - -llxFooter(); - diff --git a/htdocs/boutique/critiques/index.php b/htdocs/boutique/critiques/index.php deleted file mode 100644 index 98294d5d09c..00000000000 --- a/htdocs/boutique/critiques/index.php +++ /dev/null @@ -1,92 +0,0 @@ - - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/critiques/index.php - * \ingroup boutique - * \brief Page gestion critiques OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") { - $sortfield="date_added"; -} -if ($sortorder == "") { - $sortorder="DESC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Critiques", $page, "index.php"); - -$sql = "SELECT r.reviews_id, r.reviews_rating, d.reviews_text, p.products_name FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."reviews as r, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."reviews_description as d, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as p"; -$sql .= " WHERE r.reviews_id = d.reviews_id AND r.products_id=p.products_id"; -$sql .= " AND p.language_id = ".$conf->global->OSC_LANGUAGE_ID. " AND d.languages_id=".$conf->global->OSC_LANGUAGE_ID; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -print "

"; -print ''; -print ""; -print ""; -print ""; -print ""; -print "\n"; - -$resql=$dbosc->query($sql); -if ($resql) { - $num = $dbosc->num_rows($resql); - $i = 0; - - $var=True; - while ($i < $num) { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print "\n"; - print '\n"; - print "\n"; - print "\n"; - $i++; - } - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -print "
ProduitCritiqueNote
".substr($objp->products_name, 0, 30)."'.substr($objp->reviews_text, 0, 40)." ...$objp->reviews_rating
"; - - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/index.php b/htdocs/boutique/index.php deleted file mode 100644 index 040e81b726a..00000000000 --- a/htdocs/boutique/index.php +++ /dev/null @@ -1,240 +0,0 @@ - - * Copyright (C) 2004-2007 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/boutique/index.php - * \ingroup boutique - * \brief Main page of shop zone - */ - -require '../main.inc.php'; - -$langs->load("shop"); -$langs->load("orders"); - -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - -llxHeader("",$langs->trans("OSCommerceShop"),""); - -print_fiche_titre($langs->trans("OSCommerceShop")); - -print ''; - -print ''; -/* - * Last customers who commanded - */ -$sql = "SELECT o.orders_id, o.customers_name, o.delivery_country, o.date_purchased, t.value, s.orders_status_name as statut"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o on o.orders_id = t.orders_id "; -$sql .= " JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_status as s on o.orders_status = s.orders_status_id and s.language_id = 1"; -$sql .= " WHERE t.class = 'ot_subtotal' order by o.date_purchased desc"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $langs->load("orders"); - $num = $dbosc->num_rows($resql); - if ($num > 0) - { - $i = 0; - print '
'; - - -/* - * Turnover - */ -print_titre($langs->trans('SalesTurnover')); - -print ''; -print ''; -print ''; - -$now=dol_now(); - -$sql = "SELECT sum(t.value) as value, MONTH(o.date_purchased) as mois"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t"; -$sql .= " JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o ON o.orders_id = t.orders_id"; -$sql .= " WHERE t.class = 'ot_subtotal' AND YEAR(o.date_purchased) = YEAR(".$dbosc->idate($now).")"; -$sql .= " GROUP BY mois ORDER BY mois"; - -$result=$dbosc->query($sql); -if ($result) -{ - $num = $dbosc->num_rows($result); - - $var=True; - $i=0; - if ($num > 0) - { - while ($i < $num) - { - $objp = $dbosc->fetch_object($result); - $var=!$var; - print ""; - print ''; - print ''; - - print "\n"; - $i++; - } - } - - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - - -print "
'.$langs->trans("Description").''.$langs->trans("Total").'
'.$objp->mois.''.price($objp->value).'
"; -print '
'; -print_titre($langs->trans("Orders")); - -/* - * Last 5 successful commands - select o.orders_id, o.customers_id, o.customers_name, o.date_purchased, o.payement_method, o.status, t.value - from orders_total as t - join orders as o on o.orders_id = t.orders_id where t.class = 'ot_subtotal' order by o.date_purchased desc - */ -$sql = "SELECT o.orders_id, o.customers_name, o.date_purchased, t.value, o.payment_method"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o on o.orders_id = t.orders_id "; -$sql .= " WHERE t.class = 'ot_subtotal' ORDER BY o.date_purchased desc"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $langs->load("orders"); - $num = $dbosc->num_rows($resql); - if ($num > 0) - { - $i = 0; - print ''; - print ''; - print ''; - - $num = min($num,OSC_MAXNBCOM); - while ($i < $num) - { - - $obj = $dbosc->fetch_object($resql); - print ""; - $i++; - } - print "
'.$langs->trans("LastOrders").'
$obj->orders_id$obj->customers_name".price($obj->value)."$obj->payment_method

"; - } -} -else -{ - dol_print_error($dbosc); -} - -/* - * Last 5 commands in wait - */ -$sql = "SELECT o.orders_id, o.customers_name, o.date_purchased, t.value, o.payment_method"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o on o.orders_id = t.orders_id "; -$sql .= " WHERE t.class = 'ot_subtotal' and o.orders_status = 5 order by o.date_purchased desc"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $langs->load("orders"); - $num = $dbosc->num_rows($resql); - if ($num > 0) - { - $i = 0; - print ''; - print ''; - print ''; - - $num = min($num,OSC_MAXNBCOM); - while ($i < $num) - { - - $obj = $dbosc->fetch_object($resql); - print ""; - $i++; - } - print "
'.$langs->trans("En Attente").'
$obj->orders_id$obj->customers_name".price($obj->value)."$obj->payment_method

"; - } -} -else -{ - dol_print_error($dbosc); -} - -/* - * Commands to treat - */ -$sql = "SELECT o.orders_id, o.customers_name, o.date_purchased, t.value, o.payment_method"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders_total as t JOIN ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."orders as o on o.orders_id = t.orders_id "; -$sql .= " WHERE t.class = 'ot_subtotal' and o.orders_status = 2 order by o.date_purchased desc"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $langs->load("orders"); - $num = $dbosc->num_rows($resql); - if ($num > 0) - { - $i = 0; - print ''; - print ''; - print ''; - - $num = min($num,OSC_MAXNBCOM); - while ($i < $num) - { - - $obj = $dbosc->fetch_object($resql); - print ""; - $i++; - } - print "
'.$langs->trans("TreatmentInProgress").'
$obj->orders_id$obj->customers_name".price($obj->value)."$obj->payment_method

"; - } -} -else -{ - dol_print_error($dbosc); -} - - -print '
'; - print ''; - print ''; - - $num = min($num,OSC_MAXNBCOM); - while ($i < $num) - { - $obj = $dbosc->fetch_object($resql); - print ""; - $i++; - } - print "
'.$langs->trans("Derniers clients").'
$obj->date_purchased$obj->customers_name$obj->delivery_country".price($obj->value)."$obj->payment_method$obj->orders_id$obj->statut

"; - } -} -else -{ - dol_print_error($dbosc); -} -print ''; - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/notification/index.php b/htdocs/boutique/notification/index.php deleted file mode 100644 index f8a24c5a52c..00000000000 --- a/htdocs/boutique/notification/index.php +++ /dev/null @@ -1,89 +0,0 @@ - - * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/notification/index.php - * \ingroup boutique - * \brief Page gestion notification OS Commerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - -$langs->load("products"); - - - -llxHeader(); - -if ($sortfield == "") { - $sortfield="lower(c.customers_lastname)"; -} -if ($sortorder == "") { - $sortorder="ASC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des notifications", $page, "index.php"); - -$sql = "SELECT c.customers_id, c.customers_lastname, c.customers_firstname, p.products_name, p.products_id"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_notifications as n,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as p"; -$sql .= ",".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."customers as c"; -$sql .= " WHERE n.customers_id = c.customers_id AND p.products_id=n.products_id"; -$sql .= " AND p.language_id = ".$conf->global->OSC_LANGUAGE_ID; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print ""; - print ""; - print_liste_field_titre("Client","index.php", "c.customers_lastname"); - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print "\n"; - print '"; - print "\n"; - $i++; - } - print "
'.$langs->trans("Product").'
rowid\">$objp->customers_firstname $objp->customers_lastname'.$objp->products_name."
"; - $dbosc->free($resql); -} -else -{ - dol_print_error($dbosc); -} - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/notification/produits.php b/htdocs/boutique/notification/produits.php deleted file mode 100644 index 6b4b82b60f5..00000000000 --- a/htdocs/boutique/notification/produits.php +++ /dev/null @@ -1,95 +0,0 @@ - - * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/notification/produits.php - * \ingroup boutique - * \brief Page fiche notification produits OS Commerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") { - $sortfield="lower(p.products_name)"; -} -if ($sortorder == "") { - $sortorder="ASC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des produits suivis", $page, "produits.php"); - -$sql = "SELECT p.products_name, p.products_id, count(p.products_id) as nb"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_notifications as n,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as p"; -$sql .= " WHERE p.products_id=n.products_id"; -$sql .= " AND p.language_id = ".$conf->global->OSC_LANGUAGE_ID; -$sql .= " GROUP BY p.products_name, p.products_id"; -$sql .= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print "

"; - print ""; - print ''; - print ""; - print ""; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - - print '"; - print ''; - - print ''; - print ''; - - print "\n"; - $i++; - } - print "
ProduitNb.
'.$objp->products_name."'.$objp->nb.'Voir les clientsEnvoyer une news
"; - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/osc_master.inc.php b/htdocs/boutique/osc_master.inc.php deleted file mode 100644 index 057c15f30e1..00000000000 --- a/htdocs/boutique/osc_master.inc.php +++ /dev/null @@ -1,38 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/boutique/osc_master.inc.php - * \brief File of preparation of the environment Dolibarr for OSCommerce - */ - - -/* - * Creation objet $dbosc - */ -$dbosc=getDoliDBInstance($conf->db->type,$conf->global->OSC_DB_HOST,$conf->global->OSC_DB_USER,$conf->global->OSC_DB_PASS,$conf->global->OSC_DB_NAME,$conf->global->OSC_DB_PORT); - -if (! $dbosc->connected) -{ - dol_syslog($dbosc,"host=".$conf->global->OSC_DB_HOST.", user=".$conf->global->OSC_DB_USER.", databasename=".$conf->global->OSC_DB_NAME.", ".$db->error,LOG_ERR); - - llxHeader("",$langs->trans("OSCommerceShop"),""); - print '

'.$langs->trans('FailedConnectDBCheckModuleSetup').'
'; - llxFooter(); - exit; -} - diff --git a/htdocs/boutique/produits/index.php b/htdocs/boutique/produits/index.php deleted file mode 100644 index 02db7d5db2b..00000000000 --- a/htdocs/boutique/produits/index.php +++ /dev/null @@ -1,88 +0,0 @@ - - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/produits/index.php - * \ingroup boutique - * \brief Page gestion produits du module OsCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - -$langs->load("companies"); - - - -llxHeader(); - -if ($sortfield == "") { - $sortfield="lower(c.customers_lastname)"; -} -if ($sortorder == "") { - $sortorder="ASC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des clients", $page, "index.php"); - -$sql = "SELECT c.customers_id, c.customers_lastname, c.customers_firstname, c.customers_email_address, c.customers_newsletter"; -$sql .= " FROM ".DB_NAME_OSC.".customers as c"; -$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print ""; - print ""; - print_liste_field_titre($langs->trans("Firstname"),"index.php", "c.customers_firstname"); - print_liste_field_titre($langs->trans("Lastname"),"index.php", "c.customers_lastname"); - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print '\n"; - print '\n"; - print "\n"; - print "\n"; - print "\n"; - $i++; - } - print "
'.$langs->trans("EMail").''.$langs->trans("Newsletter").'
'.$objp->customers_firstname."'.$objp->customers_lastname."$objp->customers_email_address$objp->customers_newsletter
"; - $dbosc->free($resql); -} -else -{ - dol_print_error($dbosc); -} - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/produits/osc-liste.php b/htdocs/boutique/produits/osc-liste.php deleted file mode 100644 index d8888505254..00000000000 --- a/htdocs/boutique/produits/osc-liste.php +++ /dev/null @@ -1,106 +0,0 @@ - - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/produits/osc-liste.php - * \ingroup boutique - * \brief Page gestion produits du module OsCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -/* - * View - */ - -llxHeader(); - -if ($sortfield == "") { - $sortfield="p.label,p.price"; -} -if ($sortorder == "") { - $sortorder="ASC"; -} - - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - - -print_barre_liste("Liste des produits oscommerce", $page, "osc-liste.php"); - -$sql = "SELECT p.products_id, p.products_model, p.products_quantity, p.products_status, d.products_name, m.manufacturers_name, m.manufacturers_id"; -$sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products as p, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as d, ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."manufacturers as m"; -$sql .= " WHERE p.products_id = d.products_id AND d.language_id =" . $conf->global->OSC_LANGUAGE_ID; -$sql .= " AND p.manufacturers_id=m.manufacturers_id"; -if ($reqstock=='epuise') -{ - $sql .= " AND p.products_quantity <= 0"; -} - -//$sql .= " ORDER BY $sortfield $sortorder "; -$sql .= $dbosc->plimit($limit,$offset); - -print "

"; -print ''; -print ""; -print ""; -print ""; -print ""; -print ''; -print ''; -print ''."\n"; - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($resql); - $var=!$var; - print ""; - print "\n"; - print "\n"; - print "\n"; - print "\n"; - print '\n"; - print '\n"; - print "\n"; - $i++; - } - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} - -print "
idRefTitreGroupeStockStatus
$objp->products_id$objp->products_model$objp->products_name$objp->manufacturers_name'.$objp->products_quantity."'.$objp->products_status."
"; - - -$dbosc->close(); - -llxFooter(); diff --git a/htdocs/boutique/promotion/class/promotion.class.php b/htdocs/boutique/promotion/class/promotion.class.php deleted file mode 100644 index 6e965ad76d1..00000000000 --- a/htdocs/boutique/promotion/class/promotion.class.php +++ /dev/null @@ -1,213 +0,0 @@ - - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/boutique/promotion/class/promotion.class.php - * \brief File of class to manage discounts on online shop - */ - -/** - * \class Promotion - * \brief Class to manage discounts on online shop - */ -class Promotion -{ - var $db; - - var $id; - var $parent_id; - var $oscid; - var $ref; - var $titre; - var $description; - var $price; - var $status; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - } - - /** - * Create promotion - * - * @param User $user Object user - * @param int $pid Pid - * @param int $percent Percent - * @return int <0 if KO, >0 if OK - */ - function create($user, $pid, $percent) - { - global $conf; - - $sql = "SELECT products_price "; - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products as p"; - $sql .= " WHERE p.products_id = ".$pid; - - $result = $this->db->query($sql); - if ( $result ) - { - $result = $this->db->fetch_array($result); - $this->price_init = $result["products_price"]; - } - - $newprice = $percent * $this->price_init; - - $date_exp = "2003-05-01"; // TODO ???? - - $now=dol_now(); - - $sql = "INSERT INTO ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."specials "; - $sql .= " (products_id, specials_new_products_price, specials_date_added, specials_last_modified, expires_date, date_status_change, status) "; - $sql .= " VALUES ($pid, $newprice, '".$this->db->idate($now)."', NULL, '".$this->db->idate($now+3600*24*365)."', NULL, 1)"; - - if ($this->db->query($sql) ) - { - $id = $this->db->last_insert_id(OSC_DB_NAME.".specials"); - - return $id; - } - else - { - print $this->db->error() . ' in ' . $sql; - } - } - - /** - * Update - * - * @param int $id id - * @param User $user Object user - * @return int <0 if KO, >0 if OK - */ - function update($id, $user) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."album "; - $sql .= " SET title = '" . trim($this->titre) ."'"; - $sql .= ",description = '" . trim($this->description) ."'"; - - $sql .= " WHERE rowid = " . $id; - - if ( $this->db->query($sql) ) { - return 1; - } else { - print $this->db->error() . ' in ' . $sql; - } - } - - /** - * Set active - * - * @param int $id id - * @return int <0 if KO, >0 if OK - */ - function set_active($id) - { - global $conf; - - $sql = "UPDATE ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."specials"; - $sql .= " SET status = 1"; - - $sql .= " WHERE products_id = " . $id; - - if ( $this->db->query($sql) ) { - return 1; - } else { - print $this->db->error() . ' in ' . $sql; - } - } - - /** - * Set inactive - * - * @param int $id id - * @return int <0 if KO, >0 if OK - */ - function set_inactive($id) - { - global $conf; - - $sql = "UPDATE ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."specials"; - $sql .= " SET status = 0"; - - $sql .= " WHERE products_id = " . $id; - - if ( $this->db->query($sql) ) { - return 1; - } else { - print $this->db->error() . ' in ' . $sql; - } - } - - /** - * Fetch datas - * - * @param int $id id - * @return int <0 if KO, >0 if OK - */ - function fetch($id) - { - global $conf; - - $sql = "SELECT c.categories_id, cd.categories_name, c.parent_id"; - $sql .= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."categories as c,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."categories_description as cd"; - $sql .= " WHERE c.categories_id = cd.categories_id AND cd.language_id = ".$conf->global->OSC_LANGUAGE_ID; - $sql .= " AND c.categories_id = ".$id; - $result = $this->db->query($sql); - - if ( $result ) { - $result = $this->db->fetch_array($result); - - $this->id = $result["categories_id"]; - $this->parent_id = $result["parent_id"]; - $this->name = $result["categories_name"]; - $this->titre = $result["title"]; - $this->description = $result["description"]; - $this->oscid = $result["osc_id"]; - } - $this->db->free($result); - - return $result; - } - - - /** - * Delete object - * - * @param User $user Object user - * @return int <0 if KO, >0 if OK - */ - function delete($user) - { - global $conf; - - $sql = "DELETE FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products WHERE products_id = $idosc "; - - $sql = "DELETE FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_to_categories WHERE products_id = $idosc"; - - $sql = "DELETE FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description WHERE products_id = $idosc"; - - } - - -} diff --git a/htdocs/boutique/promotion/index.php b/htdocs/boutique/promotion/index.php deleted file mode 100644 index 10dfa09a8c1..00000000000 --- a/htdocs/boutique/promotion/index.php +++ /dev/null @@ -1,119 +0,0 @@ - - * Copyright (C) 2004-2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/boutique/promotion/index.php - * \ingroup boutique - * \brief Page gestion promotions OSCommerce - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/boutique/osc_master.inc.php'; - - -llxHeader(); - -if ($action == "inactive") -{ - $promotion = new Promotion($dbosc); - $promotion->set_inactive($id); -} -if ($action == "active") -{ - $promotion = new Promotion($dbosc); - $promotion->set_active($id); -} - -if ($sortfield == "") -{ - $sortfield="pd.products_name"; -} -if ($sortorder == "") -{ - $sortorder="ASC"; -} - -if ($page == -1) { $page = 0 ; } -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -print_barre_liste("Liste des promotions", $page, "index.php", "",$sortfield, $sortorder); - -$urladd = "&sortorder=$sortorder&sortfield=$sortfield"; - -$sql = "SELECT pd.products_name, s.specials_new_products_price, p.products_price, p.products_model, s.status, p.products_id,"; -$sql.= " expires_date as fin"; -$sql.= " FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."specials as s,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products_description as pd,".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."products as p"; -$sql.= " WHERE s.products_id = pd.products_id AND pd.products_id = p.products_id AND pd.language_id = ".$conf->global->OSC_LANGUAGE_ID; -$sql.= " ORDER BY $sortfield $sortorder "; -$sql.= $dbosc->plimit($limit,$offset); - -$resql=$dbosc->query($sql); -if ($resql) -{ - $num = $dbosc->num_rows($resql); - $i = 0; - print ''; - print ""; - print_liste_field_titre($langs->trans("Ref"),"index.php", "p.products_model"); - print_liste_field_titre("Titre","index.php", "pd.products_name"); - print ""; - print ''; - print ''; - print "\n"; - $var=True; - while ($i < $num) - { - $objp = $dbosc->fetch_object($i); - $var=!$var; - - print ""; - print '"; - print '"; - - if ($objp->status == 1) - { - print ''; - print ''; - } - else - { - print ''; - print ''; - } - print ""; - print '"; - print '"; - print ""; - $i++; - } - print "
  FinPrix initialPrix remise
'.$objp->products_model."'.$objp->products_name."actif'; - print ''; - print ''; - print ''; - print 'inactif".dol_print_date($dbosc->jdate($objp->fin),'day')."'.price($objp->products_price)."'.price($objp->specials_new_products_price)."
"; - $dbosc->free(); -} -else -{ - dol_print_error($dbosc); -} -$dbosc->close(); - -llxFooter(); - diff --git a/htdocs/cache.manifest b/htdocs/cache.manifest index 34782a02141..e46443bb86b 100644 --- a/htdocs/cache.manifest +++ b/htdocs/cache.manifest @@ -13,7 +13,6 @@ support/ support/index.php support/online.php -support/background.png support/default.css support/dolibarr_logo2.png support/headbg.jpg diff --git a/htdocs/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php index 692b055659b..1ddde37b98b 100644 --- a/htdocs/cashdesk/admin/cashdesk.php +++ b/htdocs/cashdesk/admin/cashdesk.php @@ -50,14 +50,13 @@ if (GETPOST('action','alpha') == 'set') $db->begin(); if (GETPOST('socid','int') < 0) $_POST["socid"]=''; - /*if (GETPOST("CASHDESK_ID_BANKACCOUNT") < 0) $_POST["CASHDESK_ID_BANKACCOUNT"]=''; - if (GETPOST("CASHDESK_ID_WAREHOUSE") < 0) $_POST["CASHDESK_ID_WAREHOUSE"]='';*/ - $res = dolibarr_set_const($db,"CASHDESK_ID_THIRDPARTY",GETPOST('socid','int'),'chaine',0,'',$conf->entity); - $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CASH",GETPOST('CASHDESK_ID_BANKACCOUNT_CASH','alpha'),'chaine',0,'',$conf->entity); - $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CHEQUE",GETPOST('CASHDESK_ID_BANKACCOUNT_CHEQUE','alpha'),'chaine',0,'',$conf->entity); - $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CB",GETPOST('CASHDESK_ID_BANKACCOUNT_CB','alpha'),'chaine',0,'',$conf->entity); - $res = dolibarr_set_const($db,"CASHDESK_ID_WAREHOUSE",GETPOST('CASHDESK_ID_WAREHOUSE','alpha'),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_ID_THIRDPARTY",(GETPOST('socid','int') > 0 ? GETPOST('socid','int') : ''),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CASH",(GETPOST('CASHDESK_ID_BANKACCOUNT_CASH','alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH','alpha') : ''),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CHEQUE",(GETPOST('CASHDESK_ID_BANKACCOUNT_CHEQUE','alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CHEQUE','alpha') : ''),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CB",(GETPOST('CASHDESK_ID_BANKACCOUNT_CB','alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CB','alpha') : ''),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_ID_WAREHOUSE",(GETPOST('CASHDESK_ID_WAREHOUSE','alpha') > 0 ? GETPOST('CASHDESK_ID_WAREHOUSE','alpha') : ''),'chaine',0,'',$conf->entity); + $res = dolibarr_set_const($db,"CASHDESK_NO_DECREASE_STOCK",GETPOST('CASHDESK_NO_DECREASE_STOCK','alpha'),'chaine',0,'',$conf->entity); $res = dolibarr_set_const($db,"CASHDESK_SERVICES", GETPOST('CASHDESK_SERVICES','alpha'),'chaine',0,'',$conf->entity); dol_syslog("admin/cashdesk: level ".GETPOST('level','alpha')); @@ -67,12 +66,12 @@ if (GETPOST('action','alpha') == 'set') if (! $error) { $db->commit(); - $mesg = "".$langs->trans("SetupSaved").""; + setEventMessage($langs->trans("SetupSaved")); } else { $db->rollback(); - $mesg = "".$langs->trans("Error").""; + setEventMessage($langs->trans("Error"), 'errors'); } } @@ -129,9 +128,25 @@ if (! empty($conf->banque->enabled)) if (! empty($conf->stock->enabled)) { $var=!$var; - print ''.$langs->trans("CashDeskIdWareHouse").''; + print ''.$langs->trans("CashDeskDoNotDecreaseStock").''; // Force warehouse (this is not a default value) print ''; - print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE,'CASHDESK_ID_WAREHOUSE','',1); + print $form->selectyesno('CASHDESK_NO_DECREASE_STOCK',$conf->global->CASHDESK_NO_DECREASE_STOCK,1); + print ''; + + $disabled=$conf->global->CASHDESK_NO_DECREASE_STOCK; + + $var=!$var; + print ''.$langs->trans("CashDeskIdWareHouse").''; // Force warehouse (this is not a default value) + print ''; + if (! $disabled) + { + print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE,'CASHDESK_ID_WAREHOUSE','',1,$disabled); + print ' ('.$langs->trans("Create").')'; + } + else + { + print $langs->trans("StockDecreaseForPointOfSaleDisabled"); + } print ''; } @@ -152,8 +167,6 @@ print '

\n"; -dol_htmloutput_mesg($mesg); - $db->close(); llxFooter(); diff --git a/htdocs/cashdesk/admin/index.html b/htdocs/cashdesk/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/affContenu.php b/htdocs/cashdesk/affContenu.php index 543006baedf..6d8f5ca83ee 100644 --- a/htdocs/cashdesk/affContenu.php +++ b/htdocs/cashdesk/affContenu.php @@ -43,15 +43,19 @@ else $obj_facturation = new Facturation(); } -print '
'; -require ('tpl/liste_articles.tpl.php'); -$obj_facturation->prixTotalHt($lst_total_ht); -$obj_facturation->prixTotalTtc($lst_total_ttc); +$obj_facturation->calculTotaux(); // Redefine prix_total_ttc, prix_total_ht et montant_tva from $_SESSION['poscart'] -print '
'; +$total_ttc = $obj_facturation->prixTotalTtc(); +/*var_dump($obj_facturation); +var_dump($_SESSION['poscart']); +var_dump($total_ttc); +exit;*/ + + +// Left area with selected articles (area for article, amount and payments) print '
'; $page=GETPOST('menu','alpha'); @@ -75,4 +79,15 @@ else print '
'; + + + +// Right area with selected articles (shopping cart) +print '
'; + +require ('tpl/liste_articles.tpl.php'); + +print '
'; + + $_SESSION['serObjFacturation'] = serialize($obj_facturation); diff --git a/htdocs/cashdesk/affIndex.php b/htdocs/cashdesk/affIndex.php index 5a713eed4d9..6ac2915a9d1 100644 --- a/htdocs/cashdesk/affIndex.php +++ b/htdocs/cashdesk/affIndex.php @@ -25,6 +25,7 @@ */ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/environnement.php'; +require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/keypad.php'; // Test if already logged if ( $_SESSION['uid'] <= 0 ) diff --git a/htdocs/cashdesk/class/Facturation.class.php b/htdocs/cashdesk/class/Facturation.class.php index b2bb87a0bb2..296ced0f172 100644 --- a/htdocs/cashdesk/class/Facturation.class.php +++ b/htdocs/cashdesk/class/Facturation.class.php @@ -103,7 +103,7 @@ class Facturation $sql.= " FROM ".MAIN_DB_PREFIX."c_tva"; $sql.= " WHERE rowid = ".$this->tva(); - dol_syslog("ajoutArticle sql=".$sql); + dol_syslog("ajoutArticle", LOG_DEBUG); $resql = $db->query($sql); if ($resql) diff --git a/htdocs/cashdesk/class/index.html b/htdocs/cashdesk/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/class/index.php b/htdocs/cashdesk/class/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/cashdesk/class/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/cashdesk/css/index.html b/htdocs/cashdesk/css/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/css/style.css b/htdocs/cashdesk/css/style.css index 578d8fed6a2..f62a9193830 100644 --- a/htdocs/cashdesk/css/style.css +++ b/htdocs/cashdesk/css/style.css @@ -30,23 +30,24 @@ p { .conteneur { background: #fff; text-align: left; - width: 770px; + max-width: 770px; margin: 10px auto; + border: 2px solid #000; } .conteneur_img_gauche { - background: url("../img/bg_conteneur_gauche.png") top left repeat-y; + /* background: url("../img/bg_conteneur_gauche.png") top left repeat-y; */ } .conteneur_img_droite { - background: url("../img/bg_conteneur_droite.png") top right repeat-y; + /* background: url("../img/bg_conteneur_droite.png") top right repeat-y; */ } /* ------------------- Header ------------------- */ .entete { height: 15px; margin: 0; - background: url('../img/bg_entete.png') no-repeat left top; + /* background: url('../img/bg_entete.png') no-repeat left top; */ } .entete span { @@ -57,7 +58,6 @@ p { .menu_principal { margin: 0 20px 20px 15px; font-size: 14px; - width: 735px; height: 84px; background: #CCCCCC; background-image: linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(40,40,40,.3) 100%); @@ -80,20 +80,21 @@ p { .menu li { float: left; + padding-right: 10px; } .menu_choix1,.menu_choix2 { font-size: 1.4em; text-align: left; - width: 180px; } .menu_choix1 a,.menu_choix2 a { display: block; color: #fff; text-decoration: none; - width: 100px; + padding-top: 18px; padding-left: 54px; + font-size: 14px; height: 48px; background: url('../img/new.png') top left no-repeat; } @@ -115,7 +116,6 @@ p { text-align: right; font-style: italic; font-weight: normal; - width: 340px; display: block; color: #333; text-decoration: none; @@ -126,11 +126,13 @@ p { font-weight: normal; text-decoration: none; } - +li.menu_choix0 { + float: right; +} /* ------------------- R�capitulatif des articles ------------------- */ .liste_articles { - width: 215px; + min-width: 215px; float: right; margin-top: 8px; margin-right: 20px; @@ -215,16 +217,12 @@ p.titre { border: 1px solid #6d3f6d; } -.bouton_login input { - background: #fff; - border: 1px solid #6d3f6d; -} - .principal { float: left; margin: 0 15px; padding: 0; - width: 495px; + max-width: 500px; + width: 100%; } .titre1 { @@ -242,7 +240,6 @@ p.titre { .cadre_facturation { border: 2px solid #ddd; margin-bottom: 15px; - padding: 10px 10px; } .principal p { @@ -312,7 +309,7 @@ p.titre { } .texte_ref { - width: 80px; + min-width: 150px; } .texte1,.texte1_off { @@ -325,35 +322,12 @@ p.titre { /* ------------------- */ .textarea_note { - width: 300px; - height: 150px; + width: 100%; + height: 50px; padding: 2px 2px; } /* -------------- Boutons --------------------- */ -.bouton_ajout_article,.bouton_mode_reglement,.bouton_validation { - border: 1px solid #999; - background: #f7f7f7; - -background-image: linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -o-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -moz-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -webkit-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -ms-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, rgba(255,255,255,.3)), color-stop(1, rgba(80,80,80,.3)) ); -} - -.bouton_ajout_article:hover,.bouton_mode_reglement:hover,.bouton_validation:hover -{ - background: #cccccc; -background-image: linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -o-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -moz-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -webkit-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -ms-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(80,80,80,.3) 100%); -background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, rgba(255,255,255,.3)), color-stop(1, rgba(80,80,80,.3)) ); -} - .bouton_ajout_article { margin-top: 10px; width: 100%; @@ -389,7 +363,7 @@ background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, } .resume_label,.note_label { - width: 200px; + min-width: 200px; font-weight: bold; font-size: 1.1em; } @@ -402,7 +376,7 @@ background-image: -webkit-gradient( linear, left top, left bottom, color-stop(0, .pied { clear: both; height: 15px; - background: url('../img/bg_pied.png') no-repeat bottom left; + /* background: url('../img/bg_pied.png') no-repeat bottom left; */ } /* ------------------- Param�tres communs (messages d'erreur, informations, etc...) ------------------- */ diff --git a/htdocs/cashdesk/facturation.php b/htdocs/cashdesk/facturation.php index 32411f627fb..dd722805eb6 100644 --- a/htdocs/cashdesk/facturation.php +++ b/htdocs/cashdesk/facturation.php @@ -65,7 +65,7 @@ if ( GETPOST('filtre') ) { else $sql.= ")"; $sql.= " ORDER BY label"; - dol_syslog("facturation.php sql=".$sql); + dol_syslog("facturation.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -156,11 +156,11 @@ $i=0; $sql = "SELECT t.rowid, t.taux"; $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t"; -$sql.= ", ".MAIN_DB_PREFIX."c_pays as p"; -$sql.= " WHERE t.fk_pays = p.rowid"; +$sql.= ", ".MAIN_DB_PREFIX."c_country as c"; +$sql.= " WHERE t.fk_pays = c.rowid"; $sql.= " AND t.active = 1"; -$sql.= " AND p.code = '".$mysoc->country_code."'"; -//print $request; +$sql.= " AND c.code = '".$mysoc->country_code."'"; +//print $sql; $resql = $db->query($sql); if ($resql) diff --git a/htdocs/cashdesk/facturation_dhtml.php b/htdocs/cashdesk/facturation_dhtml.php index 88a22f7865a..e481fcbecf6 100644 --- a/htdocs/cashdesk/facturation_dhtml.php +++ b/htdocs/cashdesk/facturation_dhtml.php @@ -62,7 +62,7 @@ if (dol_strlen($_GET["code"]) >= 0) // If search criteria is on char length at l } $sql.= " ORDER BY label"; - dol_syslog("facturation_dhtml.php sql=".$sql); + dol_syslog("facturation_dhtml.php", LOG_DEBUG); $result = $db->query($sql); if ($result) diff --git a/htdocs/cashdesk/facturation_verif.php b/htdocs/cashdesk/facturation_verif.php index 42e1c00f651..8953f7b0ccc 100644 --- a/htdocs/cashdesk/facturation_verif.php +++ b/htdocs/cashdesk/facturation_verif.php @@ -137,16 +137,17 @@ switch ( $_GET['action'] ) case 'ajout_article': // We have clicked on button "Add product" - //var_dump($obj_facturation); + //var_dump('ajout_article'); //exit; - if (! empty($obj_facturation->id)) // A product has been selected and stored in session + if (! empty($obj_facturation->id)) // A product was previously selected and stored in session, so we can add it { $obj_facturation->qte($_POST['txtQte']); $obj_facturation->tva($_POST['selTva']); $obj_facturation->remisePercent($_POST['txtRemise']); - $obj_facturation->ajoutArticle(); - + $obj_facturation->ajoutArticle(); // This add an entry into $_SESSION['poscart'] + // We update prixTotalTtc + } $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menu=facturation'; @@ -160,7 +161,7 @@ switch ( $_GET['action'] ) } - +// We saved object obj_facturation $_SESSION['serObjFacturation'] = serialize($obj_facturation); header('Location: '.$redirection); diff --git a/htdocs/cashdesk/img/index.html b/htdocs/cashdesk/img/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/img/index.php b/htdocs/cashdesk/img/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/cashdesk/img/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/cashdesk/include/environnement.php b/htdocs/cashdesk/include/environnement.php index f0545181ff0..3e6a88f252a 100644 --- a/htdocs/cashdesk/include/environnement.php +++ b/htdocs/cashdesk/include/environnement.php @@ -32,6 +32,7 @@ $conf_db_base = $dolibarr_main_db_name; $conf_fksoc = (! empty($_SESSION["CASHDESK_ID_THIRDPARTY"]))?$_SESSION["CASHDESK_ID_THIRDPARTY"]:($conf->global->CASHDESK_ID_THIRDPARTY>0?$conf->global->CASHDESK_ID_THIRDPARTY:0); // Identifiant unique correspondant a l'entrepot a utiliser $conf_fkentrepot = (! empty($_SESSION["CASHDESK_ID_WAREHOUSE"]))?$_SESSION["CASHDESK_ID_WAREHOUSE"]:($conf->global->CASHDESK_ID_WAREHOUSE>0?$conf->global->CASHDESK_ID_WAREHOUSE:0); +if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $conf_fkentrepot = 0; // If option to disable stock decrease is on, we set warehouse id to 0. // Identifiant unique correspondant au compte caisse / liquide $conf_fkaccount_cash = (! empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]))?$_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]:($conf->global->CASHDESK_ID_BANKACCOUNT_CASH>0?$conf->global->CASHDESK_ID_BANKACCOUNT_CASH:0); diff --git a/htdocs/cashdesk/include/index.html b/htdocs/cashdesk/include/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/include/index.php b/htdocs/cashdesk/include/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/cashdesk/include/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/cashdesk/include/keypad.php b/htdocs/cashdesk/include/keypad.php new file mode 100644 index 00000000000..7560180396a --- /dev/null +++ b/htdocs/cashdesk/include/keypad.php @@ -0,0 +1,54 @@ + + * + * 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 . + */ + +/** + * Return a string to output a keypad + * + * @param string $keypadname Key pad name + * @param string $formname Form name + * @return string HTML code to show a js keypad. + */ +function genkeypad($keypadname, $formname) +{ + global $conf; + + if (empty($conf->global->CASHDESK_SHOW_KEYPAD)) return ''; + + // défine the font size of button + $btnsize=32; + $sz=''."\n"; + $sz.='
'."\n"; + $sz.=''; + return $sz; +} diff --git a/htdocs/cashdesk/index.php b/htdocs/cashdesk/index.php index 8ea6063a5e4..fa1c6723d20 100644 --- a/htdocs/cashdesk/index.php +++ b/htdocs/cashdesk/index.php @@ -99,16 +99,15 @@ print $form->select_company(GETPOST('socid','int')?GETPOST('socid','int'):$conf- print ''; print "\n"; -if (! empty($conf->stock->enabled)) +if (! empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { $langs->load("stocks"); print ""; print ''.$langs->trans("Warehouse").''; print ''; $disabled=0; - if (! empty($conf->global->CASHDESK_ID_WAREHOUSE)) $disabled=1; // If a particular stock is defined, we disable choice - print $formproduct->selectWarehouses((GETPOST('warehouseid')?GETPOST('warehouseid'):(empty($conf->global->CASHDESK_ID_WAREHOUSE)?'ifone':$conf->global->CASHDESK_ID_WAREHOUSE)),'warehouseid','',!$disabled,$disabled); - //print ''; + if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) $disabled=1; // If a particular stock is defined, we disable choice + print $formproduct->selectWarehouses((GETPOST('warehouseid')?GETPOST('warehouseid','int'):(empty($conf->global->CASHDESK_ID_WAREHOUSE)?'ifone':$conf->global->CASHDESK_ID_WAREHOUSE)),'warehouseid','',!$disabled,$disabled); print ''; print "\n"; } @@ -152,7 +151,7 @@ print "\n";
-
+
diff --git a/htdocs/cashdesk/index_verif.php b/htdocs/cashdesk/index_verif.php index c96b4f2b6f1..db80866a77f 100644 --- a/htdocs/cashdesk/index_verif.php +++ b/htdocs/cashdesk/index_verif.php @@ -36,11 +36,11 @@ $langs->load("cashdesk"); $username = GETPOST("txtUsername"); $password = GETPOST("pwdPassword"); -$thirdpartyid = (GETPOST('socid','int')!='')?GETPOST('socid','int'):$conf->global->CASHDESK_ID_THIRDPARTY; -$warehouseid = (GETPOST("warehouseid")!='')?GETPOST("warehouseid"):$conf->global->CASHDESK_ID_WAREHOUSE; -$bankid_cash = (GETPOST("CASHDESK_ID_BANKACCOUNT_CASH")!='')?GETPOST("CASHDESK_ID_BANKACCOUNT_CASH"):$conf->global->CASHDESK_ID_BANKACCOUNT_CASH; -$bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE")!='')?GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE"):$conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE; -$bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB")!='')?GETPOST("CASHDESK_ID_BANKACCOUNT_CB"):$conf->global->CASHDESK_ID_BANKACCOUNT_CB; +$thirdpartyid = (GETPOST('socid','int') > 0)?GETPOST('socid','int'):$conf->global->CASHDESK_ID_THIRDPARTY; +$warehouseid = (GETPOST("warehouseid") > 0)?GETPOST("warehouseid",'int'):$conf->global->CASHDESK_ID_WAREHOUSE; +$bankid_cash = (GETPOST("CASHDESK_ID_BANKACCOUNT_CASH") > 0)?GETPOST("CASHDESK_ID_BANKACCOUNT_CASH",'int'):$conf->global->CASHDESK_ID_BANKACCOUNT_CASH; +$bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE") > 0)?GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE",'int'):$conf->global->CASHDESK_ID_BANKACCOUNT_CHEQUE; +$bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0)?GETPOST("CASHDESK_ID_BANKACCOUNT_CB",'int'):$conf->global->CASHDESK_ID_BANKACCOUNT_CB; // Check username if (empty($username)) @@ -58,15 +58,15 @@ if (! ($thirdpartyid > 0)) } // If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished. -if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_BILL && ! ($warehouseid > 0)) +if (! empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && ! ($warehouseid > 0)) { - $retour=$langs->trans("CashDeskSetupStock"); + $retour=$langs->trans("CashDeskYouDidNotDisableStockDecease"); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // If stock decrease on bill validation, check user has stock edit permissions -if (! empty($conf->stock->enabled) && $conf->global->STOCK_CALCULATE_ON_BILL && ! empty($username)) +if (! empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && ! empty($username)) { $testuser=new User($db); $testuser->fetch(0,$username); @@ -117,8 +117,9 @@ if ( $retour >= 0 ) $_SESSION['uname'] = $username; $_SESSION['lastname'] = $tab['lastname']; $_SESSION['firstname'] = $tab['firstname']; - $_SESSION['CASHDESK_ID_THIRDPARTY'] = $thirdpartyid; - $_SESSION['CASHDESK_ID_WAREHOUSE'] = $warehouseid; + $_SESSION['CASHDESK_ID_THIRDPARTY'] = ($thirdpartyid > 0 ? $thirdpartyid : ''); + $_SESSION['CASHDESK_ID_WAREHOUSE'] = ($warehouseid > 0 ? $warehouseid : ''); + $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] = ($bankid_cash > 0 ? $bankid_cash : ''); $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] = ($bankid_cheque > 0 ? $bankid_cheque : ''); $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] = ($bankid_cb > 0 ? $bankid_cb : ''); @@ -131,7 +132,6 @@ if ( $retour >= 0 ) { dol_print_error($db); } - } else { diff --git a/htdocs/cashdesk/javascript/dhtml.js b/htdocs/cashdesk/javascript/dhtml.js index eb0ef03f257..caf0cd94abd 100644 --- a/htdocs/cashdesk/javascript/dhtml.js +++ b/htdocs/cashdesk/javascript/dhtml.js @@ -16,7 +16,7 @@ */ // Instanciation et initialisation de l'objet xmlhttprequest -function file (fichier) { +function file(fichier) { // Instanciation de l'objet pour Mozilla, Konqueror, Opera, Safari, etc ... if (window.XMLHttpRequest) { @@ -51,7 +51,7 @@ function file (fichier) { // Affichage des donnees aTexte dans le bloc identifie par aId -function afficheDonnees (aId, aTexte) { +function afficheDonnees(aId, aTexte) { document.getElementById(aId).innerHTML = aTexte; @@ -59,7 +59,7 @@ function afficheDonnees (aId, aTexte) { // aCible : id du bloc de destination; aCode : argument a passer a la page php chargee du traitement et de l'affichage -function verifResultat (aCible, aCode) { +function verifResultat(aCible, aCode) { if (aCode != '') { if (texte = file ('facturation_dhtml.php?code='+escape(aCode))) { @@ -76,21 +76,9 @@ function verifResultat (aCible, aCode) { // Change dynamiquement la classe de l'element ayant l'id aIdElement pour aClasse -function setStyle (aIdElement, aClasse) { +function setStyle(aIdElement, aClasse) { aIdElement.className = aClasse; } - - - - - - - - - - - - diff --git a/htdocs/cashdesk/javascript/facturation1.js b/htdocs/cashdesk/javascript/facturation1.js index 11f1739e937..b0b9a45a028 100644 --- a/htdocs/cashdesk/javascript/facturation1.js +++ b/htdocs/cashdesk/javascript/facturation1.js @@ -16,7 +16,7 @@ */ // Calcul et affichage en temps reel des informations sur le produit en cours -function modif () { +function modif() { var prix_unit = parseFloat ( document.getElementById('frmQte').txtPrixUnit.value ); var qte = parseFloat ( document.getElementById('frmQte').txtQte.value ); @@ -71,7 +71,7 @@ function modif () { } // Affecte la source de la requete (liste deroulante ou champ texte 'ref') au champ cache -function setSource (aSrc) { +function setSource(aSrc) { document.getElementById('frmFacturation').hdnSource.value = aSrc; document.getElementById('frmFacturation').submit(); @@ -79,7 +79,7 @@ function setSource (aSrc) { } // Verification de la coherence des informations saisies dans le formulaire de choix du nombre d'articles -function verifSaisie () { +function verifSaisie() { if ( document.getElementById('frmQte').txtQte.value ) { @@ -95,17 +95,17 @@ function verifSaisie () { } // Verification de la coherence des informations saisies dans le formulaire de calcul de la difference -function verifDifference () { +function verifDifference() { var du = parseFloat ( document.getElementById('frmDifference').txtDu.value ); var encaisse = parseFloat ( document.getElementById('frmDifference').txtEncaisse.value ); - if ( encaisse > du ) { + if (encaisse > du) { resultat = Math.round ( (encaisse - du) * 100 ) / 100; document.getElementById('frmDifference').txtRendu.value = resultat.toFixed(2); - } else if ( encaisse == du ) { + } else if (encaisse == du) { document.getElementById('frmDifference').txtRendu.value = '0'; @@ -118,14 +118,14 @@ function verifDifference () { } // Affecte le moyen de paiement (ESP, CB ou CHQ) au champ cache en fonction du bouton clique -function verifClic (aChoix) { +function verifClic(aChoix) { document.getElementById('frmDifference').hdnChoix.value = aChoix; } // Determination du moyen de paiement, et validation du formulaire si les donnees sont coherentes -function verifReglement () { +function verifReglement() { var choix = document.getElementById('frmDifference').hdnChoix.value; var du = parseFloat (document.getElementById('frmDifference').txtDu.value); @@ -172,5 +172,4 @@ function verifReglement () { return false; } - } diff --git a/htdocs/cashdesk/javascript/index.html b/htdocs/cashdesk/javascript/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/javascript/index.php b/htdocs/cashdesk/javascript/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/cashdesk/javascript/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/cashdesk/javascript/keypad.js b/htdocs/cashdesk/javascript/keypad.js new file mode 100644 index 00000000000..6de759fc35a --- /dev/null +++ b/htdocs/cashdesk/javascript/keypad.js @@ -0,0 +1,36 @@ +/* Copyright (C) 2014 Charles-FR BENKE + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * 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 . + */ + +function closekeypad(keypadname) +{ + document.getElementById('keypad'+keypadname).style.display='none'; + document.getElementById('closekeypad'+keypadname).style.display='none'; + document.getElementById('openkeypad'+keypadname).style.display='inline-block'; +} +function openkeypad(keypadname) +{ + document.getElementById('keypad'+keypadname).style.display='inline-block'; + document.getElementById('closekeypad'+keypadname).style.display='inline-block'; + document.getElementById('openkeypad'+keypadname).style.display='none'; +} +function addvalue(keypadname, formname, valueToAdd) +{ + myform=document.forms[formname]; + if (myform.elements[keypadname].value=="0") + myform.elements[keypadname].value=""; + myform.elements[keypadname].value+=valueToAdd; + modif(); +} diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index d8e4049f922..47116705320 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -28,6 +28,7 @@ $langs->load("cashdesk"); +
trans("Article"); ?> @@ -42,6 +43,7 @@ $langs->load("cashdesk"); @@ -103,23 +105,28 @@ $langs->load("cashdesk"); trans("VATRate"); ?> - + + + - - + + + currency; ?> - + + + currency; ?> + - " /> + " />
- +
@@ -154,7 +159,9 @@ $langs->load("cashdesk"); - + + + @@ -172,7 +179,7 @@ $langs->load("cashdesk"); $langs->load("errors"); print ''; } - else print ''; + else print ''; print ''; print ''; if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) @@ -180,7 +187,7 @@ $langs->load("cashdesk"); $langs->load("errors"); print ''; } - else print ''; + else print ''; print ''; print ''; if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) @@ -188,7 +195,7 @@ $langs->load("cashdesk"); $langs->load("errors"); print ''; } - else print ''; + else print ''; print ''; ?> @@ -196,14 +203,11 @@ $langs->load("cashdesk"); diff --git a/htdocs/cashdesk/tpl/index.html b/htdocs/cashdesk/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cashdesk/tpl/index.php b/htdocs/cashdesk/tpl/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/cashdesk/tpl/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/cashdesk/tpl/liste_articles.tpl.php b/htdocs/cashdesk/tpl/liste_articles.tpl.php index 2fac2e2a16a..160c9afd8a8 100644 --- a/htdocs/cashdesk/tpl/liste_articles.tpl.php +++ b/htdocs/cashdesk/tpl/liste_articles.tpl.php @@ -67,8 +67,6 @@ else } } -$obj_facturation->calculTotaux(); -$total_ttc = $obj_facturation->prixTotalTtc(); echo ('

'.$langs->trans("Total").' : '.price(price2num($total_ttc, 'MT'),0,$langs,0,0,-1,$conf->currency).'

'."\n"); ?> diff --git a/htdocs/cashdesk/tpl/menu.tpl.php b/htdocs/cashdesk/tpl/menu.tpl.php index 4ee52ce0da6..ce38bb7d7e8 100644 --- a/htdocs/cashdesk/tpl/menu.tpl.php +++ b/htdocs/cashdesk/tpl/menu.tpl.php @@ -72,7 +72,7 @@ print $langs->trans("CashDeskThirdParty").': '.$companyLink.'
'; /*print $langs->trans("CashDeskBankCash").': '.$bankcashLink.'
'; print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'
'; print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'
';*/ -if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && ! empty($conf->stock->enabled)) +if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && ! empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { print $langs->trans("CashDeskWarehouse").': '.$warehouseLink; } diff --git a/htdocs/cashdesk/tpl/ticket.tpl.php b/htdocs/cashdesk/tpl/ticket.tpl.php index 54e82c3ded7..9ea8cb70943 100644 --- a/htdocs/cashdesk/tpl/ticket.tpl.php +++ b/htdocs/cashdesk/tpl/ticket.tpl.php @@ -153,4 +153,5 @@ echo '"; // Categorie - print ""; + print ""; // Link to delete from category print ''; } diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index 69a8bb97eab..c54d7d889b2 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -241,7 +241,7 @@ if ($object->id) // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine if ($obj['photo_vignette']) { - $filename='thumbs/'.$obj['photo_vignette']; + $filename=$obj['photo_vignette']; } else { diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 15e8f7f6a5f..0c154a0b72f 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -94,7 +94,7 @@ $cancel != $langs->trans("Cancel") && else { $action = 'add'; - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } @@ -127,7 +127,7 @@ $cancel != $langs->trans("Cancel") && else { $action = 'edit'; - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } @@ -153,10 +153,6 @@ else $title=$langs->trans("Category"); $head = categories_prepare_head($object,$type); dol_fiche_head($head, 'translation', $title, 0, 'category'); -if (! empty($mesg)) { - dol_htmloutput_mesg($mesg); -} - print '
- " onclick="javascript: verifClic('DIF');" /> + " onclick="javascript: verifClic('DIF');" /> trans("DateEcheance").' :'; print $form->select_date(-1,'txtDatePaiement'); ?> -
'.$langs->trans("TotalTTC").'trans("Close"); ?> - \ No newline at end of file + + diff --git a/htdocs/cashdesk/tpl/validation1.tpl.php b/htdocs/cashdesk/tpl/validation1.tpl.php index 15762ecf494..1aa1c0c4723 100644 --- a/htdocs/cashdesk/tpl/validation1.tpl.php +++ b/htdocs/cashdesk/tpl/validation1.tpl.php @@ -17,6 +17,7 @@ */ $langs->load("main"); +$langs->load("bills"); // Object $form must de defined @@ -111,8 +112,9 @@ $langs->load("main");

trans("Notes"); ?>

- " /> -

trans("RestartSelling"); ?>

+ diff --git a/htdocs/cashdesk/tpl/validation2.tpl.php b/htdocs/cashdesk/tpl/validation2.tpl.php index 9ebab951eb9..b00268d7b0a 100644 --- a/htdocs/cashdesk/tpl/validation2.tpl.php +++ b/htdocs/cashdesk/tpl/validation2.tpl.php @@ -18,10 +18,11 @@ */ $langs->load("main"); +$langs->load("bills"); ?> -

trans("SellFinished"); ?>

+

trans("SellFinished"); ?>


diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index 173c1894555..27ce3380dd4 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -218,7 +218,33 @@ switch ($action) $resultcreate=$invoice->create($user,0,dol_stringtotime($obj_facturation->paiementLe())); if ($resultcreate > 0) { - $resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), (isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0)); + $warehouseidtodecrease=(isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0); + if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease=0; // If a particular stock is defined, we disable choice + + $resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), 0); + + if ($warehouseidtodecrease > 0) + { + // Decrease + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; + $langs->load("agenda"); + // Loop on each line + $cpt=count($invoice->lines); + for ($i = 0; $i < $cpt; $i++) + { + if ($invoice->lines[$i]->fk_product > 0) + { + $mouvP = new MouvementStock($db); + $mouvP->origin = &$invoice; + // We decrease stock for product + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref)); + else $result=$mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref)); + if ($result < 0) { + $error++; + } + } + } + } } else { @@ -232,7 +258,33 @@ switch ($action) $resultcreate=$invoice->create($user,0,0); if ($resultcreate > 0) { - $resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), (isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0)); + $warehouseidtodecrease=(isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0); + if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease=0; // If a particular stock is defined, we disable choice + + $resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), 0); + + if ($warehouseidtodecrease > 0) + { + // Decrease + require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; + $langs->load("agenda"); + // Loop on each line + $cpt=count($invoice->lines); + for ($i = 0; $i < $cpt; $i++) + { + if ($invoice->lines[$i]->fk_product > 0) + { + $mouvP = new MouvementStock($db); + $mouvP->origin = &$invoice; + // We decrease stock for product + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref)); + else $result=$mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref)); + if ($result < 0) { + $error++; + } + } + } + } $id = $invoice->id; diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index 6f8369afc89..712f60f25cd 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -35,7 +35,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -65,7 +65,7 @@ llxHeader('',$langs->trans("Categories"),$help_url); $linkback=''.$langs->trans("BackToModuleList").''; print_fiche_titre($langs->trans("CategoriesSetup"),$linkback,'setup'); -$head = categoriesadmin_prepare_head(null); +$head = categoriesadmin_prepare_head(); dol_fiche_head($head, 'attributes_categories', $langs->trans("Categories"), 0, 'category'); diff --git a/htdocs/categories/admin/index.html b/htdocs/categories/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/categories/fiche.php b/htdocs/categories/card.php similarity index 92% rename from htdocs/categories/fiche.php rename to htdocs/categories/card.php index 208cbb38331..672c92b9508 100644 --- a/htdocs/categories/fiche.php +++ b/htdocs/categories/card.php @@ -1,9 +1,9 @@ - * Copyright (C) 2006-2011 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2007 Patrick Raguin - * Copyright (C) 2013 Florian Henry +/* Copyright (C) 2005 Matthieu Valleton + * Copyright (C) 2006-2011 Laurent Destailleur + * Copyright (C) 2005-2014 Regis Houssin + * Copyright (C) 2007 Patrick Raguin + * Copyright (C) 2013 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +20,7 @@ */ /** - * \file htdocs/categories/fiche.php + * \file htdocs/categories/card.php * \ingroup category * \brief Page to create a new category */ @@ -116,7 +116,7 @@ if ($action == 'add' && $user->rights->categorie->creer) } } - + $object->label = $label; $object->description = dol_htmlcleanlastbr($description); @@ -125,13 +125,13 @@ if ($action == 'add' && $user->rights->categorie->creer) $object->type = $type; if ($parent != "-1") $object->fk_parent = $parent; - + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); if (! $object->label) { $error++; - $errors[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("Ref")); + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Ref")), 'errors'); $action = 'create'; } @@ -143,7 +143,9 @@ if ($action == 'add' && $user->rights->categorie->creer) { $action = 'confirmed'; $_POST["addcat"] = ''; - } else { + } + else + { setEventMessage($object->error,'errors'); } } @@ -226,8 +228,6 @@ if ($user->rights->categorie->creer) print_fiche_titre($langs->trans("CreateCat")); - dol_htmloutput_errors('',$errors); - print ''; // Ref @@ -247,6 +247,7 @@ if ($user->rights->categorie->creer) print $form->select_all_categories($type, $catorigin); print ''; + $parameters=array(); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { diff --git a/htdocs/categories/categorie.php b/htdocs/categories/categorie.php index 7f8ceac853e..e9e11b656b9 100644 --- a/htdocs/categories/categorie.php +++ b/htdocs/categories/categorie.php @@ -93,7 +93,7 @@ if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user,$objecttype,$objectid,$dbtablename,'','',$fieldid); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('categorycard')); +$hookmanager->initHooks(array('categorycard','globalcard')); /* @@ -102,7 +102,7 @@ $hookmanager->initHooks(array('categorycard')); $parameters=array('id'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -$error=$hookmanager->error; $errors=array_merge($errors, (array) $hookmanager->errors); +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { @@ -207,8 +207,7 @@ if (empty($reshook)) } else { - setEventMessage($cat->error,'errors'); - setEventMessage($cat->errors,'errors'); + setEventMessages($cat->error,$this->errors,'errors'); } } } @@ -396,7 +395,7 @@ else if ($id || $ref) llxHeader("","",$langs->trans("Member")); - $head=member_prepare_head($member, $user); + $head=member_prepare_head($member); $titre=$langs->trans("Member"); $picto='user'; dol_fiche_head($head, 'category', $titre,0,$picto); @@ -471,7 +470,7 @@ else if ($id || $ref) llxHeader("","",$langs->trans("Contact")); - $head=contact_prepare_head($object, $user); + $head=contact_prepare_head($object); $titre=$langs->trans("ContactsAddresses"); $picto='contact'; dol_fiche_head($head, 'category', $titre,0,$picto); @@ -551,7 +550,7 @@ else if ($id || $ref) { $langs->load("mails"); print ''; - print ''; + print ''; } else { @@ -622,32 +621,32 @@ function formCategory($db,$object,$typeid,$socid=0,$showclassifyform=1) if ($typeid == 3) $title = $langs->trans("MembersCategoriesShort"); if ($typeid == 4) $title = $langs->trans("ContactCategoriesShort"); + $linktocreate=''; + if ($showclassifyform && $user->rights->categorie->creer) + { + $linktocreate='id.'&type='.$typeid).'">'; + $linktocreate.=$langs->trans("CreateCat").' '; + $linktocreate.=img_picto($langs->trans("Create"),'filenew'); + $linktocreate.=""; + } + print '
'; - print_fiche_titre($title,'',''); + print_fiche_titre($title,$linktocreate,''); // Form to add record into a category if ($showclassifyform) { - print ''; + print ''; print ''; print ''; print ''; print ''; print '
'.$langs->trans("NbOfEMailingsReceived").''.$object->getNbOfEMailings().''.$object->getNbOfEMailings().'
'; print ''; - if ($user->rights->categorie->creer) - { - print ''; - } + print ''; + print ''; print ''; print '
'; - print $langs->trans("ClassifyInCategory").'  '; + print ''.$langs->trans("ClassifyInCategory").'  '; print $form->select_all_categories($typeid,'auto'); - print ''; - print ''; - print 'id.'&type='.$typeid).'">'; - print $langs->trans("CreateCat").' '; - print img_picto($langs->trans("Create"),'filenew'); - print ""; - print '
'; print ''; @@ -680,10 +679,7 @@ function formCategory($db,$object,$typeid,$socid=0,$showclassifyform=1) print "
"; - //$c->id=; - //print $c->getNomUrl(1); - print img_object('','category').' '.$way."".img_object('','category').' '.$way."'; diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 2044c511c35..de8d494f9fc 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -87,10 +87,10 @@ class Categorie extends CommonObject else { - if ($label) $sql.= " WHERE label = '".$this->db->escape($label)."' AND entity=".$conf->entity;; + if ($label) $sql.= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category',1).")"; } - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -107,7 +107,7 @@ class Categorie extends CommonObject $this->type = $res['type']; $this->entity = $res['entity']; - $this->fetch_optionals($this->id,$extralabels); + $this->fetch_optionals($this->id,null); $this->db->free($resql); @@ -161,7 +161,7 @@ class Categorie extends CommonObject $this->db->begin(); - dol_syslog(get_class($this).'::create sql='.$sql); + dol_syslog(get_class($this).'::create', LOG_DEBUG); $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie ("; $sql.= "fk_parent,"; $sql.= " label,"; @@ -188,7 +188,7 @@ class Categorie extends CommonObject $sql.= $conf->entity; $sql.= ")"; - dol_syslog(get_class($this).'::create sql='.$sql); + dol_syslog(get_class($this).'::create', LOG_DEBUG); $res = $this->db->query($sql); if ($res) { @@ -198,6 +198,8 @@ class Categorie extends CommonObject { $this->id = $id; + $action='create'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('HookModuleNamedao')); @@ -216,15 +218,21 @@ class Categorie extends CommonObject } else if ($reshook < 0) $error++; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CATEGORY_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CATEGORY_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers - $this->db->commit(); - return $id; + if ( ! $error ) + { + $this->db->commit(); + return $id; + } + else + { + $this->db->rollback(); + return -3; + } } else { @@ -235,7 +243,6 @@ class Categorie extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create error ".$this->error." sql=".$sql, LOG_ERR); $this->db->rollback(); return -1; } @@ -281,14 +288,16 @@ class Categorie extends CommonObject $sql .= ", fk_parent = ".$this->fk_parent; $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql); + dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { + $action='update'; // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('HookCategorydao')); $parameters=array(); + $action='update'; $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks if (empty($reshook)) { @@ -306,12 +315,10 @@ class Categorie extends CommonObject $this->db->commit(); - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CATEGORY_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CATEGORY_MODIFY',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers return 1; } @@ -335,6 +342,9 @@ class Categorie extends CommonObject $error=0; + // Clean parameters + $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); + dol_syslog(get_class($this)."::remove"); $this->db->begin(); @@ -349,7 +359,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } } @@ -360,7 +369,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } } @@ -371,7 +379,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } } @@ -382,7 +389,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } } @@ -393,7 +399,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } } @@ -402,6 +407,16 @@ class Categorie extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact"; $sql .= " WHERE fk_categorie = ".$this->id; if (!$this->db->query($sql)) + { + $this->error=$this->db->lasterror(); + $error++; + } + } + if (! $error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_lang"; + $sql .= " WHERE fk_category = ".$this->id; + if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); @@ -417,7 +432,6 @@ class Categorie extends CommonObject if (!$this->db->query($sql)) { $this->error=$this->db->lasterror(); - dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR); $error++; } else @@ -431,16 +445,14 @@ class Categorie extends CommonObject if ($result < 0) { $error++; - dol_syslog(get_class($this)."::delete erreur ".$errorflag." ".$this->error, LOG_ERR); + dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR); } } } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CATEGORY_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; $this->error=join(',',$this->errors); } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CATEGORY_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -480,10 +492,12 @@ class Categorie extends CommonObject if ($type=='contact') $column_name='socpeople'; if ($type=='fournisseur') $column_name='societe'; + $this->db->begin(); + $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".$type." (fk_categorie, fk_".$column_name.")"; $sql .= " VALUES (".$this->id.", ".$obj->id.")"; - dol_syslog(get_class($this).'::add_type sql='.$sql); + dol_syslog(get_class($this).'::add_type', LOG_DEBUG); if ($this->db->query($sql)) { if (! empty($conf->global->CATEGORIE_RECURSIV_ADD)) @@ -491,7 +505,7 @@ class Categorie extends CommonObject $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie'; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::add_type sql=".$sql); + dol_syslog(get_class($this)."::add_type", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -520,6 +534,7 @@ class Categorie extends CommonObject if ($error) { + $this->db->rollback(); return -1; } } @@ -527,18 +542,26 @@ class Categorie extends CommonObject // Save object we want to link category to into category instance to provide information to trigger $this->linkto=$obj; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CATEGORY_LINK',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; $this->error=$interface->error; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CATEGORY_LINK',$user); + if ($result < 0) { $error++; } + // End call triggers + + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -2; + } - if (! $error) return 1; - else return -2; } else { + $this->db->rollback(); if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error=$this->db->lasterrno(); @@ -574,28 +597,37 @@ class Categorie extends CommonObject if ($type=='contact') $column_name='socpeople'; if ($type=='fournisseur') $column_name='societe'; + $this->db->begin(); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".$type; $sql .= " WHERE fk_categorie = ".$this->id; $sql .= " AND fk_".$column_name." = ".$obj->id; - dol_syslog(get_class($this).'::del_type sql='.$sql); + dol_syslog(get_class($this).'::del_type', LOG_DEBUG); if ($this->db->query($sql)) { // Save object we want to unlink category off into category instance to provide information to trigger $this->unlinkoff=$obj; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CATEGORY_UNLINK',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CATEGORY_UNLINK',$user); + if ($result < 0) { $error++; } + // End call triggers - if (! $error) return 1; - else return -2; + if (! $error) + { + $this->db->commit(); + return 1; + } + else + { + $this->db->rollback(); + return -2; + } } else { + $this->db->rollback(); $this->error=$this->db->lasterror(); return -1; } @@ -629,7 +661,7 @@ class Categorie extends CommonObject $sql.= " AND c.fk_categorie = ".$this->id; $sql.= " AND c.fk_".$field." = o.rowid"; - dol_syslog(get_class($this)."::getObjectsInCateg sql=".$sql); + dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -644,7 +676,6 @@ class Categorie extends CommonObject else { $this->error=$this->db->error().' sql='.$sql; - dol_syslog(get_class($this)."::getObjectsInCateg ".$this->error, LOG_ERR); return -1; } } @@ -682,13 +713,12 @@ class Categorie extends CommonObject } $sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . "categorie_" . $category_table; $sql .= " WHERE fk_categorie = " . $this->id . " AND fk_" . $field . " = " . $object_id; - dol_syslog(get_class($this)."::containsObject sql=".$sql); + dol_syslog(get_class($this)."::containsObject", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { return $this->db->fetch_object($resql)->nb; } else { $this->error=$this->db->error().' sql='.$sql; - dol_syslog(get_class($this)."::containsObject ".$this->error, LOG_ERR); return -1; } } @@ -740,7 +770,7 @@ class Categorie extends CommonObject $sql.= " WHERE fk_parent != 0"; $sql.= " AND entity IN (".getEntity('category',1).")"; - dol_syslog(get_class($this)."::load_motherof sql=".$sql); + dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -773,7 +803,7 @@ class Categorie extends CommonObject */ function get_full_arbo($type,$markafterid=0) { - global $langs; + global $conf, $langs; $this->cats = array(); @@ -783,15 +813,13 @@ class Categorie extends CommonObject // Init $this->cats array $sql = "SELECT DISTINCT c.rowid, c.label, c.description, c.fk_parent"; // Distinct reduce pb with old tables with duplicates - if (! empty($conf->global->MAIN_MULTILANGS)) - $sql.= ", t.label as label_trans, t.description as description_trans"; + if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= ", t.label as label_trans, t.description as description_trans"; $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c"; - if (! empty($conf->global->MAIN_MULTILANGS)) - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$current_lang."'"; + if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$current_lang."'"; $sql.= " WHERE c.entity IN (".getEntity('category',1).")"; $sql.= " AND c.type = ".$type; - dol_syslog(get_class($this)."::get_full_arbo get category list sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -985,7 +1013,7 @@ class Categorie extends CommonObject $sql.= " AND c.fk_parent = ".$this->fk_parent; $sql.= " AND c.label = '".$this->db->escape($this->label)."'"; - dol_syslog(get_class($this)."::already_exists sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::already_exists", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1009,7 +1037,6 @@ class Categorie extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::already_exists error ".$this->error." sql=".$sql, LOG_ERR); return -1; } } @@ -1148,7 +1175,7 @@ class Categorie extends CommonObject $sql.= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".$table." = ".$id." AND c.type = ".$typeid; $sql.= " AND c.entity IN (".getEntity('category',1).")"; - dol_syslog(get_class($this).'::containing sql='.$sql); + dol_syslog(get_class($this).'::containing', LOG_DEBUG); $res = $this->db->query($sql); if ($res) { @@ -1230,7 +1257,6 @@ class Categorie extends CommonObject else { $this->error=$this->db->error().' sql='.$sql; - dol_syslog(get_class($this)."::rechercher ".$this->error, LOG_ERR); return -1; } } @@ -1250,7 +1276,7 @@ class Categorie extends CommonObject $result=''; $lien = ''; - $label=$langs->trans("ShowCategory").': '.$this->label; + $label=$langs->trans("ShowCategory").': '. ($this->ref?$this->ref:$this->label); $lienfin=''; $picto='category'; @@ -1258,7 +1284,7 @@ class Categorie extends CommonObject if ($withpicto) $result.=($lien.img_object($label,$picto).$lienfin); if ($withpicto && $withpicto != 2) $result.=' '; - if ($withpicto != 2) $result.=$lien.dol_trunc($this->ref,$maxlength).$lienfin; + if ($withpicto != 2) $result.=$lien.dol_trunc(($this->ref?$this->ref:$this->label),$maxlength).$lienfin; return $result; } @@ -1356,7 +1382,7 @@ class Categorie extends CommonObject // Objet $obj=array(); $obj['photo']=$photo; - if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette']=$photo_vignette; + if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette']='thumbs/' . $photo_vignette; else $obj['photo_vignette']=""; $tabobj[$nbphoto-1]=$obj; @@ -1450,11 +1476,10 @@ class Categorie extends CommonObject $sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->label); $sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"])."')"; } - dol_syslog(get_class($this).'::setMultiLangs sql='.$sql2); + dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); if (! $this->db->query($sql2)) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this).'::setMultiLangs error='.$this->error, LOG_ERR); return -1; } } @@ -1476,11 +1501,10 @@ class Categorie extends CommonObject // on ne sauvegarde pas des champs vides if ( $this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"] ) - dol_syslog(get_class($this).'::setMultiLangs sql='.$sql2); + dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); if (! $this->db->query($sql2)) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this).'::setMultiLangs error='.$this->error, LOG_ERR); return -1; } } diff --git a/htdocs/categories/class/index.html b/htdocs/categories/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index 0c61ab8cca6..aa82fdb455d 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -80,12 +80,12 @@ if ($action == 'update' && $user->rights->categorie->creer) if (empty($categorie->label)) { $action = 'create'; - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("Label")); + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Label")), 'errors'); } if (empty($categorie->description)) { $action = 'create'; - $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("Description")); + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Description")), 'errors'); } if (empty($categorie->error)) { @@ -98,12 +98,12 @@ if ($action == 'update' && $user->rights->categorie->creer) } else { - $mesg=$categorie->error; + setEventMessage($categorie->error, 'errors'); } } else { - $mesg=$categorie->error; + setEventMessage($categorie->error, 'errors'); } } @@ -117,10 +117,6 @@ llxHeader("","",$langs->trans("Categories")); print_fiche_titre($langs->trans("ModifCat")); - -dol_htmloutput_errors($mesg); - - $object->fetch($id); $form = new Form($db); diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index eceeb2890bc..76a19c91d7d 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -171,7 +171,7 @@ $nbofentries=(count($data) - 1); if ($nbofentries > 0) { - print '
'; + print '
'; tree_recur($data,$data[0],0); print '
'; // Reference diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 010306d1e00..c55f324ab06 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -32,13 +32,13 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $langs->load("categories"); -$mesg = ''; $id=GETPOST('id','int'); $ref=GETPOST('ref'); $type=GETPOST('type'); $action=GETPOST('action'); $confirm=GETPOST('confirm'); $removeelem = GETPOST('removeelem','int'); +$elemid=GETPOST('elemid'); if ($id == "") { @@ -117,10 +117,37 @@ if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confi } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } +if ($type==0 && $elemid && $action == 'addintocategory' && ($user->rights->produit->creer || $user->rights->service->creer)) +{ + require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; + $newobject = new Product($db); + $result = $newobject->fetch($elemid); + $elementtype = 'product'; + + // TODO Add into categ + $result=$object->add_type($newobject,$elementtype); + if ($result >= 0) + { + setEventMessage($langs->trans("WasAddedSuccessfully",$newobject->ref)); + } + else + { + if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + setEventMessage($langs->trans("ObjectAlreadyLinkedToCategory"),'warnings'); + } + else + { + setEventMessages($object->error,$object->errors,'errors'); + } + } + +} + /* @@ -131,8 +158,6 @@ $form = new Form($db); llxHeader("","",$langs->trans("Categories")); -dol_htmloutput_mesg($mesg); - if ($type == 0) $title=$langs->trans("ProductsCategoryShort"); elseif ($type == 1) $title=$langs->trans("SuppliersCategoryShort"); elseif ($type == 2) $title=$langs->trans("CustomersCategoryShort"); @@ -147,6 +172,7 @@ dol_fiche_head($head, 'card', $title, 0, 'category'); /* * Confirmation suppression */ + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type,$langs->trans('DeleteCategory'),$langs->trans('ConfirmDeleteCategory'),'confirm_delete'); @@ -215,7 +241,7 @@ else print "
".$langs->trans("SubCats").''; if ($user->rights->categorie->creer) { - print ""; + print ""; print img_picto($langs->trans("Create"),'filenew'); print ""; } @@ -254,10 +280,9 @@ else print "
\n"; } -// List of products +// List of products or services (type is type of category) if ($object->type == 0) { - $prods = $object->getObjectsInCateg("product"); if ($prods < 0) { @@ -265,6 +290,29 @@ if ($object->type == 0) } else { + $showclassifyform=1; $typeid=0; + + // Form to add record into a category + if ($showclassifyform) + { + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + print $langs->trans("AddProductServiceIntoCategory").'  '; + print $form->select_produits('','elemid','',0,0,-1,2,'',1); + print ''; + print '
'; + print '
'; + } + print "
"; print "\n"; print '\n"; @@ -519,4 +567,5 @@ if($object->type == 4) llxFooter(); + $db->close(); diff --git a/htdocs/comm/action/fiche.php b/htdocs/comm/action/card.php similarity index 53% rename from htdocs/comm/action/fiche.php rename to htdocs/comm/action/card.php index d17b1acb4f0..8a2c602a3f0 100644 --- a/htdocs/comm/action/fiche.php +++ b/htdocs/comm/action/card.php @@ -1,10 +1,11 @@ - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005 Simon TOSSER * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2010-2013 Juanjo Menent * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Cedric GROSS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,7 +22,7 @@ */ /** - * \file htdocs/comm/action/fiche.php + * \file htdocs/comm/action/card.php * \ingroup agenda * \brief Page for event card */ @@ -34,7 +35,8 @@ require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; -if (! empty($conf->projet->enabled)) { +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'; } @@ -54,6 +56,10 @@ $contactid=GETPOST('contactid','int'); $origin=GETPOST('origin','alpha'); $originid=GETPOST('originid','int'); +$fulldayevent=GETPOST('fullday'); +$datep=dol_mktime($fulldayevent?'00':GETPOST("aphour"), $fulldayevent?'00':GETPOST("apmin"), 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); +$datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour"), $fulldayevent?'59':GETPOST("p2min"), $fulldayevent?'59':'0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); + // Security check $socid = GETPOST('socid','int'); $id = GETPOST('id','int'); @@ -62,7 +68,7 @@ $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions| if ($user->societe_id && $socid) $result = restrictedArea($user,'societe',$socid); $error=GETPOST("error"); -$mesg=''; +$donotclearsession=GETPOST('donotclearsession')?GETPOST('donotclearsession'):0; $cactioncomm = new CActionComm($db); $object = new ActionComm($db); @@ -75,15 +81,53 @@ $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); //var_dump($_POST); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('actioncard')); +$hookmanager->initHooks(array('actioncard','globalcard')); /* * Actions */ -// Add action -if ($action == 'add_action') +// Remove user to assigned list +if (GETPOST('removedassigned') || GETPOST('removedassigned') == '0') +{ + $idtoremove=GETPOST('removedassigned'); + + if (! empty($_SESSION['assignedtouser'])) $tmpassigneduserids=dol_json_decode($_SESSION['assignedtouser'],1); + else $tmpassigneduserids=array(); + + foreach ($tmpassigneduserids as $key => $val) + { + if ($val['id'] == $idtoremove || $val['id'] == -1) unset($tmpassigneduserids[$key]); + } + //var_dump($_POST['removedassigned']);exit; + $_SESSION['assignedtouser']=dol_json_encode($tmpassigneduserids); + $donotclearsession=1; + if ($action == 'add') $action = 'create'; + if ($action == 'update') $action = 'edit'; +} + +// Add user to assigned list +if (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser')) +{ + // Add a new user + if (GETPOST('assignedtouser') > 0) + { + $assignedtouser=array(); + if (! empty($_SESSION['assignedtouser'])) + { + $assignedtouser=dol_json_decode($_SESSION['assignedtouser'], true); + } + $assignedtouser[GETPOST('assignedtouser')]=array('id'=>GETPOST('assignedtouser'), 'transparency'=>GETPOST('transparency'),'mandatory'=>1); + $_SESSION['assignedtouser']=dol_json_encode($assignedtouser); + } + $donotclearsession=1; + if ($action == 'add') $action = 'create'; + if ($action == 'update') $action = 'edit'; +} + +// Add event +if ($action == 'add') { $error=0; @@ -104,91 +148,101 @@ if ($action == 'add_action') exit; } - $fulldayevent=GETPOST('fullday'); $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):GETPOST("percentage"); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - $datep=dol_mktime($fulldayevent?'00':$_POST["aphour"], $fulldayevent?'00':$_POST["apmin"], 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); - $datef=dol_mktime($fulldayevent?'23':$_POST["p2hour"], $fulldayevent?'59':$_POST["p2min"], $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); + $datep=dol_mktime($fulldayevent?'00':GETPOST("aphour"), $fulldayevent?'00':GETPOST("apmin"), 0, GETPOST("apmonth"), GETPOST("apday"), GETPOST("apyear")); + $datef=dol_mktime($fulldayevent?'23':GETPOST("p2hour"), $fulldayevent?'59':GETPOST("p2min"), $fulldayevent?'59':'0', GETPOST("p2month"), GETPOST("p2day"), GETPOST("p2year")); // Check parameters if (! $datef && $percentage == 100) { - $error++; + $error++; $donotclearsession=1; $action = 'create'; - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")), 'errors'); } if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && ! GETPOST('label')) { - $error++; + $error++; $donotclearsession=1; $action = 'create'; - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Title")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Title")), 'errors'); } // Initialisation objet cactioncomm - if (! GETPOST('actioncode')) + if (! GETPOST('actioncode') > 0) // actioncode is id { - $error++; + $error++; $donotclearsession=1; $action = 'create'; - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")), 'errors'); } else { - $result=$cactioncomm->fetch(GETPOST('actioncode')); + $object->type_code = GETPOST('actioncode'); } - // Initialisation objet actioncomm - $object->type_id = $cactioncomm->id; - $object->type_code = $cactioncomm->code; - $object->priority = GETPOST("priority")?GETPOST("priority"):0; - $object->fulldayevent = (! empty($fulldayevent)?1:0); - $object->location = GETPOST("location"); - $object->transparency = (GETPOST("transparency")=='on'?1:0); - $object->label = trim(GETPOST('label')); - $object->fk_element = GETPOST("fk_element"); - $object->elementtype = GETPOST("elementtype"); - if (! GETPOST('label')) + if (! $error) { - if (GETPOST('actioncode') == 'AC_RDV' && $contact->getFullName($langs)) + // Initialisation objet actioncomm + $object->priority = GETPOST("priority")?GETPOST("priority"):0; + $object->fulldayevent = (! empty($fulldayevent)?1:0); + $object->location = GETPOST("location"); + $object->label = trim(GETPOST('label')); + $object->fk_element = GETPOST("fk_element"); + $object->elementtype = GETPOST("elementtype"); + if (! GETPOST('label')) { - $object->label = $langs->transnoentitiesnoconv("TaskRDVWith",$contact->getFullName($langs)); - } - else - { - if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) + if (GETPOST('actioncode') == 'AC_RDV' && $contact->getFullName($langs)) { - $object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n"; + $object->label = $langs->transnoentitiesnoconv("TaskRDVWith",$contact->getFullName($langs)); } - else $object->label = $cactioncomm->libelle; + else + { + if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) + { + $object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n"; + } + else $object->label = $cactioncomm->libelle; + } + } + $object->fk_project = isset($_POST["projectid"])?$_POST["projectid"]:0; + $object->datep = $datep; + $object->datef = $datef; + $object->percentage = $percentage; + $object->duree=((float) (GETPOST('dureehour') * 60) + (float) GETPOST('dureemin')) * 60; + + $listofuserid=array(); + if (! empty($_SESSION['assignedtouser'])) $listofuserid=dol_json_decode($_SESSION['assignedtouser']); + $i=0; + foreach($listofuserid as $key => $value) + { + if ($i == 0) // First entry + { + if ($value['id'] > 0) $object->userownerid=$value['id']; + $object->transparency = (GETPOST("transparency")=='on'?1:0); + } + + $object->userassigned[$value['id']]=array('id'=>$value['id'], 'transparency'=>(GETPOST("transparency")=='on'?1:0)); + + $i++; } } - $object->fk_project = isset($_POST["projectid"])?$_POST["projectid"]:0; - $object->datep = $datep; - $object->datef = $datef; - $object->percentage = $percentage; - $object->duree=((float) (GETPOST('dureehour') * 60) + (float) GETPOST('dureemin')) * 60; - $usertodo=new User($db); - if ($_POST["affectedto"] > 0) + if (! $error && ! empty($conf->global->AGENDA_ENABLE_DONEBY)) { - $usertodo->fetch($_POST["affectedto"]); + if (GETPOST("doneby") > 0) $object->userdoneid = GETPOST("doneby","int"); } - $object->usertodo = $usertodo; - $userdone=new User($db); - if ($_POST["doneby"] > 0) - { - $userdone->fetch($_POST["doneby"]); - } - $object->userdone = $userdone; $object->note = trim($_POST["note"]); + if (isset($_POST["contactid"])) $object->contact = $contact; + if (GETPOST('socid','int') > 0) { - $societe = new Societe($db); - $societe->fetch(GETPOST('socid','int')); - $object->societe = $societe; + $object->socid=GETPOST('socid','int'); + $object->fetch_thirdparty(); + + $object->societe = $object->thirdparty; // For backward compatibility } // Special for module webcal and phenix @@ -197,18 +251,24 @@ if ($action == 'add_action') if (! empty($conf->phenix->enabled) && GETPOST('add_phenix') == 'on') $object->use_phenix=1; // Check parameters + if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) + { + $error++; $donotclearsession=1; + $action = 'create'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ActionsOwnedBy")), 'errors'); + } if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) { - $error++; + $error++; $donotclearsession=1; $action = 'create'; - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")), 'errors'); } if (! GETPOST('apyear') && ! GETPOST('adyear')) { - $error++; + $error++; $donotclearsession=1; $action = 'create'; - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Date")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Date")), 'errors'); } // Fill array 'array_options' with data from add form @@ -225,19 +285,24 @@ if ($action == 'add_action') { if (! $object->error) { + unset($_SESSION['assignedtouser']); + + $moreparam=''; + if ($user->id != $object->ownerid) $moreparam="usertodo=-1"; // We force to remove filter so created record is visible when going back to per user view. + $db->commit(); if (! empty($backtopage)) { - dol_syslog("Back to ".$backtopage); - header("Location: ".$backtopage); + dol_syslog("Back to ".$backtopage.($moreparam?(preg_match('/\?/',$backtopage)?'&'.$moreparam:'?'.$moreparam):'')); + header("Location: ".$backtopage.($moreparam?(preg_match('/\?/',$backtopage)?'&'.$moreparam:'?'.$moreparam):'')); } elseif($idaction) { - header("Location: ".DOL_URL_ROOT.'/comm/action/fiche.php?id='.$idaction); + header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam?'&'.$moreparam:'')); } else { - header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'); + header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam?'?'.$moreparam:'')); } exit; } @@ -248,24 +313,155 @@ if ($action == 'add_action') $langs->load("errors"); $error=$langs->trans($object->error); setEventMessage($error,'errors'); - $action = 'create'; + $action = 'create'; $donotclearsession=1; } } else { $db->rollback(); - $langs->load("errors"); - - if (! empty($object->error)) setEventMessage($langs->trans($object->error), 'errors'); - if (count($object->errors)) setEventMessage($object->errors, 'errors'); - - $action = 'create'; + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; $donotclearsession=1; } } } /* - * Action suppression de l'action + * Action update event + */ +if ($action == 'update') +{ + if (empty($cancel)) + { + $fulldayevent=GETPOST('fullday'); + $aphour=GETPOST('aphour'); + $apmin=GETPOST('apmin'); + $p2hour=GETPOST('p2hour'); + $p2min=GETPOST('p2min'); + $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):(in_array(GETPOST('complete'),array(-1,100))?GETPOST('complete'):GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status + + // Clean parameters + if ($aphour == -1) $aphour='0'; + if ($apmin == -1) $apmin='0'; + if ($p2hour == -1) $p2hour='0'; + if ($p2min == -1) $p2min='0'; + + $object->fetch($id); + $object->fetch_userassigned(); + + $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); + $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); + + $object->fk_action = dol_getIdFromCode($db, GETPOST("actioncode"), 'c_actioncomm'); + $object->label = GETPOST("label"); + $object->datep = $datep; + $object->datef = $datef; + $object->percentage = $percentage; + $object->priority = GETPOST("priority"); + $object->fulldayevent= GETPOST("fullday")?1:0; + $object->location = GETPOST('location'); + $object->socid = GETPOST("socid"); + $object->contactid = GETPOST("contactid",'int'); + //$object->societe->id = $_POST["socid"]; // deprecated + //$object->contact->id = $_POST["contactid"]; // deprecated + $object->fk_project = GETPOST("projectid",'int'); + $object->note = GETPOST("note"); + $object->pnote = GETPOST("note"); + $object->fk_element = GETPOST("fk_element"); + $object->elementtype = GETPOST("elementtype"); + + if (! $datef && $percentage == 100) + { + $error++; $donotclearsession=1; + setEventMessages($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateEnd")),$object->errors,'errors'); + $action = 'edit'; + } + + $transparency=(GETPOST("transparency")=='on'?1:0); + + // Users + $listofuserid=array(); + if (! empty($_SESSION['assignedtouser'])) // Now concat assigned users + { + // Restore array with key with same value than param 'id' + $tmplist1=dol_json_decode($_SESSION['assignedtouser'], true); $tmplist2=array(); + foreach($tmplist1 as $key => $val) + { + if ($val['id'] > 0 && $val['id'] != $assignedtouser) $listofuserid[$val['id']]=$val; + } + } + else { + $assignedtouser=(! empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : 0); + if ($assignedtouser) $listofuserid[$assignedtouser]=array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>($user->id == $assignedtouser ? $transparency : '')); // Owner first + } + + $object->userassigned=array(); $object->userownerid=0; // Clear old content + $i=0; + foreach($listofuserid as $key => $val) + { + if ($i == 0) $object->userownerid = $val['id']; + $object->userassigned[$val['id']]=array('id'=>$val['id'], 'mandatory'=>0, 'transparency'=>($user->id == $val['id'] ? $transparency : '')); + $i++; + } + + if (! empty($conf->global->AGENDA_ENABLE_DONEBY)) + { + if (GETPOST("doneby")) $object->userdoneid=GETPOST("doneby","int"); + } + + // Check parameters + if (! GETPOST('actioncode') > 0) + { + $error++; $donotclearsession=1; + $action = 'edit'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")), 'errors'); + } + else + { + $result=$cactioncomm->fetch(GETPOST('actioncode')); + } + if (empty($object->userownerid)) + { + $error++; $donotclearsession=1; + $action = 'edit'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ActionsOwnedBy")), 'errors'); + } + + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + + if (! $error) + { + $db->begin(); + + $result=$object->update($user); + + if ($result > 0) + { + unset($_SESSION['assignedtouser']); + + $db->commit(); + } + else + { + setEventMessages($object->error,$object->errors,'errors'); + $db->rollback(); + } + } + } + + if (! $error) + { + if (! empty($backtopage)) + { + unset($_SESSION['assignedtouser']); + header("Location: ".$backtopage); + exit; + } + } +} + +/* + * delete event */ if ($action == 'confirm_delete' && GETPOST("confirm") == 'yes') { @@ -283,107 +479,54 @@ if ($action == 'confirm_delete' && GETPOST("confirm") == 'yes') } else { - $mesg=$object->error; - setEventMessage($mesg,'errors'); + setEventMessages($object->error,$object->errors,'errors'); } } } /* - * Action update event + * Action move update, used when user move an event in calendar by drag'n drop */ -if ($action == 'update') +if ($action == 'mupdate') { - if (empty($cancel)) - { - $fulldayevent=GETPOST('fullday'); - $aphour=GETPOST('aphour'); - $apmin=GETPOST('apmin'); - $p2hour=GETPOST('p2hour'); - $p2min=GETPOST('p2min'); - $percentage=in_array(GETPOST('status'),array(-1,100))?GETPOST('status'):GETPOST("percentage"); // If status is -1 or 100, percentage is not defined and we must use status + $object->fetch($id); + $object->fetch_userassigned(); - // Clean parameters - if ($aphour == -1) $aphour='0'; - if ($apmin == -1) $apmin='0'; - if ($p2hour == -1) $p2hour='0'; - if ($p2min == -1) $p2min='0'; + $shour = dol_print_date($object->datep,"%H"); + $smin = dol_print_date($object->datep, "%M"); - $object->fetch($id); + $newdate=GETPOST('newdate','alpha'); + if (empty($newdate) || strpos($newdate,'dayevent_') != 0 ) + { + header("Location: ".$backtopage); + exit; + } - $datep=dol_mktime($fulldayevent?'00':$aphour, $fulldayevent?'00':$apmin, 0, $_POST["apmonth"], $_POST["apday"], $_POST["apyear"]); - $datef=dol_mktime($fulldayevent?'23':$p2hour, $fulldayevent?'59':$p2min, $fulldayevent?'59':'0', $_POST["p2month"], $_POST["p2day"], $_POST["p2year"]); - - $object->fk_action = dol_getIdFromCode($db, $_POST["actioncode"], 'c_actioncomm'); - $object->label = $_POST["label"]; - $object->datep = $datep; - $object->datef = $datef; - $object->percentage = $percentage; - $object->priority = $_POST["priority"]; - $object->fulldayevent= $_POST["fullday"]?1:0; - $object->location = GETPOST('location'); - $object->societe->id = $_POST["socid"]; - $object->contact->id = $_POST["contactid"]; - $object->fk_project = $_POST["projectid"]; - $object->note = $_POST["note"]; - $object->pnote = $_POST["note"]; - $object->fk_element = $_POST["fk_element"]; - $object->elementtype = $_POST["elementtype"]; - if (! $datef && $percentage == 100) - { - $error=$langs->trans("ErrorFieldRequired",$langs->trans("DateEnd")); - $action = 'edit'; - } - - // Users - $usertodo=new User($db); - if ($_POST["affectedto"]) - { - $usertodo->fetch($_POST["affectedto"]); - } - $object->usertodo = $usertodo; - $object->transparency=(GETPOST("transparency")=='on'?1:0); - - $userdone=new User($db); - if ($_POST["doneby"]) - { - $userdone->fetch($_POST["doneby"]); - } - $object->userdone = $userdone; - - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost($extralabels,$object); - - if (! $error) - { - $db->begin(); - - $result=$object->update($user); - - if ($result > 0) - { - $db->commit(); - } - else - { - $db->rollback(); - } - } - } - - if ($result < 0) - { - setEventMessage($object->error,'errors'); - setEventMessage($object->errors,'errors'); - } - else - { - if (! empty($backtopage)) + $datep=dol_mktime($shour, $smin, 0, substr($newdate,13,2), substr($newdate,15,2), substr($newdate,9,4)); + if ($datep!=$object->datep) + { + if (!empty($object->datef)) { - header("Location: ".$backtopage); - exit; + $object->datef+=$datep-$object->datep; } - } + $object->datep=$datep; + $result=$object->update($user); + if ($result < 0) + { + setEventMessage($object->error,'errors'); + setEventMessage($object->errors,'errors'); + } + } + if (! empty($backtopage)) + { + header("Location: ".$backtopage); + exit; + } + else + { + $action=''; + } + } @@ -395,7 +538,7 @@ $help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('',$langs->trans("Agenda"),$help_url); $form = new Form($db); -$htmlactions = new FormActions($db); +$formactions = new FormActions($db); if ($action == 'create') { @@ -453,42 +596,46 @@ if ($action == 'create') print '
'; print ''; - print ''; + print ''; + print ''; if ($backtopage) print ''; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) print ''; if (GETPOST("actioncode") == 'AC_RDV') print_fiche_titre($langs->trans("AddActionRendezVous")); else print_fiche_titre($langs->trans("AddAnAction")); - dol_htmloutput_mesg($mesg); - print '
'.$langs->trans("ProductsAndServices")."
'; - // Type d'action actifs + // Type of event if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print ''; } - else print ''; // Title print 'global->AGENDA_USE_EVENT_TYPE)?' class="fieldrequired"':'').'>'.$langs->trans("Title").''; // Full day - print ''; + print ''; // Date start - $datep=$object->datep; + $datep=($datep?$datep:$object->datep); if (GETPOST('datep','int',1)) $datep=dol_stringtotime(GETPOST('datep','int',1),0); print ''; + // Date end - $datef=$object->datef; + $datef=($datef?$datef:$object->datef); if (GETPOST('datef','int',1)) $datef=dol_stringtotime(GETPOST('datef','int',1),0); + if (empty($datef) && ! empty($datep) && ! empty($conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS)) + { + $datef=dol_time_plus_duree($datep, $conf->global->AGENDA_AUTOSET_END_DATE_WITH_DELTA_HOURS, 'h'); + } print ''; print ''; // Location - print ''; + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) + { + print ''; + } // Assigned to - $var=false; print ''; - - print '
'.$langs->trans("Type").''; - $htmlactions->select_type_actions(GETPOST("actioncode")?GETPOST("actioncode"):$object->type_code, "actioncode","systemauto"); + $formactions->select_type_actions(GETPOST("actioncode")?GETPOST("actioncode"):$object->type_code, "actioncode","systemauto"); print '
'.$langs->trans("EventOnFullDay").'
'.$langs->trans("EventOnFullDay").'
'.$langs->trans("DateActionStart").''; if (GETPOST("afaire") == 1) $form->select_date($datep,'ap',1,1,0,"action",1,1,0,0,'fulldayend'); else if (GETPOST("afaire") == 2) $form->select_date($datep,'ap',1,1,1,"action",1,1,0,0,'fulldayend'); else $form->select_date($datep,'ap',1,1,1,"action",1,1,0,0,'fulldaystart'); print '
'.$langs->trans("DateActionEnd").''; if (GETPOST("afaire") == 1) $form->select_date($datef,'p2',1,1,1,"action",1,1,0,0,'fulldayend'); else if (GETPOST("afaire") == 2) $form->select_date($datef,'p2',1,1,1,"action",1,1,0,0,'fulldayend'); @@ -499,47 +646,47 @@ if ($action == 'create') print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; $percent=-1; - if (isset($_GET['status']) || isset($_POST['status'])) - { - $percent=GETPOST('status'); - } - else if (isset($_GET['percentage']) || isset($_POST['percentage'])) - { - $percent=GETPOST('percentage'); - } + if (isset($_GET['status']) || isset($_POST['status'])) $percent=GETPOST('status'); + else if (isset($_GET['percentage']) || isset($_POST['percentage'])) $percent=GETPOST('percentage'); else { - if (GETPOST("afaire") == 1) $percent=0; - else if (GETPOST("afaire") == 2) $percent=100; + if (GETPOST('complete') == '0' || GETPOST("afaire") == 1) $percent='0'; + else if (GETPOST('complete') == 100 || GETPOST("afaire") == 2) $percent=100; } - $htmlactions->form_select_status_action('formaction',$percent,1,'complete'); + $formactions->form_select_status_action('formaction',$percent,1,'complete'); print '
'.$langs->trans("Location").'
'.$langs->trans("Location").'
'.$langs->trans("ActionAffectedTo").''; - $form->select_users(GETPOST("affectedto")?GETPOST("affectedto"):(! empty($object->usertodo->id) && $object->usertodo->id > 0 ? $object->usertodo->id : $user->id),'affectedto',1); - print '
'; - - print '

'; - - print ''; - - // Busy - print ''; // Realised by - if ($conf->global->AGENDA_ENABLE_DONEBY) + if (! empty($conf->global->AGENDA_ENABLE_DONEBY)) { print ''; } @@ -554,7 +701,7 @@ if ($action == 'create') $societe = new Societe($db); $societe->fetch(GETPOST('socid','int')); print $societe->getNomUrl(1); - print ''; + print ''; } else { @@ -563,9 +710,9 @@ if ($action == 'create') $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); //For external user force the company to user company if (!empty($user->societe_id)) { - print $form->select_company($user->societe_id,'socid','',1,1,0,$events); + print $form->select_thirdparty_list($user->societe_id,'socid','',1,1,0,$events); } else { - print $form->select_company('','socid','',1,1,0,$events); + print $form->select_thirdparty_list('','socid','',1,1,0,$events); } } @@ -589,7 +736,7 @@ if ($action == 'create') $numproject=$formproject->select_projects((! empty($societe->id)?$societe->id:0),GETPOST("projectid")?GETPOST("projectid"):'','projectid'); if ($numproject==0) { - print '   '.$langs->trans("AddProject").''; + print '   '.$langs->trans("AddProject").''; } print ''; } @@ -612,7 +759,7 @@ if ($action == 'create') // Description print ''; @@ -641,45 +788,24 @@ if ($action == 'create') // View or edit if ($id > 0) { - if ($error) - { - dol_htmloutput_errors($error); - } - if ($mesg) - { - dol_htmloutput_mesg($mesg); - } + $result1=$object->fetch($id); + $result2=$object->fetch_thirdparty(); + $result3=$object->fetch_contact(); + $result4=$object->fetch_userassigned(); + $result5=$object->fetch_optionals($id,$extralabels); - $result=$object->fetch($id); - $object->fetch_optionals($id,$extralabels); - - if ($result < 0) + if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) { dol_print_error($db,$object->error); exit; } - $societe = new Societe($db); - if ($object->societe->id) - { - $result=$societe->fetch($object->societe->id); - } - $object->societe = $societe; + if ($object->authorid > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->authorid); $object->author=$tmpuser; } + if ($object->usermodid > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->usermodid); $object->usermod=$tmpuser; } - if ($object->author->id > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->author->id); $object->author=$tmpuser; } - if ($object->usermod->id > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->usermod->id); $object->usermod=$tmpuser; } - if ($object->usertodo->id > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->usertodo->id); $object->usertodo=$tmpuser; } - if ($object->userdone->id > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->userdone->id); $object->userdone=$tmpuser; } - - $contact = new Contact($db); - if ($object->contact->id) - { - $result=$contact->fetch($object->contact->id,$user); - } - $object->contact = $contact; /* - * Affichage onglets + * Show tabs */ $head=actions_prepare_head($object); @@ -690,7 +816,7 @@ if ($id > 0) // Confirmation suppression action if ($action == 'delete') { - print $form->formconfirm("fiche.php?id=".$id,$langs->trans("DeleteAction"),$langs->trans("ConfirmDeleteAction"),"confirm_delete",'','',1); + print $form->formconfirm("card.php?id=".$id,$langs->trans("DeleteAction"),$langs->trans("ConfirmDeleteAction"),"confirm_delete",'','',1); } if ($action == 'edit') @@ -721,13 +847,13 @@ if ($id > 0) print ''."\n"; } - // Fiche action en mode edition print ''; print ''; print ''; print ''; print ''; if ($backtopage) print ''; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) print ''; dol_fiche_head($head, 'card', $langs->trans("Action"),0,'action'); @@ -736,11 +862,11 @@ if ($id > 0) // Ref print ''; - // Type + // Type of event if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) { print ''; } @@ -766,33 +892,54 @@ if ($id > 0) // Status print ''; // Location - print ''; + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) + { + print ''; + } // Assigned to - print ''; - - print '
'.$langs->trans("Busy").''; - print 'transparency?' checked="checked"':'').'>'; + $listofuserid=array(); + if (empty($donotclearsession)) + { + $assignedtouser=GETPOST("assignedtouser")?GETPOST("assignedtouser"):(! empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : $user->id); + if ($assignedtouser) $listofuserid[$assignedtouser]=array('id'=>$assignedtouser,'mandatory'=>0,'transparency'=>$object->transparency); // Owner first + $_SESSION['assignedtouser']=dol_json_encode($listofuserid); + } + else + { + if (!empty($_SESSION['assignedtouser'])) + { + $listofuserid=dol_json_decode($_SESSION['assignedtouser'], true); + } + } + print $form->select_dolusers_forevent(($action=='create'?'add':'update'),'assignedtouser',1); + if (in_array($user->id,array_keys($listofuserid))) print $langs->trans("MyAvailability").': '.$langs->trans("Busy"); print '
'.$langs->trans("ActionDoneBy").''; - $form->select_users(GETPOST("doneby")?GETPOST("doneby"):(! empty($object->userdone->id) && $percent==100?$object->userdone->id:0),'doneby',1); + print $form->select_dolusers(GETPOST("doneby")?GETPOST("doneby"):(! empty($object->userdoneid) && $percent==100?$object->userdoneid:0),'doneby',1); print '
'.$langs->trans("Description").''; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('note',(GETPOST('note')?GETPOST('note'):$object->note),'',240,'dolibarr_notes','In',true,true,$conf->fckeditor->enabled,ROWS_7,90); + $doleditor=new DolEditor('note',(GETPOST('note')?GETPOST('note'):$object->note),'',180,'dolibarr_notes','In',true,true,$conf->fckeditor->enabled,ROWS_6,90); $doleditor->Create(); print '
'.$langs->trans("Ref").''.$object->id.'
'.$langs->trans("Type").''; - $htmlactions->select_type_actions(GETPOST("actioncode")?GETPOST("actioncode"):$object->type_code, "actioncode","systemauto"); + $formactions->select_type_actions(GETPOST("actioncode")?GETPOST("actioncode"):$object->type_code, "actioncode","systemauto"); print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; $percent=GETPOST("percentage")?GETPOST("percentage"):$object->percentage; - $htmlactions->form_select_status_action('formaction',$percent,1); + $formactions->form_select_status_action('formaction',$percent,1); print '
'.$langs->trans("Location").'
'.$langs->trans("Location").'
'.$langs->trans("ActionAffectedTo").''; - print $form->select_dolusers($object->usertodo->id>0?$object->usertodo->id:-1,'affectedto',1); - print '


'; - - // Busy - print ''; // Realised by - if ($conf->global->AGENDA_ENABLE_DONEBY) + if (! empty($conf->global->AGENDA_ENABLE_DONEBY)) { print ''; } - print '
'.$langs->trans("Busy").''; - print 'transparency?' checked="checked"':'').'">'; + print '
'.$langs->trans("ActionAssignedTo").''; + $listofuserid=array(); + if (empty($donotclearsession)) + { + if ($object->userownerid > 0) $listofuserid[$object->userownerid]=array('id'=>$object->userownerid,'transparency'=>$object->userassigned[$user->id]['transparency'],'answer_status'=>$object->userassigned[$user->id]['answer_status'],'mandatory'=>$object->userassigned[$user->id]['mandatory']); // Owner first + if (! empty($object->userassigned)) // Now concat assigned users + { + // Restore array with key with same value than param 'id' + $tmplist1=$object->userassigned; $tmplist2=array(); + foreach($tmplist1 as $key => $val) + { + if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']]=$val; + } + } + $_SESSION['assignedtouser']=dol_json_encode($listofuserid); + } + else + { + if (!empty($_SESSION['assignedtouser'])) + { + $listofuserid=dol_json_decode($_SESSION['assignedtouser'], true); + } + } + print $form->select_dolusers_forevent(($action=='create'?'add':'update'),'assignedtouser',1); + if (in_array($user->id,array_keys($listofuserid))) print $langs->trans("MyAvailability").': id]['transparency']?' checked="checked"':'').'">'.$langs->trans("Busy"); print '
'.$langs->trans("ActionDoneBy").''; - print $form->select_dolusers($object->userdone->id> 0?$object->userdone->id:-1,'doneby',1); + print $form->select_dolusers($object->userdoneid> 0?$object->userdoneid:-1,'doneby',1); print '


'; + print ''; + + print '

'; print ''; @@ -803,12 +950,12 @@ if ($id > 0) print ''; // Contact print ''; } @@ -822,10 +969,10 @@ if ($id > 0) $langs->load("project"); print ''; } @@ -895,100 +1042,102 @@ if ($id > 0) // Full day event print ''; + $rowspan=4; + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) $rowspan++; + // Date start - print ''; - print ''; print ''; // Date end - print ''; // Status - print ''; // Location - print ''; + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) + { + print ''; + } // Assigned to - print ''; - - print '
'; $events=array(); $events[]=array('method' => 'getContacts', 'url' => dol_buildpath('/core/ajax/contacts.php',1), 'htmlname' => 'contactid', 'params' => array('add-customer-contact' => 'disabled')); - print $form->select_company($object->societe->id,'socid','',1,1,0,$events); + print $form->select_company($object->socid,'socid','',1,1,0,$events); print ''.$langs->trans("Contact").''; - $form->select_contacts($object->societe->id, $object->contact->id,'contactid',1); + $form->select_contacts($object->socid, $object->contactid,'contactid',1); print '
'.$langs->trans("Project").''; - $numprojet=$formproject->select_projects($object->societe->id,$object->fk_project,'projectid'); + $numprojet=$formproject->select_projects($object->socid,$object->fk_project,'projectid'); if ($numprojet==0) { - print '   '.$langs->trans("AddProject").''; + print '   '.$langs->trans("AddProject").''; } print '
'.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent).'
'.$langs->trans("DateActionStart").''; + print '
'.$langs->trans("DateActionStart").''; if (! $object->fulldayevent) print dol_print_date($object->datep,'dayhour'); else print dol_print_date($object->datep,'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone"').' '; - print ''."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarweek','class="hideonsmartphone"').' '; - print '
'."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarday','class="hideonsmartphone"').' '; - print '
'."\n"; - print '
'.$langs->trans("DateActionEnd").''; + print '
'.$langs->trans("DateActionEnd").''; if (! $object->fulldayevent) print dol_print_date($object->datef,'dayhour'); else print dol_print_date($object->datef,'day'); if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now- $delay_warning)) print img_warning($langs->trans("Late")); print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; + print '
'.$langs->trans("Status").' / '.$langs->trans("Percentage").''; print $object->getLibStatut(4); print '
'.$langs->trans("Location").''.$object->location.'
'.$langs->trans("Location").''.$object->location.'
'.$langs->trans("ActionAffectedTo").''; - if ($object->usertodo->id > 0) print $object->usertodo->getNomUrl(1); - print '


'; - - // Busy - print ''; + print ''; // Done by if ($conf->global->AGENDA_ENABLE_DONEBY) { print ''; } - print '
'.$langs->trans("Busy").''; - if ($object->usertodo->id > 0) print yn(($object->transparency > 0)?1:0); // We show nothing if event is assigned to nobody - print '
'.$langs->trans("ActionAssignedTo").''; + $listofuserid=array(); + if (empty($donotclearsession)) + { + if ($object->userownerid > 0) $listofuserid[$object->userownerid]=array('id'=>$object->userownerid,'transparency'=>$object->transparency); // Owner first + if (! empty($object->userassigned)) // Now concat assigned users + { + // Restore array with key with same value than param 'id' + $tmplist1=$object->userassigned; $tmplist2=array(); + foreach($tmplist1 as $key => $val) + { + if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']]=$val; + } + } + $_SESSION['assignedtouser']=dol_json_encode($listofuserid); + } + else + { + if (!empty($_SESSION['assignedtouser'])) + { + $listofuserid=dol_json_decode($_SESSION['assignedtouser'], true); + } + } + print $form->select_dolusers_forevent('view','assignedtouser',1); + if (in_array($user->id,array_keys($listofuserid))) print $langs->trans("MyAvailability").': '.(($object->userassigned[$user->id]['transparency'] > 0)?$langs->trans("Busy"):$langs->trans("Available")); // We show nothing if event is assigned to nobody + print '
'.$langs->trans("ActionDoneBy").''; - if ($object->userdone->id > 0) print $object->userdone->getNomUrl(1); + if ($object->userdoneid > 0) + { + $tmpuser=new User($db); + $tmpuser->fetch($object->userdoneid); + print $tmpuser->getNomUrl(1); + } print '


'; + print '
'; + + print '

'; + + print ''; // Third party - Contact if ($conf->societe->enabled) { - print ''; print ''; print '\n"; } - print '
'.$langs->trans("ActionOnCompany").''.($object->societe->id?$object->societe->getNomUrl(1):$langs->trans("None")); - if ($object->societe->id && $object->type_code == 'AC_TEL') + print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); + if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { - if ($object->societe->fetch($object->societe->id)) + if ($object->thirdparty->fetch($object->thirdparty->id)) { - print "
".dol_print_phone($object->societe->phone); + print "
".dol_print_phone($object->thirdparty->phone); } } print '
'.$langs->trans("Contact").''; - if ($object->contact->id > 0) + if ($object->contactid > 0) { print $object->contact->getNomUrl(1); - if ($object->contact->id && $object->type_code == 'AC_TEL') + if ($object->contactid && $object->type_code == 'AC_TEL') { - if ($object->contact->fetch($object->contact->id)) + if ($object->contact->fetch($object->contactid)) { print "
".dol_print_phone($object->contact->phone_pro); } @@ -1049,7 +1198,7 @@ if ($id > 0) print $extrafields->showOutputField($key,$value); print "


'; + print ''; } dol_fiche_end(); @@ -1069,9 +1218,9 @@ if ($id > 0) if ($action != 'edit') { if ($user->rights->agenda->allactions->create || - (($object->author->id == $user->id || $object->usertodo->id == $user->id) && $user->rights->agenda->myactions->create)) + (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { - print ''; + print ''; } else { @@ -1079,9 +1228,9 @@ if ($id > 0) } if ($user->rights->agenda->allactions->delete || - (($object->author->id == $user->id || $object->usertodo->id == $user->id) && $user->rights->agenda->myactions->delete)) + (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->delete)) { - print ''; + print ''; } else { @@ -1091,6 +1240,76 @@ if ($id > 0) } print '
'; + + if ($action != 'edit') + { + // Link to agenda views + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarweek','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarday','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarperuser','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + + if (empty($conf->global->AGENDA_DISABLE_BUILDDOC)) + { + print '
 
'; + print ''; // ancre + + /* + * Documents generes + */ + + $filedir=$conf->agenda->multidir_output[$conf->entity].'/'.$object->id; + $urlsource=$_SERVER["PHP_SELF"]."?socid=".$object->id; + + $genallowed=$user->rights->agenda->myactions->create; + $delallowed=$user->rights->agenda->myactions->delete; + + $var=true; + + $somethingshown=$formfile->show_documents('agenda',$object->id,$filedir,$urlsource,$genallowed,$delallowed,'',0,0,0,0,0,'','','',$object->default_lang); + + print '
'; + + + print '
'; + + print '
 
'; + } + } } diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 360f38c3f45..15394c81a3a 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -39,36 +39,44 @@ class ActionComm extends CommonObject var $id; - var $type_id; // id into parent table llx_c_actioncomm (will be deprecated into future, link should not be required) - var $type_code; // code into parent table llx_c_actioncomm (will be deprecated into future, link should not be required). With defautl setup, should be AC_OTH_AUTO or AC_OTH - var $type; // label into parent table llx_c_actioncomm (will be deprecated into future, link should not be required) + var $type_id; // Id into parent table llx_c_actioncomm (used only if option to use type is set) + var $type_code; // Code into parent table llx_c_actioncomm (used only if option to use type is set). With default setup, should be AC_OTH_AUTO or AC_OTH. + var $type; // Label into parent table llx_c_actioncomm (used only if option to use type is set) + var $type_color; // Color into parent table llx_c_actioncomm (used only if option to use type is set) var $code; // Free code to identify action. Ie: Agenda trigger add here AC_TRIGGERNAME ('AC_COMPANY_CREATE', 'AC_PROPAL_VALIDATE', ...) var $label; var $datec; // Date creation record (datec) var $datem; // Date modification record (tms) - var $author; // Object user that create action - var $usermod; // Object user that modified action + var $author; // Object user that create action //deprecated + var $usermod; // Object user that modified action // deprecated + var $authorid; // Id user that create action + var $usermodid; // Id user that modified action var $datep; // Date action start (datep) var $datef; // Date action end (datep2) - var $durationp = -1; // -1=Unkown duration + var $durationp = -1; // -1=Unkown duration // deprecated var $fulldayevent = 0; // 1=Event on full day - var $punctual = 1; // Milestone + var $punctual = 1; // Milestone // deprecated. Milestone is already event with end date = start date var $percentage; // Percentage var $location; // Location + var $transparency; // Transparency (ical standard). Used to say if people assigned to event are busy or not by event. 0=available, 1=busy, 2=busy (refused events) var $priority; // Small int (0 By default) var $note; // Description - var $usertodo; // Object user that must do action - var $userdone; // Object user that did action + var $userassigned = array(); // Array of user ids + var $userownerid; // Id of user owner + var $userdoneid; // Id of user done + var $usertodo; // Object user of owner // deprecated + var $userdone; // Object user that did action // deprecated + var $socid; + var $contactid; var $societe; // Company linked to action (optional) var $contact; // Contact linked to action (optional) var $fk_project; // Id of project (optional) - // Properties for links to other objects var $fk_element; // Id of record var $elementtype; // Type of record. This if property ->element of object linked to. @@ -87,18 +95,17 @@ class ActionComm extends CommonObject */ function __construct($db) { + global $langs; + $this->db = $db; - $this->author = new stdClass(); - $this->usermod = new stdClass(); - $this->usertodo = new stdClass(); - $this->userdone = new stdClass(); - $this->societe = new stdClass(); - $this->contact = new stdClass(); + $this->societe = new stdClass(); // deprecated + $this->contact = new stdClass(); // deprecated } /** - * Add an action/event into database + * Add an action/event into database. + * $this->type_id OR $this->type_code must be set. * * @param User $user Object user making action * @param int $notrigger 1 = disable triggers, 0 = enable triggers @@ -122,7 +129,7 @@ class ActionComm extends CommonObject if (empty($this->transparency)) $this->transparency = 0; if ($this->percentage > 100) $this->percentage = 100; //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if (! empty($this->datep) && ! empty($this->datef)) $this->durationp=($this->datef - $this->datep); + if (! empty($this->datep) && ! empty($this->datef)) $this->durationp=($this->datef - $this->datep); // deprecated //if (! empty($this->date) && ! empty($this->dateend)) $this->durationa=($this->dateend - $this->date); if (! empty($this->datep) && ! empty($this->datef) && $this->datep > $this->datef) $this->datef=$this->datep; //if (! empty($this->date) && ! empty($this->dateend) && $this->date > $this->dateend) $this->dateend=$this->date; @@ -131,24 +138,29 @@ class ActionComm extends CommonObject if ($this->elementtype=='commande') $this->elementtype='order'; if ($this->elementtype=='contrat') $this->elementtype='contract'; - if (! $this->type_id && $this->type_code) + $userownerid=$this->userownerid; + $userdoneid=$this->userdoneid; + + if (! $this->type_id || ! $this->type_code) { + $key=empty($this->type_id)?$this->type_code:$this->type_id; + // Get id from code $cactioncomm=new CActionComm($this->db); - $result=$cactioncomm->fetch($this->type_code); + $result=$cactioncomm->fetch($key); if ($result > 0) { $this->type_id=$cactioncomm->id; - $this->code=$cactioncomm->code; + $this->type_code=$cactioncomm->code; } else if ($result == 0) { - $this->error='Failed to get record with code '.$this->type_code.' from dictionary "type of events"'; + $this->error='Failed to get record with id '.$this->type_id.' code '.$this->type_code.' from dictionary "type of events"'; return -1; } else - { + { $this->error=$cactioncomm->error; return -1; } @@ -167,7 +179,7 @@ class ActionComm extends CommonObject $sql.= "(datec,"; $sql.= "datep,"; $sql.= "datep2,"; - $sql.= "durationp,"; + $sql.= "durationp,"; // deprecated $sql.= "fk_action,"; $sql.= "code,"; $sql.= "fk_soc,"; @@ -186,16 +198,16 @@ class ActionComm extends CommonObject $sql.= "'".$this->db->idate($now)."',"; $sql.= (strval($this->datep)!=''?"'".$this->db->idate($this->datep)."'":"null").","; $sql.= (strval($this->datef)!=''?"'".$this->db->idate($this->datef)."'":"null").","; - $sql.= (isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->durationp."'":"null").","; + $sql.= (isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->durationp."'":"null").","; // deprecated $sql.= (isset($this->type_id)?$this->type_id:"null").","; - $sql.= (isset($this->code)?" '".$this->code."'":"null").","; - $sql.= (isset($this->societe->id) && $this->societe->id > 0?" '".$this->societe->id."'":"null").","; + $sql.= (isset($this->type_code)?" '".$this->type_code."'":"null").","; + $sql.= (isset($this->socid) && $this->socid > 0?" '".$this->socid."'":"null").","; $sql.= (isset($this->fk_project) && $this->fk_project > 0?" '".$this->fk_project."'":"null").","; $sql.= " '".$this->db->escape($this->note)."',"; - $sql.= (isset($this->contact->id) && $this->contact->id > 0?"'".$this->contact->id."'":"null").","; + $sql.= (isset($this->contactid) && $this->contactid > 0?"'".$this->contactid."'":"null").","; $sql.= (isset($user->id) && $user->id > 0 ? "'".$user->id."'":"null").","; - $sql.= (isset($this->usertodo->id) && $this->usertodo->id > 0?"'".$this->usertodo->id."'":"null").","; - $sql.= (isset($this->userdone->id) && $this->userdone->id > 0?"'".$this->userdone->id."'":"null").","; + $sql.= ($userownerid>0?"'".$userownerid."'":"null").","; + $sql.= ($userdoneid>0?"'".$userdoneid."'":"null").","; $sql.= "'".$this->db->escape($this->label)."','".$this->percentage."','".$this->priority."','".$this->fulldayevent."','".$this->db->escape($this->location)."','".$this->punctual."',"; $sql.= "'".$this->transparency."',"; $sql.= (! empty($this->fk_element)?$this->fk_element:"null").","; @@ -203,39 +215,59 @@ class ActionComm extends CommonObject $sql.= $conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::add sql=".$sql); + dol_syslog(get_class($this)."::add", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."actioncomm","id"); - // Actions on extra fields (by external module or standard code) - $hookmanager->initHooks(array('actioncommdao')); - $parameters=array('actcomm'=>$this->id); - $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if (empty($reshook)) + // Now insert assignedusers + if (! $error) + { + foreach($this->userassigned as $key => $val) + { + $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".($val['mandatory']?$val['mandatory']:'0').", ".($val['transparency']?$val['transparency']:'0').", ".($val['answer_status']?$val['answer_status']:'0').")"; + + $resql = $this->db->query($sql); + if (! $resql) + { + $error++; + $this->errors[]=$this->db->lasterror(); + } + //var_dump($sql);exit; + } + } + + if (! $error) { - if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used - { - $result=$this->insertExtraFields(); - if ($result < 0) - { - $error++; - } - } + $action='create'; + + // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('actioncommdao')); + $parameters=array('actcomm'=>$this->id); + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + else if ($reshook < 0) $error++; } - else if ($reshook < 0) $error++; if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ACTION_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ACTION_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -253,7 +285,6 @@ class ActionComm extends CommonObject { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::add ".$this->error,LOG_ERR); return -1; } @@ -263,9 +294,10 @@ class ActionComm extends CommonObject * Load object from database * * @param int $id Id of action to get + * @param string $ref Ref of action to get * @return int <0 if KO, >0 if OK */ - function fetch($id) + function fetch($id, $ref='') { global $langs; @@ -274,8 +306,8 @@ class ActionComm extends CommonObject $sql.= " a.ref_ext,"; $sql.= " a.datep,"; $sql.= " a.datep2,"; + $sql.= " a.durationp,"; // deprecated $sql.= " a.datec,"; - $sql.= " a.durationp,"; $sql.= " a.tms as datem,"; $sql.= " a.code, a.label, a.note,"; $sql.= " a.fk_soc,"; @@ -291,9 +323,11 @@ class ActionComm extends CommonObject $sql.= " FROM (".MAIN_DB_PREFIX."c_actioncomm as c, ".MAIN_DB_PREFIX."actioncomm as a)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_author"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = a.fk_soc"; - $sql.= " WHERE a.id=".$id." AND a.fk_action=c.id"; + $sql.= " WHERE a.fk_action=c.id"; + if ($ref) $sql.= " AND a.id=".$ref; // No field ref, we use id + else $sql.= " AND a.id=".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -316,6 +350,7 @@ class ActionComm extends CommonObject $this->label = $obj->label; $this->datep = $this->db->jdate($obj->datep); $this->datef = $this->db->jdate($obj->datep2); + $this->durationp = $this->durationp; // deprecated $this->datec = $this->db->jdate($obj->datec); $this->datem = $this->db->jdate($obj->datem); @@ -323,22 +358,30 @@ class ActionComm extends CommonObject $this->note = $obj->note; $this->percentage = $obj->percentage; - $this->author->id = $obj->fk_user_author; - $this->author->firstname = $obj->firstname; - $this->author->lastname = $obj->lastname; - $this->usermod->id = $obj->fk_user_mod; + $this->authorid = $obj->fk_user_author; + $this->usermodid = $obj->fk_user_mod; - $this->usertodo->id = $obj->fk_user_action; - $this->userdone->id = $obj->fk_user_done; + if (!is_object($this->author)) $this->author = new stdClass(); // For avoid warning + $this->author->id = $obj->fk_user_author; // deprecated + $this->author->firstname = $obj->firstname; // deprecated + $this->author->lastname = $obj->lastname; // deprecated + if (!is_object($this->usermod)) $this->usermod = new stdClass(); // For avoid warning + $this->usermod->id = $obj->fk_user_mod; // deprecated + + $this->userownerid = $obj->fk_user_action; + $this->userdoneid = $obj->fk_user_done; $this->priority = $obj->priority; $this->fulldayevent = $obj->fulldayevent; $this->location = $obj->location; $this->transparency = $obj->transparency; + $this->punctual = $obj->punctual; - $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working - $this->societe->id = $obj->fk_soc; - $this->contact->id = $obj->fk_contact; - $this->fk_project = $obj->fk_project; + $this->socid = $obj->fk_soc; // To have fetch_thirdparty method working + $this->contactid = $obj->fk_contact; // To have fetch_contact method working + $this->fk_project = $obj->fk_project; // To have fetch_project method working + + $this->societe->id = $obj->fk_soc; // deprecated + $this->contact->id = $obj->fk_contact; // deprecated $this->fk_element = $obj->fk_element; $this->elementtype = $obj->elementtype; @@ -353,6 +396,42 @@ class ActionComm extends CommonObject } } + + /** + * Initialize this->userassigned array with list of id of user assigned to event + * + * @return int <0 if KO, >0 if OK + */ + function fetch_userassigned() + { + global $langs; + + $sql.="SELECT fk_actioncomm, element_type, fk_element, answer_status, mandatory, transparency"; + $sql.=" FROM ".MAIN_DB_PREFIX."actioncomm_resources"; + $sql.=" WHERE element_type = 'user' AND fk_actioncomm = ".$this->id; + $resql2=$this->db->query($sql); + if ($resql2) + { + $this->userassigned=array(); + + // If owner is known, we must but id first into list + if ($this->userownerid > 0) $this->userassigned[$this->userownerid]=array('id'=>$this->userownerid); // Set first so will be first into list. + + while ($obj = $this->db->fetch_object($resql2)) + { + if ($obj->fk_element > 0) $this->userassigned[$obj->fk_element]=array('id'=>$obj->fk_element, 'mandatory'=>$obj->mandatory, 'answer_status'=>$obj->answer_status, 'transparency'=>$obj->transparency); + if (empty($this->userownerid)) $this->userownerid=$obj->fk_element; // If not defined (should not happened, we fix this) + } + + return 1; + } + else + { + dol_print_error($this->db); + return -1; + } + } + /** * Delete event from database * @@ -370,7 +449,7 @@ class ActionComm extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."actioncomm"; $sql.= " WHERE id=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $res=$this->db->query($sql); if ($res < 0) { $this->error=$this->db->lasterror(); @@ -391,14 +470,10 @@ class ActionComm extends CommonObject { if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ACTION_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ACTION_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -416,7 +491,6 @@ class ActionComm extends CommonObject { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error,LOG_ERR); return -1; } } @@ -444,19 +518,24 @@ class ActionComm extends CommonObject if (empty($this->fulldayevent)) $this->fulldayevent = 0; if ($this->percentage > 100) $this->percentage = 100; //if ($this->percentage == 100 && ! $this->dateend) $this->dateend = $this->date; - if ($this->datep && $this->datef) $this->durationp=($this->datef - $this->datep); + if ($this->datep && $this->datef) $this->durationp=($this->datef - $this->datep); // deprecated //if ($this->date && $this->dateend) $this->durationa=($this->dateend - $this->date); if ($this->datep && $this->datef && $this->datep > $this->datef) $this->datef=$this->datep; //if ($this->date && $this->dateend && $this->date > $this->dateend) $this->dateend=$this->date; if ($this->fk_project < 0) $this->fk_project = 0; // Check parameters - if ($this->percentage == 0 && $this->userdone->id > 0) + if ($this->percentage == 0 && $this->userdoneid > 0) { $this->error="ErrorCantSaveADoneUserWithZeroPercentage"; return -1; } + $socid=($this->socid?$this->socid:((isset($this->societe->id) && $this->societe->id > 0) ? $this->societe->id : 0)); + $contactid=($this->contactid?$this->contactid:((isset($this->contact->id) && $this->contact->id > 0) ? $this->contact->id : 0)); + $userownerid=($this->userownerid?$this->userownerid:0); + $userdoneid=($this->userdoneid?$this->userdoneid:0); + $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."actioncomm "; @@ -465,24 +544,29 @@ class ActionComm extends CommonObject $sql.= ", label = ".($this->label ? "'".$this->db->escape($this->label)."'":"null"); $sql.= ", datep = ".(strval($this->datep)!='' ? "'".$this->db->idate($this->datep)."'" : 'null'); $sql.= ", datep2 = ".(strval($this->datef)!='' ? "'".$this->db->idate($this->datef)."'" : 'null'); + $sql.= ", durationp = ".(isset($this->durationp) && $this->durationp >= 0 && $this->durationp != ''?"'".$this->durationp."'":"null"); // deprecated $sql.= ", note = ".($this->note ? "'".$this->db->escape($this->note)."'":"null"); - $sql.= ", fk_soc =". ($this->societe->id > 0 ? "'".$this->societe->id."'":"null"); $sql.= ", fk_project =". ($this->fk_project > 0 ? "'".$this->fk_project."'":"null"); - $sql.= ", fk_contact =". ($this->contact->id > 0 ? "'".$this->contact->id."'":"null"); + $sql.= ", fk_soc =". ($socid > 0 ? "'".$socid."'":"null"); + $sql.= ", fk_contact =". ($contactid > 0 ? "'".$contactid."'":"null"); $sql.= ", priority = '".$this->priority."'"; $sql.= ", fulldayevent = '".$this->fulldayevent."'"; $sql.= ", location = ".($this->location ? "'".$this->db->escape($this->location)."'":"null"); $sql.= ", transparency = '".$this->transparency."'"; $sql.= ", fk_user_mod = '".$user->id."'"; - $sql.= ", fk_user_action=".($this->usertodo->id > 0 ? "'".$this->usertodo->id."'":"null"); - $sql.= ", fk_user_done=".($this->userdone->id > 0 ? "'".$this->userdone->id."'":"null"); + $sql.= ", fk_user_action=".($userownerid > 0 ? "'".$userownerid."'":"null"); + $sql.= ", fk_user_done=".($userdoneid > 0 ? "'".$userdoneid."'":"null"); + if (! empty($this->fk_element)) $sql.= ", fk_element=".($this->fk_element?$this->fk_element:"null"); + if (! empty($this->elementtype)) $sql.= ", elementtype=".($this->elementtype?"'".$this->elementtype."'":"null"); $sql.= " WHERE id=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql); + dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { + $action='update'; // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('actioncommdao')); $parameters=array('actcomm'=>$this->id); $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks @@ -499,16 +583,33 @@ class ActionComm extends CommonObject } else if ($reshook < 0) $error++; - if (! $notrigger) + // Now insert assignedusers + if (! $error) + { + $sql ="DELETE FROM ".MAIN_DB_PREFIX."actioncomm_resources where fk_actioncomm = ".$this->id." AND element_type = 'user'"; + $resql = $this->db->query($sql); + + foreach($this->userassigned as $key => $val) + { + $sql ="INSERT INTO ".MAIN_DB_PREFIX."actioncomm_resources(fk_actioncomm, element_type, fk_element, mandatory, transparency, answer_status)"; + $sql.=" VALUES(".$this->id.", 'user', ".$val['id'].", ".($val['manadatory']?$val['manadatory']:'0').", ".($val['transparency']?$val['transparency']:'0').", ".($val['answer_status']?$val['answer_status']:'0').")"; + + $resql = $this->db->query($sql); + if (! $resql) + { + $error++; + $this->errors[]=$this->db->lasterror(); + } + //var_dump($sql);exit; + } + } + + if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ACTION_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ACTION_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -527,7 +628,6 @@ class ActionComm extends CommonObject { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); return -1; } } @@ -540,9 +640,11 @@ class ActionComm extends CommonObject * @param int $fk_element Id of element action is linked to * @param string $elementtype Type of element action is linked to * @param string $filter Other filter + * @param string $sortfield Sort on this field + * @param string $sortorder ASC or DESC * @return array or string Error string if KO, array with actions if OK */ - static function getActions($db, $socid=0, $fk_element=0, $elementtype='', $filter='') + static function getActions($db, $socid=0, $fk_element=0, $elementtype='', $filter='', $sortfield='', $sortorder='') { global $conf, $langs; @@ -558,8 +660,9 @@ class ActionComm extends CommonObject else $sql.= " AND a.fk_element = ".$fk_element." AND a.elementtype = '".$elementtype."'"; } if (! empty($filter)) $sql.= $filter; + if ($sortorder && $sortfield) $sql.=$db->order($sortfield, $sortorder); - dol_syslog(get_class()."::getActions sql=".$sql); + dol_syslog(get_class()."::getActions", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -645,7 +748,7 @@ class ActionComm extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; $sql.= ' WHERE a.id = '.$id; - dol_syslog(get_class($this)."::info sql=".$sql); + dol_syslog(get_class($this)."::info", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -755,8 +858,8 @@ class ActionComm extends CommonObject } /** - * Renvoie nom clicable (avec eventuellement le picto) - * Utilise $this->id, $this->code et $this->label + * Return URL of event + * Use $this->id, $this->type_code, $this->label and $this->type_label * * @param int $withpicto 0=Pas de picto, 1=Inclut le picto dans le lien, 2=Picto seul * @param int $maxlength Nombre de caracteres max dans libelle @@ -767,39 +870,34 @@ class ActionComm extends CommonObject */ function getNomUrl($withpicto=0,$maxlength=0,$classname='',$option='',$overwritepicto='') { - global $langs; + global $conf,$langs; $result=''; if ($option=='birthday') $lien = ''; - else $lien = ''; + else $lien = ''; $lienfin=''; $label=$this->label; - if (empty($label)) $label=$this->libelle; // Fro backward compatibility - //print 'rrr'.$this->libelle; + if (empty($label)) $label=$this->libelle; // For backward compatibility + //print 'rrr'.$this->libelle.'-'.$withpicto; if ($withpicto == 2) { $libelle=$label; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle=$langs->trans("Action".$this->type_code); + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle=$langs->transnoentities("Action".$this->type_code); $libelleshort=''; } - else if (empty($this->libelle)) - { - $libelle=$label; - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $libelle=$langs->trans("Action".$this->type_code); - $libelleshort=dol_trunc($label, $maxlength); - } else { - $libelle=$label; - $libelleshort=dol_trunc($label,$maxlength); + $libelle=(empty($this->libelle)?$label:$this->libelle.(($label && $label != $this->libelle)?' '.$label:'')); + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($libelle)) $libelle=($langs->transnoentities("Action".$this->type_code) != "Action".$this->type_code)?$langs->transnoentities("Action".$this->type_code):$this->type_label; + $libelleshort=dol_trunc($libelle,$maxlength); } if ($withpicto) { - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) // Add code into () { - $libelle.=(($this->type_code && $libelle!=$langs->trans("Action".$this->type_code) && $langs->trans("Action".$this->type_code)!="Action".$this->type_code)?' ('.$langs->trans("Action".$this->type_code).')':''); + $libelle.=(($this->type_code && $libelle!=$langs->transnoentities("Action".$this->type_code) && $langs->transnoentities("Action".$this->type_code)!="Action".$this->type_code)?' ('.$langs->transnoentities("Action".$this->type_code).')':''); } $result.=$lien.img_object($langs->trans("ShowAction").': '.$libelle,($overwritepicto?$overwritepicto:'action')).$lienfin; } @@ -870,7 +968,7 @@ class ActionComm extends CommonObject $sql = "SELECT a.id,"; $sql.= " a.datep,"; // Start $sql.= " a.datep2,"; // End - $sql.= " a.durationp,"; + $sql.= " a.durationp,"; // deprecated $sql.= " a.datec, a.tms as datem,"; $sql.= " a.label, a.code, a.note, a.fk_action as type_id,"; $sql.= " a.fk_soc,"; @@ -894,6 +992,7 @@ class ActionComm extends CommonObject if ($key == 'id') $sql.=" AND a.id=".(is_numeric($value)?$value:0); if ($key == 'idfrom') $sql.=" AND a.id >= ".(is_numeric($value)?$value:0); if ($key == 'idto') $sql.=" AND a.id <= ".(is_numeric($value)?$value:0); + if ($key == 'project') $sql.=" AND a.fk_project=".(is_numeric($value)?$value:0); if ($key == 'login') { $login=$value; @@ -931,7 +1030,7 @@ class ActionComm extends CommonObject $sql.= " ORDER by datep"; //print $sql;exit; - dol_syslog(get_class($this)."::build_exportfile select events sql=".$sql); + dol_syslog(get_class($this)."::build_exportfile select events", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -947,23 +1046,24 @@ class ActionComm extends CommonObject $event['type']=$type; $datestart=$this->db->jdate($obj->datep)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600)); $dateend=$this->db->jdate($obj->datep2)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600)); - $duration=$obj->durationp; + $duration=($datestart && $dateend)?($dateend - $datestart):0; $event['summary']=$obj->label.($obj->socname?" (".$obj->socname.")":""); $event['desc']=$obj->note; $event['startdate']=$datestart; - $event['duration']=$duration; // Not required with type 'journal' $event['enddate']=$dateend; // Not required with type 'journal' + $event['duration']=$duration; // Not required with type 'journal' $event['author']=dolGetFirstLastname($obj->firstname, $obj->lastname); $event['priority']=$obj->priority; $event['fulldayevent']=$obj->fulldayevent; $event['location']=$obj->location; $event['transparency']=(($obj->transparency > 0)?'OPAQUE':'TRANSPARENT'); // OPAQUE (busy) or TRANSPARENT (not busy) + $event['punctual']=$obj->punctual; $event['category']=$obj->libelle; // libelle type action // Define $urlwithroot $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root)); $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $url=$urlwithroot.'/comm/action/fiche.php?id='.$obj->id; + $url=$urlwithroot.'/comm/action/card.php?id='.$obj->id; $event['url']=$url; $event['created']=$this->db->jdate($obj->datec)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600)); $event['modified']=$this->db->jdate($obj->datem)-(empty($conf->global->AGENDA_EXPORT_FIX_TZ)?0:($conf->global->AGENDA_EXPORT_FIX_TZ*3600)); @@ -977,7 +1077,6 @@ class ActionComm extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::build_exportfile ".$this->db->lasterror(), LOG_ERR); return -1; } @@ -1043,7 +1142,7 @@ class ActionComm extends CommonObject */ function initAsSpecimen() { - global $user,$langs,$conf; + global $user,$langs,$conf,$user; $now=dol_now(); @@ -1064,9 +1163,12 @@ class ActionComm extends CommonObject $this->punctual=0; $this->percentage=0; $this->location='Location'; - $this->transparency=0; + $this->transparency=1; // 1 means opaque $this->priority=1; $this->note = 'Note'; + + $this->userownerid=$user->id; + $this->userassigned[$user->id]=array('id'=>$user->id, 'transparency'=> 1); } } diff --git a/htdocs/comm/action/class/cactioncomm.class.php b/htdocs/comm/action/class/cactioncomm.class.php index 68960c5a6c0..77dfea739e1 100644 --- a/htdocs/comm/action/class/cactioncomm.class.php +++ b/htdocs/comm/action/class/cactioncomm.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2005 Laurent Destailleur + * Copyright (C) 2004-2014 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 @@ -37,6 +37,7 @@ class CActionComm var $type; var $libelle; var $active; + var $color; var $type_actions=array(); @@ -59,12 +60,12 @@ class CActionComm */ function fetch($id) { - $sql = "SELECT id, code, type, libelle, active"; + $sql = "SELECT id, code, type, libelle, color, active"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; if (is_numeric($id)) $sql.= " WHERE id=".$id; else $sql.= " WHERE code='".$id."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -77,12 +78,13 @@ class CActionComm $this->type = $obj->type; $this->libelle = $obj->libelle; $this->active = $obj->active; + $this->color = $obj->color; $this->db->free($resql); return 1; } else - { + { $this->db->free($resql); return 0; } @@ -95,13 +97,13 @@ class CActionComm } /** - * Return list of event types + * Return list of event types: array(id=>label) or array(code=>label) * * @param int $active 1 or 0 to filter on event state active or not ('' by default = no filter) * @param string $idorcode 'id' or 'code' * @param string $excludetype Type to exclude * @param string $onlyautoornot Group list by auto events or not - * @return array Array of all event types if OK, <0 if KO + * @return mixed Array of all event types if OK, <0 if KO */ function liste_array($active='',$idorcode='id',$excludetype='',$onlyautoornot=0) { @@ -111,13 +113,13 @@ class CActionComm $repid = array(); $repcode = array(); - $sql = "SELECT id, code, libelle, module, type"; + $sql = "SELECT id, code, libelle, module, type, color"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm"; if ($active != '') $sql.=" WHERE active=".$active; if (! empty($excludetype)) $sql.=($active != ''?" AND":" WHERE")." type <> '".$excludetype."'"; $sql.= " ORDER BY module, position"; - dol_syslog(get_class($this)."::liste_array sql=".$sql); + dol_syslog(get_class($this)."::liste_array", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/comm/action/class/ical.class.php b/htdocs/comm/action/class/ical.class.php index 717d7269fa2..2dd6ea2b125 100644 --- a/htdocs/comm/action/class/ical.class.php +++ b/htdocs/comm/action/class/ical.class.php @@ -1,8 +1,8 @@ - * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2013 Laurent Destailleur - * Copyright (C) 2012 Regis Houssin +/* Copyright (C) 2006 Roman Ozana + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2013-2014 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -261,6 +261,7 @@ class ICal */ function ical_rrule($value) { + $result=aray(); $rrule = explode(';',$value); foreach ($rrule as $line) { @@ -299,6 +300,7 @@ class ICal */ function ical_dt_date($key, $value) { + $return_value=array(); $value = $this->ical_date_to_unix($value); // Analyse TZID @@ -309,8 +311,8 @@ class ICal $value = str_replace('T', '', $value); return array($key,$value); } - // adding $value and $tzid - $key = $temp[0]; + + $key = $temp[0]; $temp = explode("=", $temp[1]); $return_value[$temp[0]] = $temp[1]; $return_value['unixtime'] = $value; @@ -330,8 +332,9 @@ class ICal { usort($temp, array(&$this, "ical_dtstart_compare")); return $temp; - } else - { + } + else + { return false; } } diff --git a/htdocs/comm/action/class/index.html b/htdocs/comm/action/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/action/contact.php b/htdocs/comm/action/contact.php deleted file mode 100644 index 84b50893844..00000000000 --- a/htdocs/comm/action/contact.php +++ /dev/null @@ -1,260 +0,0 @@ - - * Copyright (C) 2004-2012 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2012 Philippe Grand - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/comm/action/contact.php - * \ingroup agenda - * \brief Page for multi-users event - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; -require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; -require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; - -$langs->load("companies"); -$langs->load("commercial"); -$langs->load("other"); -$langs->load("bills"); - -$id = GETPOST('id','int'); -$action = GETPOST('action','alpha'); -$ref = GETPOST('ref'); -$confirm = GETPOST('confirm'); -$lineid = GETPOST('lineid','int'); - -// Security check -$socid = GETPOST('socid','int'); -if ($user->societe_id) $socid=$user->societe_id; -if ($user->societe_id > 0) -{ - unset($_GET["action"]); - $action=''; -} -$result = restrictedArea($user, 'agenda', $objectid, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id'); - - -$object = new ActionComm($db); - - -/* - * Actions - */ - -// Add new contact -if ($action == 'addcontact' && $user->rights->action->creer) -{ - $result = $object->fetch($id); - - if ($object->id > 0) - { - $contactid = (GETPOST('userid','int') ? GETPOST('userid','int') : GETPOST('contactid','int')); - $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); - } - - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - $langs->load("errors"); - setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); - } - else - { - setEventMessage($object->error, 'errors'); - } - } -} - -// modification d'un contact. On enregistre le type -if ($action == 'updateline') -{ - if ($object->fetch($id)) - { - $contact = $object->detail_contact($_POST["line"]); - $type = $_POST["type"]; - $statut = $contact->statut; - - $result = $object->update_contact($_POST["line"], $statut, $type); - if ($result >= 0) - { - $db->commit(); - } else - { - dol_print_error($db, "result=$result"); - $db->rollback(); - } - } - else - { - setEventMessage($object->error, 'errors'); - } -} - -// Bascule du statut d'un contact -else if ($action == 'swapstatut') -{ - if ($object->id > 0) - { - $result=$object->swapContactStatus(GETPOST('ligne')); - } -} - -// Efface un contact -else if ($action == 'deletecontact') -{ - $result = $object->delete_contact($lineid); - - if ($result >= 0) - { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } - else - { - dol_print_error($db); - } -} - -/* - * View - */ - -$form = new Form($db); -$formcompany= new FormCompany($db); - -$contactstatic=new Contact($db); -$userstatic=new User($db); - -$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; -llxHeader('',$langs->trans("Agenda"),$help_url); - - -if ($id > 0 || ! empty($ref)) -{ - dol_htmloutput_mesg($mesg,$mesgs); - - if ($object->fetch($id,$ref) > 0) - { - - $head=actions_prepare_head($object); - dol_fiche_head($head, 'contact', $langs->trans("Action"),0,'action'); - - // Affichage fiche action en mode visu - print ''; - - $linkback = ''.$langs->trans("BackToList").''; - - // Ref - print ''; - - // Type - if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - print ''; - } - - // Title - print ''; - - // Full day event - print ''; - - // Date start - print ''; - print ''; - print ''; - - // Date end - print ''; - - // Location - print ''; - - print '
'.$langs->trans("Ref").''; - print $form->showrefnav($object, 'id', $linkback, ($user->societe_id?0:1), 'id', 'ref', ''); - print '
'.$langs->trans("Type").''.$object->type.'
'.$langs->trans("Title").''.$object->label.'
'.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent).'
'.$langs->trans("DateActionStart").''; - if (! $object->fulldayevent) print dol_print_date($object->datep,'dayhour'); - else print dol_print_date($object->datep,'day'); - if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); - print ''."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendar').' '; - print '
'."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarweek').' '; - print '
'."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarday').' '; - print '
'."\n"; - print '
'.$langs->trans("DateActionEnd").''; - if (! $object->fulldayevent) print dol_print_date($object->datef,'dayhour'); - else print dol_print_date($object->datef,'day'); - if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now- $delay_warning)) print img_warning($langs->trans("Late")); - print '
'.$langs->trans("Location").''.$object->location.'
'; - - dol_fiche_end(); - - print '
'; - - // Contacts lines (modules that overwrite templates must declare this into descriptor) - $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl')); - foreach($dirtpls as $reldir) - { - $res=@include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; - } - - } - else - { - print "ErrorRecordNotFound"; - } -} - -llxFooter(); - -$db->close(); - diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 694536b6d14..82d88089684 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -41,7 +41,7 @@ $langs->load("commercial"); $langs->load("other"); $langs->load("bills"); -$objectid = GETPOST('id', 'int'); +$id = GETPOST('id', 'int'); $action=GETPOST('action', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); @@ -53,19 +53,14 @@ if ($user->societe_id > 0) unset($_GET["action"]); $action=''; } -$result = restrictedArea($user, 'agenda', $objectid, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id'); +$result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id'); $object = new ActionComm($db); -if ($objectid > 0) +if ($id > 0) { - $ret = $object->fetch($objectid); - if ($ret > 0) { - $company=new Societe($db); - $company->fetch($object->societe->id); - $object->societe=$company; // For backward compatibility - $object->thirdparty=$company; - } + $ret = $object->fetch($id); + $object->fetch_thirdparty(); } // Get parameters @@ -101,13 +96,31 @@ llxHeader('',$langs->trans("Agenda"),$help_url); if ($object->id > 0) { + $result1=$object->fetch($id); + $result2=$object->fetch_thirdparty(); + $result3=$object->fetch_contact(); + $result4=$object->fetch_userassigned(); + $result5=$object->fetch_optionals($id,$extralabels); + + if ($result1 < 0 || $result2 < 0 || $result3 < 0 || $result4 < 0 || $result5 < 0) + { + dol_print_error($db,$object->error); + exit; + } + + if ($object->authorid > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->authorid); $object->author=$tmpuser; } + if ($object->usermodid > 0) { $tmpuser=new User($db); $res=$tmpuser->fetch($object->usermodid); $object->usermod=$tmpuser; } + $author=new User($db); $author->fetch($object->author->id); $object->author=$author; - if ($object->contact->id) $object->fetch_contact($object->contact->id); $head=actions_prepare_head($object); + + $now=dol_now(); + $delay_warning=$conf->global->MAIN_DELAY_ACTIONS_TODO*24*60*60; + dol_fiche_head($head, 'documents', $langs->trans("Action"),0,'action'); // Affichage fiche action en mode visu @@ -133,44 +146,15 @@ if ($object->id > 0) print ''.$langs->trans("EventOnFullDay").''.yn($object->fulldayevent).''; // Date start - print ''.$langs->trans("DateActionStart").''; + print ''.$langs->trans("DateActionStart").''; if (! $object->fulldayevent) print dol_print_date($object->datep,'dayhour'); else print dol_print_date($object->datep,'day'); if ($object->percentage == 0 && $object->datep && $object->datep < ($now - $delay_warning)) print img_warning($langs->trans("Late")); print ''; - print ''."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendar').' '; - print '
'."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarweek').' '; - print '
'."\n"; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - //print ''; - print img_picto($langs->trans("ViewCal"),'object_calendarday').' '; - print '
'."\n"; - print ''; print ''; // Date end - print ''.$langs->trans("DateActionEnd").''; + print ''.$langs->trans("DateActionEnd").''; if (! $object->fulldayevent) print dol_print_date($object->datef,'dayhour'); else print dol_print_date($object->datef,'day'); if ($object->percentage > 0 && $object->percentage < 100 && $object->datef && $object->datef < ($now- $delay_warning)) print img_warning($langs->trans("Late")); @@ -182,19 +166,49 @@ if ($object->id > 0) print ''; // Location - print ''.$langs->trans("Location").''.$object->location.''; + if (empty($conf->global->AGENDA_DISABLE_LOCATION)) + { + print ''.$langs->trans("Location").''.$object->location.''; + } + // Assigned to + print ''.$langs->trans("ActionAffectedTo").''; + $listofuserid=array(); + if (empty($donotclearsession)) + { + if ($object->userownerid > 0) $listofuserid[$object->userownerid]=array('id'=>$object->userownerid,'transparency'=>$object->transparency); // Owner first + if (! empty($object->userassigned)) // Now concat assigned users + { + // Restore array with key with same value than param 'id' + $tmplist1=$object->userassigned; $tmplist2=array(); + foreach($tmplist1 as $key => $val) + { + if ($val['id'] && $val['id'] != $object->userownerid) $listofuserid[$val['id']]=$val; + } + } + $_SESSION['assignedtouser']=dol_json_encode($listofuserid); + } + else + { + if (!empty($_SESSION['assignedtouser'])) + { + $listofuserid=dol_json_decode($_SESSION['assignedtouser'], true); + } + } + print $form->select_dolusers_forevent('view','assignedtouser',1); + if (in_array($user->id,array_keys($listofuserid))) print $langs->trans("MyAvailability").': '.(($object->userassigned[$user->id]['transparency'] > 0)?$langs->trans("Busy"):$langs->trans("Available")); // We show nothing if event is assigned to nobody + print ' '; print '

'; // Third party - Contact - print ''; @@ -236,8 +250,20 @@ if ($object->id > 0) print ($object->priority?$object->priority:''); print ''; + // Other attributes + $parameters=array('colspan'=>' colspan="3"', 'colspanvalue'=>'3', 'id'=>$object->id); + $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields,'edit'); + } - print '
'.$langs->trans("ActionOnCompany").''.($object->societe->id?$object->societe->getNomUrl(1):$langs->trans("None")); - if ($object->societe->id && $object->type_code == 'AC_TEL') + print '
'.$langs->trans("ActionOnCompany").''.($object->thirdparty->id?$object->thirdparty->getNomUrl(1):$langs->trans("None")); + if (is_object($object->thirdparty) && $object->thirdparty->id > 0 && $object->type_code == 'AC_TEL') { - if ($object->societe->fetch($object->societe->id)) + if ($object->thirdparty->fetch($object->thirdparty->id)) { - print "
".dol_print_phone($object->societe->phone); + print "
".dol_print_phone($object->thirdparty->phone); } } print '


'; + + print '
'; + + print '

'; + + print ''; // Construit liste des fichiers $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1); @@ -250,9 +276,59 @@ if ($object->id > 0) print ''; print ''; + print '
'.$langs->trans("NbOfAttachedFiles").''.count($filearray).'
'.$langs->trans("TotalSizeOfAttachedFiles").''.$totalsize.' '.$langs->trans("bytes").'
'; - print ''; + dol_fiche_end(); + + + + if ($action != 'edit') + { + // Link to agenda views + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendar','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarweek','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarday','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print img_picto($langs->trans("ViewCal"),'object_calendarperuser','class="hideonsmartphone"').' '; + print '
'."\n"; + print '
'; + + print '
'; + print "

"; + } + $modulepart = 'actions'; $permission = $user->rights->agenda->myactions->create||$user->rights->agenda->allactions->create; @@ -264,6 +340,7 @@ else print $langs->trans("ErrorUnknown"); } -$db->close(); llxFooter(); + +$db->close(); diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 38e8ab24bb1..4630d486ebf 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -1,9 +1,10 @@ * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2014 Cedric GROSS * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -42,8 +43,14 @@ $filter=GETPOST("filter",'',3); $filtera = GETPOST("userasked","int",3)?GETPOST("userasked","int",3):GETPOST("filtera","int",3); $filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3); $filterd = GETPOST("userdone","int",3)?GETPOST("userdone","int",3):GETPOST("filterd","int",3); +$usergroup = GETPOST("usergroup","int",3); $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; +// If not choice done on calendar owner, we filter on user. +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) +{ + $filtert=$user->id; +} $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); @@ -55,9 +62,10 @@ if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="a.datec"; // Security check -$socid = GETPOST("socid","int",1); +$socid = GETPOST("socid","int"); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); +if ($socid < 0) $socid=''; $canedit=1; if (! $user->rights->agenda->myactions->read) accessforbidden(); @@ -79,28 +87,36 @@ $pid=GETPOST("projectid","int",3); $status=GETPOST("status"); $type=GETPOST("type"); $maxprint=(isset($_GET["maxprint"])?GETPOST("maxprint"):$conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); -$actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_USE_EVENT_TYPE)?'AC_OTH':'')); +$actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':''); + +if ($actioncode == '') $actioncode=(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE); +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 (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week') { $action='show_month'; $day=''; } // View by month -if (GETPOST('viewweek')) { +if (GETPOST('viewweek') || $action == 'show_week') { $action='show_week'; $week=($week?$week:date("W")); $day=($day?$day:date("d")); } // View by week -if (GETPOST('viewday')) { +if (GETPOST('viewday') || $action == 'show_day') { $action='show_day'; $day=($day?$day:date("d")); } // View by day + $langs->load("agenda"); $langs->load("other"); $langs->load("commercial"); +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('agenda')); /* * Actions */ -if (GETPOST("viewlist")) + +if (GETPOST("viewlist") || $action == 'show_list') { $param=''; foreach($_POST as $key => $val) @@ -113,7 +129,20 @@ if (GETPOST("viewlist")) exit; } -if ($action=='delete_action') +if (GETPOST("viewperuser") || $action == 'show_peruser') +{ + $param=''; + foreach($_POST as $key => $val) + { + if ($key=='token') continue; + $param.='&'.$key.'='.urlencode($val); + } + //print $param; + header("Location: ".DOL_URL_ROOT.'/comm/action/peruser.php?'.$param); + exit; +} + +if ($action =='delete_action') { $event = new ActionComm($db); $event->fetch($actionid); @@ -134,10 +163,15 @@ $companystatic=new Societe($db); $contactstatic=new Contact($db); $now=dol_now(); +$nowarray=dol_getdate($now); +$nowyear=$nowarray['year']; +$nowmonth=$nowarray['mon']; +$nowday=$nowarray['mday']; -// Define list of all external calendars $listofextcals=array(); -if (empty($conf->global->AGENDA_DISABLE_EXT) && $conf->global->AGENDA_EXT_NB > 0) + +// Define list of external calendars (global admin setup) +if (empty($conf->global->AGENDA_DISABLE_EXT)) { $i=0; while($i < $conf->global->AGENDA_EXT_NB) @@ -154,7 +188,25 @@ if (empty($conf->global->AGENDA_DISABLE_EXT) && $conf->global->AGENDA_EXT_NB > 0 } } } - +// Define list of external calendars (user setup) +if (empty($user->conf->AGENDA_DISABLE_EXT)) +{ + $i=0; + while($i < $conf->global->AGENDA_EXT_NB) + { + $i++; + $source='AGENDA_EXT_SRC_'.$user->id.'_'.$i; + $name='AGENDA_EXT_NAME_'.$user->id.'_'.$i; + $color='AGENDA_EXT_COLOR_'.$user->id.'_'.$i; + $enabled='AGENDA_EXT_ENABLED_'.$user->id.'_'.$i; + $buggedfile='AGENDA_EXT_BUGGEDFILE_'.$user->id.'_'.$i; + if (! empty($user->conf->$source) && ! empty($user->conf->$name)) + { + // Note: $conf->global->buggedfile can be empty or 'uselocalandtznodaylight' or 'uselocalandtzdaylight' + $listofextcals[]=array('src'=>$user->conf->$source,'name'=>$user->conf->$name,'color'=>$user->conf->$color,'buggedfile'=>(isset($user->conf->buggedfile)?$user->conf->buggedfile:0)); + } + } +} if (empty($action) || $action=='show_month') { @@ -167,13 +219,13 @@ if (empty($action) || $action=='show_month') $max_day_in_prev_month = date("t",dol_mktime(0,0,0,$prev_month,1,$prev_year)); // Nb of days in previous month $max_day_in_month = date("t",dol_mktime(0,0,0,$month,1,$year)); // Nb of days in next month - // tmpday is a negative or null cursor to know how many days before the 1 to show on month view (if tmpday=0 we start on monday) - $tmpday = -date("w",dol_mktime(0,0,0,$month,1,$year))+2; + // tmpday is a negative or null cursor to know how many days before the 1st to show on month view (if tmpday=0, 1st is monday) + $tmpday = -date("w",dol_mktime(12,0,0,$month,1,$year,true))+2; // date('w') is 0 fo sunday $tmpday+=((isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)-1); - if ($tmpday >= 1) $tmpday -= 7; - // Define firstdaytoshow and lastdaytoshow + if ($tmpday >= 1) $tmpday -= 7; // If tmpday is 0 we start with sunday, if -6, we start with monday of previous week. + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) $firstdaytoshow=dol_mktime(0,0,0,$prev_month,$max_day_in_prev_month+$tmpday,$prev_year); - $next_day=7-($max_day_in_month+1-$tmpday)%7; + $next_day=7 - ($max_day_in_month+1-$tmpday) % 7; if ($next_day < 6) $next_day+=7; $lastdaytoshow=dol_mktime(0,0,0,$next_month,$next_day,$next_year); } @@ -186,6 +238,7 @@ if ($action=='show_week') $first_day = $prev['first_day']; $first_month= $prev['first_month']; $first_year = $prev['first_year']; + $week = $prev['week']; $day = (int) $day; @@ -194,7 +247,7 @@ if ($action=='show_week') $next_month = $next['month']; $next_day = $next['day']; - // Define firstdaytoshow and lastdaytoshow + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) $firstdaytoshow=dol_mktime(0,0,0,$first_month,$first_day,$first_year); $lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); @@ -213,7 +266,7 @@ if ($action == 'show_day') $next_month = $next['month']; $next_day = $next['day']; - // Define firstdaytoshow and lastdaytoshow + // Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) $firstdaytoshow=dol_mktime(0,0,0,$prev_month,$prev_day,$prev_year); $lastdaytoshow=dol_mktime(0,0,0,$next_month,$next_day,$next_year); } @@ -227,8 +280,8 @@ if ($status == 'done') $title=$langs->trans("DoneActions"); if ($status == 'todo') $title=$langs->trans("ToDoActions"); $param=''; -$region=''; -if ($status) $param="&status=".$status; +if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param.="&actioncode=".$actioncode; +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param.="&status=".$status; if ($filter) $param.="&filter=".$filter; if ($filtera) $param.="&filtera=".$filtera; if ($filtert) $param.="&filtert=".$filtert; @@ -236,34 +289,36 @@ if ($filterd) $param.="&filterd=".$filterd; if ($socid) $param.="&socid=".$socid; if ($showbirthday) $param.="&showbirthday=1"; if ($pid) $param.="&projectid=".$pid; -if ($actioncode != '') $param.="&actioncode=".$actioncode; if ($type) $param.="&type=".$type; -if ($action == 'show_day' || $action == 'show_week') $param.='&action='.$action; +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month') $param.='&action='.$action; $param.="&maxprint=".$maxprint; // Show navigation bar if (empty($action) || $action=='show_month') { - $nav ="".img_previous($langs->trans("Previous"))."\n"; + $nav ="".img_previous($langs->trans("Previous"))."\n"; $nav.=" ".dol_print_date(dol_mktime(0,0,0,$month,1,$year),"%b %Y"); $nav.=" \n"; - $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="   (".$langs->trans("Today").")"; $picto='calendar'; } if ($action=='show_week') { - $nav ="".img_previous($langs->trans("Previous"))."\n"; - $nav.=" ".dol_print_date(dol_mktime(0,0,0,$month,1,$year),"%Y").", ".$langs->trans("Week")." ".$week; + $nav ="".img_previous($langs->trans("Previous"))."\n"; + $nav.=" ".dol_print_date(dol_mktime(0,0,0,$first_month,$first_day,$first_year),"%Y").", ".$langs->trans("Week")." ".$week; $nav.=" \n"; - $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="   (".$langs->trans("Today").")"; $picto='calendarweek'; } if ($action=='show_day') { - $nav ="".img_previous($langs->trans("Previous"))."\n"; + $nav ="".img_previous($langs->trans("Previous"))."\n"; $nav.=" ".dol_print_date(dol_mktime(0,0,0,$month,$day,$year),"daytextshort"); $nav.=" \n"; - $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="".img_next($langs->trans("Next"))."\n"; + $nav.="   (".$langs->trans("Today").")"; $picto='calendarday'; } @@ -274,12 +329,61 @@ $param.='&year='.$year.'&month='.$month.($day?'&day='.$day:''); -$head = calendars_prepare_head(''); +$tabactive=''; +if ($action == 'show_month') $tabactive='cardmonth'; +if ($action == 'show_week') $tabactive='cardweek'; +if ($action == 'show_day') $tabactive='cardday'; +if ($action == 'show_list') $tabactive='cardlist'; -dol_fiche_head($head, 'card', $langs->trans('Events'), 0, $picto); -print_actions_filter($form,$canedit,$status,$year,$month,$day,$showbirthday,$filtera,$filtert,$filterd,$pid,$socid,$listofextcals,$actioncode); +$paramnoaction=preg_replace('/action=[a-z_]+/','',$param); + +$head = calendars_prepare_head($paramnoaction); + +dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); +print_actions_filter($form,$canedit,$status,$year,$month,$day,$showbirthday,$filtera,$filtert,$filterd,$pid,$socid,$action,$listofextcals,$actioncode,$usergroup); dol_fiche_end(); +$showextcals=$listofextcals; +// Legend +if ($conf->use_javascript_ajax) +{ + $s=''; + $s.='' . "\n"; + if (! empty($conf->use_javascript_ajax)) + { + $s.='
' . $langs->trans("LocalAgenda").'  
'; + if (is_array($showextcals) && count($showextcals) > 0) + { + foreach ($showextcals as $val) + { + $htmlname = dol_string_nospecial($val['name']); + $s.='' . "\n"; + $s.='
' . $val ['name'] . '  
'; + } + } + } + $s.='
'.$langs->trans("AgendaShowBirthdayEvents").'  
'; +} + + $link=''; // Add link to show birthdays if (empty($conf->use_javascript_ajax)) @@ -295,7 +399,7 @@ if (empty($conf->use_javascript_ajax)) $link.=''; } -print_fiche_titre($title,$link.'     '.$nav, ''); +print_fiche_titre($s,$link.'     '.$nav, ''); // Get event in an array @@ -308,18 +412,20 @@ $sql.= ' a.datea,'; $sql.= ' a.datea2,'; $sql.= ' a.percent,'; $sql.= ' a.fk_user_author,a.fk_user_action,a.fk_user_done,'; -$sql.= ' a.priority, a.fulldayevent, a.location,'; +$sql.= ' a.transparency, a.priority, a.fulldayevent, a.location,'; $sql.= ' a.fk_soc, a.fk_contact,'; -$sql.= ' ca.code'; -$sql.= ' FROM ('.MAIN_DB_PREFIX.'c_actioncomm as ca,'; -$sql.= " ".MAIN_DB_PREFIX."actioncomm as a)"; +$sql.= ' ca.code as type_code, ca.libelle as type_label'; +$sql.= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a"; if (! $user->rights->societe->client->voir && ! $socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if ($usergroup > 0) $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ugu"; $sql.= ' WHERE a.fk_action = ca.id'; $sql.= ' AND a.entity IN ('.getEntity('agenda', 1).')'; if ($actioncode) $sql.=" AND ca.code='".$db->escape($actioncode)."'"; if ($pid) $sql.=" AND a.fk_project=".$db->escape($pid); if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; -if ($user->societe_id) $sql.= ' AND a.fk_soc = '.$user->societe_id; // To limit to external user company +if ($socid > 0) $sql.= ' AND a.fk_soc = '.$socid; +// FIXME: We must filter on assignement table +if ($usergroup > 0) $sql.= " AND ugu.fk_user = a.fk_user_action"; if ($action == 'show_day') { $sql.= " AND ("; @@ -348,21 +454,26 @@ else $sql.= ')'; } if ($type) $sql.= " AND ca.id = ".$type; -if ($status == 'done') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } +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 == 'done' || $status == '100') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } if ($status == 'todo') { $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; } -if ($filtera > 0 || $filtert > 0 || $filterd > 0) +// FIXME: We must filter on assignement table +if ($filtera > 0 || $filtert > 0 || $filterd > 0 || $usergroup > 0) { $sql.= " AND ("; if ($filtera > 0) $sql.= " a.fk_user_author = ".$filtera; if ($filtert > 0) $sql.= ($filtera>0?" OR ":"")." a.fk_user_action = ".$filtert; if ($filterd > 0) $sql.= ($filtera>0||$filtert>0?" OR ":"")." a.fk_user_done = ".$filterd; + if ($usergroup > 0) $sql.= ($filtera>0||$filtert>0||$filterd>0?" OR ":"")." ugu.fk_usergroup = ".$usergroup; $sql.= ")"; } // Sort on date $sql.= ' ORDER BY datep'; //print $sql; -dol_syslog("comm/action/index.php sql=".$sql, LOG_DEBUG); +dol_syslog("comm/action/index.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -372,21 +483,29 @@ if ($resql) { $obj = $db->fetch_object($resql); + // Discard auto action if option is on + if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + { + $i++; + continue; + } + // Create a new object action $event=new ActionComm($db); $event->id=$obj->id; $event->datep=$db->jdate($obj->datep); // datep and datef are GMT date $event->datef=$db->jdate($obj->datep2); - $event->type_code=$obj->code; + $event->type_code=$obj->type_code; + $event->type_label=$obj->type_label; $event->libelle=$obj->label; $event->percentage=$obj->percent; - $event->author->id=$obj->fk_user_author; // user id of creator - $event->usertodo->id=$obj->fk_user_action; // user id of owner - $event->userdone->id=$obj->fk_user_done; // deprecated - // $event->userstodo=... with s after user, in future version, will be an array with all id of user assigned to event + $event->authorid=$obj->fk_user_author; // user id of creator + $event->userownerid=$obj->fk_user_action; // user id of owner + $event->fetch_userassigned(); // This load $event->userassigned $event->priority=$obj->priority; $event->fulldayevent=$obj->fulldayevent; $event->location=$obj->location; + $event->transparency=$obj->transparency; $event->societe->id=$obj->fk_soc; $event->contact->id=$obj->fk_contact; @@ -413,14 +532,14 @@ if ($resql) // Check values if ($event->date_end_in_calendar < $firstdaytoshow || - $event->date_start_in_calendar > $lastdaytoshow) + $event->date_start_in_calendar >= $lastdaytoshow) { // This record is out of visible range } else { if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=$lastdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); // Add an entry in actionarray for each day $daycursor=$event->date_start_in_calendar; @@ -473,7 +592,7 @@ if ($showbirthday) } $sql.= ' ORDER BY birthday'; - dol_syslog("comm/action/index.php sql=".$sql, LOG_DEBUG); + dol_syslog("comm/action/index.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -550,7 +669,7 @@ if (count($listofextcals)) if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event { //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=$lastdaytoshow; + //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); if ($icalevent['DTSTART;VALUE=DATE']) //fullday event { $datecurstart=dol_stringtotime($icalevent['DTSTART;VALUE=DATE'],1); @@ -589,10 +708,10 @@ if (count($listofextcals)) $until=empty($icalevent['RRULE']['UNTIL'])?0:dol_stringtotime($icalevent['RRULE']['UNTIL'],1); $maxrepeat=empty($icalevent['RRULE']['COUNT'])?0:$icalevent['RRULE']['COUNT']; if ($until && ($until+($datecurend-$datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart > $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show $numofevent=0; - while (($datecurstart <= $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) { if ($datecurend >= $firstdaytoshow) // We add event { @@ -724,7 +843,7 @@ if (count($listofextcals)) } // Add event into $eventarray if date range are ok. - if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar > $lastdaytoshow) + if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) { //print 'x'.$datestart.'-'.$dateend;exit; //print 'x'.$datestart.'-'.$dateend;exit; @@ -734,7 +853,7 @@ if (count($listofextcals)) else { if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; - if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=$lastdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow - 1); // Add an entry in actionarray for each day $daycursor=$event->date_start_in_calendar; @@ -748,8 +867,7 @@ if (count($listofextcals)) $daykey=dol_mktime(0,0,0,$mois,$jour,$annee); $daykeygmt=dol_mktime(0,0,0,$mois,$jour,$annee,true,0); do - //print 'x'.$datestart.'-'.$dateend;exit; - { + { //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; $eventarray[$daykey][]=$event; $daykey+=60*60*24; $daykeygmt+=60*60*24; // Add one day @@ -766,6 +884,7 @@ if (count($listofextcals)) $maxnbofchar=18; $cachethirdparties=array(); $cachecontacts=array(); +$cacheusers=array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php"; @@ -803,13 +922,12 @@ if (empty($action) || $action == 'show_month') // View by month // In loops, tmpday contains day nb in current month (can be zero or negative for days of previous month) //var_dump($eventarray); - //print $tmpday; for ($iter_week = 0; $iter_week < 6 ; $iter_week++) { echo " \n"; for ($iter_day = 0; $iter_day < 7; $iter_day++) { - /* Show days before the beginning of the current month (previous month) */ + /* Show days before the beginning of the current month (previous month) */ if ($tmpday <= 0) { $style='cal_other_month cal_past'; @@ -822,21 +940,20 @@ if (empty($action) || $action == 'show_month') // View by month elseif ($tmpday <= $max_day_in_month) { $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); - $style='cal_current_month'; if ($iter_day == 6) $style.=' cal_current_month_right'; $today=0; if ($todayarray['mday']==$tmpday && $todayarray['mon']==$month && $todayarray['year']==$year) $today=1; if ($today) $style='cal_today'; if ($curtime < $todaytms) $style.=' cal_past'; - + //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); echo ' '; show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo " \n"; } /* Show days after the current month (next month) */ else - { + { $style='cal_other_month'; if ($iter_day == 6) $style.=' cal_other_month_right'; echo ' '; @@ -848,6 +965,12 @@ if (empty($action) || $action == 'show_month') // View by month echo " \n"; } echo "\n"; + echo '
'; + echo ''; + echo ''; + echo '' ; + echo '
'; + } elseif ($action == 'show_week') // View by week { @@ -873,7 +996,7 @@ elseif ($action == 'show_week') // View by week echo " \n"; - for($iter_day = 0; $iter_day < 7; $iter_day++) + for ($iter_day = 0; $iter_day < 7; $iter_day++) { // Show days of the current week $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); @@ -896,6 +1019,11 @@ elseif ($action == 'show_week') // View by week echo " \n"; echo "\n"; + echo '
'; + echo ''; + echo ''; + echo '' ; + echo '
'; } else // View by day { @@ -905,20 +1033,20 @@ else // View by day $newparam=preg_replace('/viewday=[0-9]+&?/i','',$newparam); $newparam.='&viewday=1'; // Code to show just one day - $style='cal_current_month'; + $style='cal_current_month cal_current_month_oneday'; $today=0; $todayarray=dol_getdate($now,'fast'); if ($todayarray['mday']==$day && $todayarray['mon']==$month && $todayarray['year']==$year) $today=1; - if ($today) $style='cal_today'; + //if ($today) $style='cal_today'; $timestamp=dol_mktime(12,0,0,$month,$day,$year); $arraytimestamp=dol_getdate($timestamp); - echo ''; + echo '
'; echo ' '; echo ' \n"; echo " \n"; echo " \n"; - echo ' \n"; @@ -927,8 +1055,6 @@ else // View by day } -$db->close(); - /* TODO Export print ' @@ -945,6 +1071,8 @@ $("#actionagenda_vcal_link").attr("href","/public/agenda/agendaexport.php?format llxFooter(); +$db->close(); + /** * Show event of a particular day @@ -955,22 +1083,24 @@ llxFooter(); * @param int $year Year * @param int $monthshown Current month shown in calendar view * @param string $style Style to use for this day - * @param array $eventarray Array of events + * @param array $eventarray Array of events * @param int $maxprint Nb of actions to show each day on month view (0 means no limit) * @param int $maxnbofchar Nb of characters to show for event line * @param string $newparam Parameters on current URL - * @param int $showinfo Add extended information (used by day view) + * @param int $showinfo Add extended information (used by day and week view) * @param int $minheight Minimum height for each event. 60px by default. * @return void */ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint=0, $maxnbofchar=16, $newparam='', $showinfo=0, $minheight=60) { global $user, $conf, $langs; - global $filter, $filtera, $filtert, $filterd, $status, $actioncode; // Filters used into search form + global $action, $filter, $filtera, $filtert, $filterd, $status, $actioncode; // Filters used into search form global $theme_datacolor; - global $cachethirdparties, $cachecontacts, $colorindexused; + global $cachethirdparties, $cachecontacts, $cacheusers, $colorindexused; print '
'."\n"; + + // Line with title of day $curtime = dol_mktime(0, 0, 0, $month, $day, $year); print '
'.$langs->trans("Day".$arraytimestamp['wday'])."
'; + echo ' '; $maxnbofchar=80; show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); echo "
'; print ''; - print ''; print ''; + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } + // Origin of demand print '"; print ''; - print ''; + print ''; print "\n"; } } @@ -381,7 +381,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propale->lire) /* if (! empty($conf->propal->enabled)) { - $sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as name, s.rowid as socid"; $sql.=" FROM ".MAIN_DB_PREFIX."propal as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -399,7 +399,7 @@ if (! empty($conf->propal->enabled)) print '
'; @@ -978,7 +1108,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print 'action=show_day&day='.str_pad($day, 2, "0", STR_PAD_LEFT).'&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; print $newparam; print '">'; - if ($showinfo) print dol_print_date($curtime,'daytext'); + if ($showinfo) print dol_print_date($curtime,'daytextshort'); else print dol_print_date($curtime,'%d'); print ''; print ''; @@ -988,18 +1118,21 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa //$param='month='.$monthshown.'&year='.$year; $hourminsec='100000'; - print ''; + print ''; print img_picto($langs->trans("NewAction"),'edit_add.png'); print ''; } print '
'; + + // Line with td contains all div of each events + print '
'; + print '
'; //$curtime = dol_mktime (0, 0, 0, $month, $day, $year); $i=0; $nummytasks=0; $numother=0; $numbirthday=0; $numical=0; $numicals=array(); $ymd=sprintf("%04d",$year).sprintf("%02d",$month).sprintf("%02d",$day); - $nextindextouse=count($colorindexused); + $nextindextouse=count($colorindexused); // At first run this is 0, so fist user has 0, next 1, ... //print $nextindextouse; foreach ($eventarray as $daykey => $notused) @@ -1013,20 +1146,26 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa { if ($i < $maxprint || $maxprint == 0 || ! empty($conf->global->MAIN_JS_SWITCH_AGENDA)) { - $ponct=($event->date_start_in_calendar == $event->date_end_in_calendar); + $keysofuserassigned=array_keys($event->userassigned); - // Define $color and $cssclass of event + $ponct=($event->date_start_in_calendar == $event->date_end_in_calendar); + + // Define $color (Hex string like '0088FF') and $cssclass of event $color=-1; $cssclass=''; $colorindex=-1; - if ((! empty($event->author->id) && $event->author->id == $user->id) - || (! empty($event->usertodo->id) && $event->usertodo->id == $user->id) - || (! empty($event->userdone->id) && $event->userdone->id == $user->id)) - { - $nummytasks++; $cssclass='family_mytasks'; - // TODO Set a color using user color - // Must defined rule to choose color of who to use. - // event->usertodo->id will still contains user id of owner - // event->userstodo will be an array in future. - // $color=$user->color; + if (in_array($user->id, $keysofuserassigned)) + { + $nummytasks++; $cssclass='family_mytasks'; + + if (empty($cacheusers[$event->userownerid])) + { + $newuser=new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid]=$newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); + + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (! empty($cacheusers[$event->userownerid]->color)) $color=$cacheusers[$event->userownerid]->color; } else if ($event->type_code == 'ICALEVENT') { @@ -1038,35 +1177,80 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $numicals[dol_string_nospecial($event->icalname)]++; } $color=$event->icalcolor; - $cssclass=(! empty($event->icalname)?'family_'.dol_string_nospecial($event->icalname):'family_other'); + $cssclass=(! empty($event->icalname)?'family_'.dol_string_nospecial($event->icalname):'family_other unsortable'); } - else if ($event->type_code == 'BIRTHDAY') { $numbirthday++; $colorindex=2; $cssclass='family_birthday'; } - else { $numother++; $cssclass='family_other'; } + else if ($event->type_code == 'BIRTHDAY') + { + $numbirthday++; $colorindex=2; $cssclass='family_birthday unsortable'; $color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]); + } + else + { + $numother++; $cssclass='family_other'; + + if (empty($cacheusers[$event->userownerid])) + { + $newuser=new User($db); + $newuser->fetch($event->userownerid); + $cacheusers[$event->userownerid]=$newuser; + } + //var_dump($cacheusers[$event->userownerid]->color); + + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (! empty($cacheusers[$event->userownerid]->color)) $color=$cacheusers[$event->userownerid]->color; + } if ($color == -1) // Color was not forced. Set color according to color index. { // Define color index if not yet defined - $idusertouse=($event->usertodo->id?$event->usertodo->id:0); + $idusertouse=($event->userownerid?$event->userownerid:0); if (isset($colorindexused[$idusertouse])) { $colorindex=$colorindexused[$idusertouse]; // Color already assigned to this user } else { - $colorindex=$nextindextouse; - $colorindexused[$idusertouse]=$colorindex; + $colorindex=$nextindextouse; + $colorindexused[$idusertouse]=$colorindex; if (! empty($theme_datacolor[$nextindextouse+1])) $nextindextouse++; // Prepare to use next color } //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; // Define color $color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]); - } + } $cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd; + // Defined style to disable drag and drop feature + if ($event->date_end_in_calendar && date('Ymd',$event->date_start_in_calendar) != date('Ymd',$event->date_end_in_calendar)) + { + $tmpyearend = date('Y',$event->date_end_in_calendar); + $tmpmonthend = date('m',$event->date_end_in_calendar); + $tmpdayend = date('d',$event->date_end_in_calendar); + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) + { + $cssclass.= " unsortable"; + } + } + if ($event->type_code =='AC_OTH_AUTO') + { + $cssclass.= " unsortable"; + } + + $h=''; $nowrapontd=1; + if ($action == 'show_day') { $h='height: 100%; '; $nowrapontd=0; } + if ($action == 'show_week') { $h='height: 100%; '; $nowrapontd=0; } + // Show rect of event - print '
'; - print '
  • '; - print ''; - print ''; + } +} diff --git a/htdocs/comm/action/rapport/index.php b/htdocs/comm/action/rapport/index.php index 78f1ca24827..24eb117684f 100644 --- a/htdocs/comm/action/rapport/index.php +++ b/htdocs/comm/action/rapport/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2004-2009 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -37,9 +37,6 @@ $action=GETPOST('action','alpha'); $month=GETPOST('month'); $year=GETPOST('year'); -$mesg=''; -$mesgs=array(); - $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -58,13 +55,14 @@ $result = restrictedArea($user, 'agenda', $socid, '', 'myactions'); /* * Actions */ + if ($action == 'builddoc') { $cat = new CommActionRapport($db, $month, $year); $result=$cat->write_file(GETPOST('id','int')); if ($result < 0) { - $mesg=$cat->error; + setEventMessage($cat->error, 'errors'); } } @@ -82,22 +80,20 @@ $sql.= " date_format(a.datep, '%Y') as year"; $sql.= " FROM ".MAIN_DB_PREFIX."actioncomm as a,"; $sql.= " ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE a.fk_user_author = u.rowid"; -$sql.= " AND a.entity = ".$conf->entity; +$sql.= ' AND a.entity IN ('.getEntity('agenda', 1).')'; //$sql.= " AND percent = 100"; $sql.= " GROUP BY year, month, df"; $sql.= " ORDER BY year DESC, month DESC, df DESC"; $sql.= $db->plimit($limit+1,$offset); //print $sql; -dol_syslog("select sql=".$sql); +dol_syslog("select", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { $num = $db->num_rows($resql); - print_barre_liste($langs->trans("Actions"), $page, "index.php",'',$sortfield,$sortorder,'',$num); - - dol_htmloutput_mesg($mesg,$mesgs); + print_barre_liste($langs->trans("Actions"), $page, $_SERVER["PHP_SELF"],'',$sortfield,$sortorder,'',$num); $i = 0; print '
    '; + print '
    '; + print '
    • '; + print ''; + print ''; print '
      '; if ($event->type_code == 'BIRTHDAY') // It's a birthday { print $event->getNomUrl(1,$maxnbofchar,'cal_event','birthday','contact'); @@ -1133,7 +1317,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print "
      \n"; } else - { + { if ($showinfo) { print $langs->trans("EventOnFullDay")."
      \n"; @@ -1197,7 +1381,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa } else { - print ''."\n"; } + print ''; print '
      '; print '
    '."\n"; } + /** * Change color with a delta * @@ -1252,4 +1439,3 @@ function dol_color_minus($color, $minus) $newcolor[4]=((hexdec($newcolor[4])-$minus)<0)?0:dechex((hexdec($newcolor[4])-$minus)); return $newcolor; } - diff --git a/htdocs/comm/action/listactions.php b/htdocs/comm/action/listactions.php index 2c0c108b275..7fa67695860 100644 --- a/htdocs/comm/action/listactions.php +++ b/htdocs/comm/action/listactions.php @@ -42,13 +42,28 @@ $actioncode=GETPOST("actioncode","alpha",3); $pid=GETPOST("projectid",'int',3); $status=GETPOST("status",'alpha'); $type=GETPOST('type'); +$actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':(empty($conf->global->AGENDA_USE_EVENT_TYPE)?'AC_OTH':'')); +$dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth'), GETPOST('dateselectday'), GETPOST('dateselectyear')); +$datestart=dol_mktime(0, 0, 0, GETPOST('datestartmonth'), GETPOST('datestartday'), GETPOST('datestartyear')); +$dateend=dol_mktime(0, 0, 0, GETPOST('dateendmonth'), GETPOST('dateendday'), GETPOST('dateendyear')); + +if ($actioncode == '') $actioncode=(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE); +if ($status == '' && ! isset($_GET['status']) && ! isset($_POST['status'])) $status=(empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS)?'':$conf->global->AGENDA_DEFAULT_FILTER_STATUS); +if (empty($action) && ! isset($_GET['action']) && ! isset($_POST['action'])) $action=(empty($conf->global->AGENDA_DEFAULT_VIEW)?'show_month':$conf->global->AGENDA_DEFAULT_VIEW); $filter=GETPOST("filter",'',3); $filtera = GETPOST("userasked","int",3)?GETPOST("userasked","int",3):GETPOST("filtera","int",3); $filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3); $filterd = GETPOST("userdone","int",3)?GETPOST("userdone","int",3):GETPOST("filterd","int",3); +$usergroup = GETPOST("usergroup","int",3); $showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; +// If not choice done on calendar owner, we filter on user. +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) +{ + $filtert=$user->id; +} + $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -57,21 +72,22 @@ $limit = $conf->liste_limit; $offset = $limit * $page ; if (! $sortorder) { - $sortorder="ASC"; - if ($status == 'todo') $sortorder="ASC"; - if ($status == 'done') $sortorder="DESC"; + $sortorder="DESC"; + if ($status == 'todo') $sortorder="DESC"; + //if ($status == 'done') $sortorder="DESC"; } if (! $sortfield) { - $sortfield="a.percent"; + $sortfield="a.datep"; if ($status == 'todo') $sortfield="a.datep"; - if ($status == 'done') $sortfield="a.datep2"; + //if ($status == 'done') $sortfield="a.datep2"; } // Security check $socid = GETPOST("socid",'int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); +if ($socid < 0) $socid=''; $canedit=1; if (! $user->rights->agenda->myactions->read) accessforbidden(); @@ -83,11 +99,21 @@ if (! $user->rights->agenda->allactions->read || $filter=='mine') // If no permi $filterd=$user->id; } +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $datestart=''; + $dateend=''; +} + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('agendalist')); /* * Actions */ + if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) { $param=''; @@ -106,18 +132,25 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) * View */ +$form=new Form($db); + +$nav=''; +$nav.='  
    '; +$nav.=$form->select_date($dateselect, 'dateselect', 0, 0, 1, '', 1, 0, 1); +$nav.=' '; +$nav.='
    '; + $now=dol_now(); $help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('',$langs->trans("Agenda"),$help_url); -$form=new Form($db); - // Define list of all external calendars $listofextcals=array(); $param=''; -if ($status) $param="&status=".$status; +if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param.="&actioncode=".$actioncode; +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param.="&status=".$status; if ($filter) $param.="&filter=".$filter; if ($filtera) $param.="&filtera=".$filtera; if ($filtert) $param.="&filtert=".$filtert; @@ -126,15 +159,14 @@ if ($socid) $param.="&socid=".$socid; if ($showbirthday) $param.="&showbirthday=1"; if ($pid) $param.="&projectid=".$pid; if ($type) $param.="&type=".$type; -if ($actioncode) $param.="&actioncode=".$actioncode; $sql = "SELECT s.nom as societe, s.rowid as socid, s.client,"; $sql.= " a.id, a.datep as dp, a.datep2 as dp2,"; $sql.= " a.fk_contact, a.note, a.label, a.percent as percent,"; -$sql.= " c.code as acode, c.libelle,"; +$sql.= " c.code as type_code, c.libelle as type_label,"; $sql.= " ua.login as loginauthor, ua.rowid as useridauthor,"; $sql.= " ut.login as logintodo, ut.rowid as useridtodo,"; -$sql.= " ud.login as logindone, ud.rowid as useriddone,"; +//$sql.= " ud.login as logindone, ud.rowid as useriddone,"; $sql.= " sp.lastname, sp.firstname"; $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as c,"; $sql.= " ".MAIN_DB_PREFIX.'user as u,'; @@ -144,30 +176,41 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as ua ON a.fk_user_author = ua.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as ut ON a.fk_user_action = ut.rowid"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as ud ON a.fk_user_done = ud.rowid"; +//$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as ud ON a.fk_user_done = ud.rowid"; +if ($usergroup > 0) $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ugu"; $sql.= " WHERE c.id = a.fk_action"; $sql.= ' AND a.fk_user_author = u.rowid'; -$sql.= ' AND a.entity IN ('.getEntity().')'; // To limit to entity +$sql.= ' AND a.entity IN ('.getEntity('agenda', 1).')'; if ($actioncode) $sql.=" AND c.code='".$db->escape($actioncode)."'"; if ($pid) $sql.=" AND a.fk_project=".$db->escape($pid); if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; -if ($socid) $sql.= " AND s.rowid = ".$socid; +if ($socid > 0) $sql.= " AND s.rowid = ".$socid; +// FIXME: We must filter on assignement table +if ($usergroup > 0) $sql.= " AND ugu.fk_user = a.fk_user_action"; if ($type) $sql.= " AND c.id = ".$type; -if ($status == 'done') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } +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 == 'done' || $status == '100') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } if ($status == 'todo') { $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; } -if ($filtera > 0 || $filtert > 0 || $filterd > 0) +// FIXME: We must filter on assignement table +if ($filtera > 0 || $filtert > 0 || $filterd > 0 || $usergroup > 0) { - $sql.= " AND ("; - if ($filtera > 0) $sql.= " a.fk_user_author = ".$filtera; - if ($filtert > 0) $sql.= ($filtera>0?" OR ":"")." a.fk_user_action = ".$filtert; - if ($filterd > 0) $sql.= ($filtera>0||$filtert>0?" OR ":"")." a.fk_user_done = ".$filterd; - $sql.= ")"; + $sql.= " AND ("; + if ($filtera > 0) $sql.= " a.fk_user_author = ".$filtera; + if ($filtert > 0) $sql.= ($filtera>0?" OR ":"")." a.fk_user_action = ".$filtert; + if ($filterd > 0) $sql.= ($filtera>0||$filtert>0?" OR ":"")." a.fk_user_done = ".$filterd; + if ($usergroup > 0) $sql.= ($filtera>0||$filtert>0||$filterd>0?" OR ":"")." ugu.fk_usergroup = ".$usergroup; + $sql.= ")"; } +if ($dateselect > 0) $sql.= " AND a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect+3600*24-1)."'"; +if ($datestart > 0) $sql.= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart+3600*24-1)."'"; +if ($dateend > 0) $sql.= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend+3600*24-1)."'"; $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit + 1, $offset); //print $sql; -dol_syslog("comm/action/listactions.php sql=".$sql); +dol_syslog("comm/action/listactions.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -176,26 +219,20 @@ if ($resql) $num = $db->num_rows($resql); - $title=$langs->trans("DoneAndToDoActions"); + /*$title=$langs->trans("DoneAndToDoActions"); if ($status == 'done') $title=$langs->trans("DoneActions"); if ($status == 'todo') $title=$langs->trans("ToDoActions"); + */ + $title=$langs->trans("ListOfEvents"); - if ($socid) - { - $societe = new Societe($db); - $societe->fetch($socid); - $newtitle=$langs->trans($title).' '.$langs->trans("For").' '.$societe->nom; - } - else - { - $newtitle=$langs->trans($title); - } + $newtitle=$langs->trans($title); + $tabactive='cardlist'; - $head = calendars_prepare_head(''); + $head = calendars_prepare_head($param); - dol_fiche_head($head, 'card', $langs->trans('Events'), 0, 'list'); - print_actions_filter($form,$canedit,$status,$year,$month,$day,$showbirthday,$filtera,$filtert,$filterd,$pid,$socid,-1,$actioncode); + dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); + print_actions_filter($form,$canedit,$status,$year,$month,$day,$showbirthday,$filtera,$filtert,$filterd,$pid,$socid,$action,-1,$actioncode,$usergroup); dol_fiche_end(); // Add link to show birthdays @@ -215,9 +252,11 @@ if ($resql) } */ - print_barre_liste($newtitle, $page, $_SERVER["PHP_SELF"], $param,$sortfield,$sortorder,$link,$num,0,''); + print_barre_liste($newtitle, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $link, $num, 0, '', 0, $nav); //print '
    '; + print '
    '."\n"; + $i = 0; print ''; print ''; @@ -227,12 +266,29 @@ if ($resql) print_liste_field_titre($langs->trans("DateEnd"),$_SERVER["PHP_SELF"],"a.datep2",$param,'','align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom",$param,"","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("Contact"),$_SERVER["PHP_SELF"],"a.fk_contact",$param,"","",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ActionUserAsk"),$_SERVER["PHP_SELF"],"ua.login",$param,"","",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("AffectedTo"),$_SERVER["PHP_SELF"],"ut.login",$param,"","",$sortfield,$sortorder); + //print_liste_field_titre($langs->trans("ActionUserAsk"),$_SERVER["PHP_SELF"],"ua.login",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("ActionsOwnedBy"),$_SERVER["PHP_SELF"],"ut.login",$param,"","",$sortfield,$sortorder); //print_liste_field_titre($langs->trans("DoneBy"),$_SERVER["PHP_SELF"],"ud.login",$param,"","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"a.percent",$param,"",'align="right"',$sortfield,$sortorder); print "\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + //print ''; + print ''; + print ''; + print "\n"; + $contactstatic = new Contact($db); $now=dol_now(); $delay_warning=$conf->global->MAIN_DELAY_ACTIONS_TODO*24*60*60; @@ -242,6 +298,13 @@ if ($resql) { $obj = $db->fetch_object($resql); + // Discard auto action if option is on + if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') + { + $i++; + continue; + } + $var=!$var; print ""; @@ -249,14 +312,15 @@ if ($resql) // Action (type) print ''; // Start date print ''; // Third party @@ -276,7 +340,7 @@ if ($resql) { $societestatic->id=$obj->socid; $societestatic->client=$obj->client; - $societestatic->nom=$obj->societe; + $societestatic->name=$obj->societe; print $societestatic->getNomUrl(1,'',10); } else print ' '; @@ -298,6 +362,7 @@ if ($resql) print ''; // User author + /* print ''; + */ // User to do print '
    '; + print $form->select_date($datestart, 'datestart', 0, 0, 1, '', 1, 0, 1); + print ''; + print $form->select_date($dateend, 'dateend', 0, 0, 1, '', 1, 0, 1); + print ''; + print ''; + print '
    '; $actionstatic->id=$obj->id; - $actionstatic->type_code=$obj->acode; + $actionstatic->type_code=$obj->type_code; + $actionstatic->type_label=$obj->type_label; $actionstatic->libelle=$obj->label; print $actionstatic->getNomUrl(1,28); print ''; - print dol_print_date($db->jdate($obj->dp),"day"); + print dol_print_date($db->jdate($obj->dp),"dayhour"); $late=0; if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late=1; if ($obj->percent == 0 && ! $obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) $late=1; @@ -267,7 +331,7 @@ if ($resql) // End date print ''; - print dol_print_date($db->jdate($obj->dp2),"day"); + print dol_print_date($db->jdate($obj->dp2),"dayhour"); print ''; if ($obj->useridauthor) { @@ -308,6 +373,7 @@ if ($resql) } else print ' '; print ''; @@ -342,6 +408,9 @@ if ($resql) $i++; } print "
    "; + + print '
    '; + $db->free($resql); } diff --git a/htdocs/comm/action/peruser.php b/htdocs/comm/action/peruser.php new file mode 100644 index 00000000000..22cf8841c02 --- /dev/null +++ b/htdocs/comm/action/peruser.php @@ -0,0 +1,1042 @@ + + * Copyright (C) 2003 Eric Seigne + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2014 Cedric GROSS + * + * 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/comm/action/peruser.php + * \ingroup agenda + * \brief Tab of calendar events per user + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php'; +if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; + + +if (! isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW=3; + +$filter=GETPOST("filter",'',3); +$filtera = GETPOST("userasked","int",3)?GETPOST("userasked","int",3):GETPOST("filtera","int",3); +$filtert = GETPOST("usertodo","int",3)?GETPOST("usertodo","int",3):GETPOST("filtert","int",3); +$filterd = GETPOST("userdone","int",3)?GETPOST("userdone","int",3):GETPOST("filterd","int",3); +$usergroup = GETPOST("usergroup","int",3); +//if (! ($usergroup > 0) && ! ($filtert > 0)) $filtert = $user->id; +//$showbirthday = empty($conf->use_javascript_ajax)?GETPOST("showbirthday","int"):1; +$showbirthday = 0; + +// If not choice done on calendar owner, we filter on user. +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) +{ + $filtert=$user->id; +} + +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page","int"); +if ($page == -1) { $page = 0; } +$limit = $conf->liste_limit; +$offset = $limit * $page; +if (! $sortorder) $sortorder="ASC"; +if (! $sortfield) $sortfield="a.datec"; + +// Security check +$socid = GETPOST("socid","int"); +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'agenda', 0, '', 'myactions'); +if ($socid < 0) $socid=''; + +$canedit=1; +if (! $user->rights->agenda->myactions->read) accessforbidden(); +if (! $user->rights->agenda->allactions->read) $canedit=0; +if (! $user->rights->agenda->allactions->read || $filter =='mine') // If no permission to see all, we show only affected to me +{ + $filtera=$user->id; + $filtert=$user->id; + $filterd=$user->id; +} + +//$action=GETPOST('action','alpha'); +$action='show_peruser'; //We use 'show_week' mode +//$year=GETPOST("year"); +$year=GETPOST("year","int")?GETPOST("year","int"):date("Y"); +$month=GETPOST("month","int")?GETPOST("month","int"):date("m"); +$week=GETPOST("week","int")?GETPOST("week","int"):date("W"); +$day=GETPOST("day","int")?GETPOST("day","int"):date("d"); +$pid=GETPOST("projectid","int",3); +$status=GETPOST("status"); +$type=GETPOST("type"); +$maxprint=(isset($_GET["maxprint"])?GETPOST("maxprint"):$conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); +$actioncode=GETPOST("actioncode","alpha",3)?GETPOST("actioncode","alpha",3):(GETPOST("actioncode")=='0'?'0':''); + +$dateselect=dol_mktime(0, 0, 0, GETPOST('dateselectmonth'), GETPOST('dateselectday'), GETPOST('dateselectyear')); +if ($dateselect > 0) +{ + $day=GETPOST('dateselectday'); + $month=GETPOST('dateselectmonth'); + $year=GETPOST('dateselectyear'); +} + +$tmp=empty($conf->global->MAIN_DEFAULT_WORKING_HOURS)?'9-18':$conf->global->MAIN_DEFAULT_WORKING_HOURS; +$tmparray=explode('-',$tmp); +$begin_h = GETPOST('begin_h')!=''?GETPOST('begin_h','int'):($tmparray[0] != '' ? $tmparray[0] : 9); +$end_h = GETPOST('end_h')?GETPOST('end_h'):($tmparray[1] != '' ? $tmparray[1] : 18); +if ($begin_h < 0 || $begin_h > 23) $begin_h = 9; +if ($end_h < 1 || $end_h > 24) $end_h = 18; +if ($end_h <= $begin_h) $end_h = $begin_h + 1; + +$tmp=empty($conf->global->MAIN_DEFAULT_WORKING_DAYS)?'1-5':$conf->global->MAIN_DEFAULT_WORKING_DAYS; +$tmparray=explode('-',$tmp); +$begin_d = GETPOST('begin_d')?GETPOST('begin_d','int'):($tmparray[0] != '' ? $tmparray[0] : 1); +$end_d = GETPOST('end_d')?GETPOST('end_d'):($tmparray[1] != '' ? $tmparray[1] : 5); +if ($begin_d < 1 || $begin_d > 7) $begin_d = 1; +if ($end_d < 1 || $end_d > 7) $end_d = 7; +if ($end_d < $begin_d) $end_d = $begin_d + 1; + +if ($actioncode == '') $actioncode=(empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE)?'':$conf->global->AGENDA_DEFAULT_FILTER_TYPE); +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 (GETPOST('viewcal') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { + $action='show_month'; $day=''; +} // View by month +if (GETPOST('viewweek') || $action == 'show_week') { + $action='show_week'; $week=($week?$week:date("W")); $day=($day?$day:date("d")); +} // View by week +if (GETPOST('viewday') || $action == 'show_day') { + $action='show_day'; $day=($day?$day:date("d")); +} // View by day + + +$langs->load("agenda"); +$langs->load("other"); +$langs->load("commercial"); + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +$hookmanager->initHooks(array('agenda')); + + +/* + * Actions + */ + +if ($action =='delete_action') +{ + $event = new ActionComm($db); + $event->fetch($actionid); + $result=$event->delete(); +} + + + +/* + * View + */ + +$help_url='EN:Module_Agenda_En|FR:Module_Agenda|ES:Módulo_Agenda'; +llxHeader('',$langs->trans("Agenda"),$help_url); + +$form=new Form($db); +$companystatic=new Societe($db); + +$now=dol_now(); +$nowarray=dol_getdate($now); +$nowyear=$nowarray['year']; +$nowmonth=$nowarray['mon']; +$nowday=$nowarray['mday']; + + +// Define list of all external calendars (global setup) +$listofextcals=array(); + +$prev = dol_get_first_day_week($day, $month, $year); +$first_day = $prev['first_day']; +$first_month = $prev['first_month']; +$first_year = $prev['first_year']; + +$week = $prev['week']; + +$day = (int) $day; +$next = dol_get_next_week($day, $week, $month, $year); +$next_year = $next['year']; +$next_month = $next['month']; +$next_day = $next['day']; + +$max_day_in_month = date("t",dol_mktime(0,0,0,$month,1,$year)); + +$tmpday = $first_day; +//print 'xx'.$prev_year.'-'.$prev_month.'-'.$prev_day; +//print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; + +$title=$langs->trans("DoneAndToDoActions"); +if ($status == 'done') $title=$langs->trans("DoneActions"); +if ($status == 'todo') $title=$langs->trans("ToDoActions"); + +$param=''; +if ($actioncode || isset($_GET['actioncode']) || isset($_POST['actioncode'])) $param.="&actioncode=".$actioncode; +if ($status || isset($_GET['status']) || isset($_POST['status'])) $param.="&status=".$status; +if ($filter) $param.="&filter=".$filter; +if ($filtera) $param.="&filtera=".$filtera; +if ($filtert) $param.="&filtert=".$filtert; +if ($filterd) $param.="&filterd=".$filterd; +if ($usergroup) $param.="&usergroup=".$usergroup; +if ($socid) $param.="&socid=".$socid; +if ($showbirthday) $param.="&showbirthday=1"; +if ($pid) $param.="&projectid=".$pid; +if ($type) $param.="&type=".$type; +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param.='&action='.$action; +$param.="&maxprint=".$maxprint; + +$prev = dol_get_first_day_week($day, $month, $year); +$prev_year = $prev['prev_year']; +$prev_month = $prev['prev_month']; +$prev_day = $prev['prev_day']; +$first_day = $prev['first_day']; +$first_month= $prev['first_month']; +$first_year = $prev['first_year']; + +$week = $prev['week']; + +$day = (int) $day; +$next = dol_get_next_week($first_day, $week, $first_month, $first_year); +$next_year = $next['year']; +$next_month = $next['month']; +$next_day = $next['day']; + +// Define firstdaytoshow and lastdaytoshow (warning: lastdaytoshow is last second to show + 1) +$firstdaytoshow=dol_mktime(0,0,0,$first_month,$first_day,$first_year); +$lastdaytoshow=dol_time_plus_duree($firstdaytoshow, 7, 'd'); +//print dol_print_date($firstdaytoshow,'dayhour'); +//print dol_print_date($lastdaytoshow,'dayhour'); + +$max_day_in_month = date("t",dol_mktime(0,0,0,$month,1,$year)); + +$tmpday = $first_day; + +$nav ="".img_previous($langs->trans("Previous"))."\n"; +$nav.=" ".dol_print_date(dol_mktime(0,0,0,$first_month,$first_day,$first_year),"%Y").", ".$langs->trans("Week")." ".$week; +$nav.=" \n"; +$nav.="".img_next($langs->trans("Next"))."\n"; +$nav.="   (".$langs->trans("Today").")"; +$picto='calendarweek'; + +$nav.='  
    '; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; +$nav.=''; + +$nav.=$form->select_date($dateselect, 'dateselect', 0, 0, 1, '', 1, 0, 1); +$nav.=' '; +$nav.='
    '; + +// Must be after the nav definition +$param.='&year='.$year.'&month='.$month.($day?'&day='.$day:''); +//print 'x'.$param; + + + + +$tabactive=''; +if ($action == 'show_month') $tabactive='cardmonth'; +if ($action == 'show_week') $tabactive='cardweek'; +if ($action == 'show_day') $tabactive='cardday'; +if ($action == 'show_list') $tabactive='cardlist'; +if ($action == 'show_peruser') $tabactive='cardperuser'; + +$paramnoaction=preg_replace('/action=[a-z_]+/','',$param); + +$head = calendars_prepare_head($paramnoaction); + +dol_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); +print_actions_filter($form, $canedit, $status, $year, $month, $day, $showbirthday, $filtera, $filtert, $filterd, $pid, $socid, $action, $listofextcals, $actioncode, $usergroup); +dol_fiche_end(); + +$showextcals=$listofextcals; +// Legend +if ($conf->use_javascript_ajax) +{ + $s=''; + $s.='' . "\n"; + if (! empty($conf->use_javascript_ajax)) + { + $s.='
    ' . $langs->trans("LocalAgenda").'  
    '; + if (is_array($showextcals) && count($showextcals) > 0) + { + foreach ($showextcals as $val) + { + $htmlname = dol_string_nospecial($val['name']); + $s.='' . "\n"; + $s.='
    ' . $val ['name'] . '  
    '; + } + } + } + //$s.='
    '.$langs->trans("AgendaShowBirthdayEvents").'  
    '; +} + + + +$link=''; +print_fiche_titre($s,$link.'     '.$nav, ''); + + +// Get event in an array +$eventarray=array(); + +$sql = 'SELECT a.id,a.label,'; +$sql.= ' a.datep,'; +$sql.= ' a.datep2,'; +$sql.= ' a.datea,'; +$sql.= ' a.datea2,'; +$sql.= ' a.percent,'; +$sql.= ' a.fk_user_author,a.fk_user_action,a.fk_user_done,'; +$sql.= ' a.transparency, a.priority, a.fulldayevent, a.location,'; +$sql.= ' a.fk_soc, a.fk_contact, a.fk_element, a.elementtype,'; +$sql.= ' ca.code, ca.color'; +$sql.= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a"; +if (! $user->rights->societe->client->voir && ! $socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if ($usergroup > 0) $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ugu"; +$sql.= ' WHERE a.fk_action = ca.id'; +$sql.= ' AND a.entity IN ('.getEntity('agenda', 1).')'; +if ($actioncode) $sql.=" AND ca.code='".$db->escape($actioncode)."'"; +if ($pid) $sql.=" AND a.fk_project=".$db->escape($pid); +if (! $user->rights->societe->client->voir && ! $socid) $sql.= " AND (a.fk_soc IS NULL OR sc.fk_user = " .$user->id . ")"; +if ($socid > 0) $sql.= ' AND a.fk_soc = '.$socid; +// FIXME: We must filter on assignement table +if ($usergroup > 0) $sql.= " AND ugu.fk_user = a.fk_user_action"; +if ($action == 'show_day') +{ + $sql.= " AND ("; + $sql.= " (a.datep BETWEEN '".$db->idate(dol_mktime(0,0,0,$month,$day,$year))."'"; + $sql.= " AND '".$db->idate(dol_mktime(23,59,59,$month,$day,$year))."')"; + $sql.= " OR "; + $sql.= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0,0,0,$month,$day,$year))."'"; + $sql.= " AND '".$db->idate(dol_mktime(23,59,59,$month,$day,$year))."')"; + $sql.= " OR "; + $sql.= " (a.datep < '".$db->idate(dol_mktime(0,0,0,$month,$day,$year))."'"; + $sql.= " AND a.datep2 > '".$db->idate(dol_mktime(23,59,59,$month,$day,$year))."')"; + $sql.= ')'; +} +else +{ + // To limit array + $sql.= " AND ("; + $sql.= " (a.datep BETWEEN '".$db->idate(dol_mktime(0,0,0,$month,1,$year)-(60*60*24*7))."'"; // Start 7 days before + $sql.= " AND '".$db->idate(dol_mktime(23,59,59,$month,28,$year)+(60*60*24*10))."')"; // End 7 days after + 3 to go from 28 to 31 + $sql.= " OR "; + $sql.= " (a.datep2 BETWEEN '".$db->idate(dol_mktime(0,0,0,$month,1,$year)-(60*60*24*7))."'"; + $sql.= " AND '".$db->idate(dol_mktime(23,59,59,$month,28,$year)+(60*60*24*10))."')"; + $sql.= " OR "; + $sql.= " (a.datep < '".$db->idate(dol_mktime(0,0,0,$month,1,$year)-(60*60*24*7))."'"; + $sql.= " AND a.datep2 > '".$db->idate(dol_mktime(23,59,59,$month,28,$year)+(60*60*24*10))."')"; + $sql.= ')'; +} +if ($type) $sql.= " AND ca.id = ".$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 == 'done' || $status == '100') { $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep2 <= '".$db->idate($now)."'))"; } +if ($status == 'todo') { $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep2 > '".$db->idate($now)."'))"; } +// FIXME: We must filter on assignement table +if ($filtera > 0 || $filtert > 0 || $filterd > 0 || $usergroup > 0) +{ + $sql.= " AND ("; + if ($filtera > 0) $sql.= " a.fk_user_author = ".$filtera; + if ($filtert > 0) $sql.= ($filtera>0?" OR ":"")." a.fk_user_action = ".$filtert; + if ($filterd > 0) $sql.= ($filtera>0||$filtert>0?" OR ":"")." a.fk_user_done = ".$filterd; + if ($usergroup > 0) $sql.= ($filtera>0||$filtert>0||$filterd>0?" OR ":"")." ugu.fk_usergroup = ".$usergroup; + $sql.= ")"; +} +// Sort on date +$sql.= ' ORDER BY fk_user_action, datep'; //fk_user_action +//print $sql; + +dol_syslog("comm/action/index.php", LOG_DEBUG); +$resql=$db->query($sql); +if ($resql) +{ + $num = $db->num_rows($resql); + $i=0; + while ($i < $num) + { + $obj = $db->fetch_object($resql); + + // Discard auto action if option is on + if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->code == 'AC_OTH_AUTO') + { + $i++; + continue; + } + + // Create a new object action + $event=new ActionComm($db); + $event->id=$obj->id; + $event->datep=$db->jdate($obj->datep); // datep and datef are GMT date + $event->datef=$db->jdate($obj->datep2); + $event->type_code=$obj->code; + $event->type_color=$obj->color; + //$event->libelle=$obj->label; // deprecated + $event->label=$obj->label; + $event->percentage=$obj->percent; + //$event->author->id=$obj->fk_user_author; // user id of creator + $event->authorid=$obj->fk_user_author; // user id of creator + $event->userownerid=$obj->fk_user_action; // user id of owner + $event->fetch_userassigned(); // This load $event->userassigned + $event->priority=$obj->priority; + $event->fulldayevent=$obj->fulldayevent; + $event->location=$obj->location; + $event->transparency=$obj->transparency; + + $event->socid=$obj->fk_soc; + $event->contactid=$obj->fk_contact; + //$event->societe->id=$obj->fk_soc; // deprecated + //$event->contact->id=$obj->fk_contact; // deprecated + + $event->fk_element=$obj->fk_element; + $event->elementtype=$obj->elementtype; + + // Defined date_start_in_calendar and date_end_in_calendar property + // They are date start and end of action but modified to not be outside calendar view. + if ($event->percentage <= 0) + { + $event->date_start_in_calendar=$event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar=$event->datef; + else $event->date_end_in_calendar=$event->datep; + } + else + { + $event->date_start_in_calendar=$event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar=$event->datef; + else $event->date_end_in_calendar=$event->datep; + } + // Define ponctual property + if ($event->date_start_in_calendar == $event->date_end_in_calendar) + { + $event->ponctuel=1; + } + + // Check values + if ($event->date_end_in_calendar < $firstdaytoshow || + $event->date_start_in_calendar >= $lastdaytoshow) + { + // This record is out of visible range + } + else + { + if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; + if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow - 1); + + // Add an entry in actionarray for each day + $daycursor=$event->date_start_in_calendar; + $annee = date('Y',$daycursor); + $mois = date('m',$daycursor); + $jour = date('d',$daycursor); + + // Loop on each day covered by action to prepare an index to show on calendar + $loop=true; $j=0; + $daykey=dol_mktime(0,0,0,$mois,$jour,$annee); + do + { + //if ($event->id==408) print 'daykey='.$daykey.' '.$event->datep.' '.$event->datef.'
    '; + + $eventarray[$daykey][]=$event; + $j++; + + $daykey+=60*60*24; + if ($daykey > $event->date_end_in_calendar) $loop=false; + } + while ($loop); + + //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); + //print ' startincalendar='.dol_print_date($event->date_start_in_calendar).'-endincalendar='.dol_print_date($event->date_end_in_calendar).') was added in '.$j.' different index key of array
    '; + } + $i++; + + } +} +else +{ + dol_print_error($db); +} + +$maxnbofchar=18; +$cachethirdparties=array(); +$cachecontacts=array(); + +// Define theme_datacolor array +$color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php"; +if (is_readable($color_file)) +{ + include_once $color_file; +} +if (! is_array($theme_datacolor)) $theme_datacolor=array(array(120,130,150), array(200,160,180), array(190,190,220)); + + +$newparam=$param; // newparam is for birthday links +$newparam=preg_replace('/showbirthday=/i','showbirthday_=',$newparam); // To avoid replacement when replace day= is done +$newparam=preg_replace('/action=show_month&?/i','',$newparam); +$newparam=preg_replace('/action=show_week&?/i','',$newparam); +$newparam=preg_replace('/day=[0-9]+&?/i','',$newparam); +$newparam=preg_replace('/month=[0-9]+&?/i','',$newparam); +$newparam=preg_replace('/year=[0-9]+&?/i','',$newparam); +$newparam=preg_replace('/viewweek=[0-9]+&?/i','',$newparam); +$newparam=preg_replace('/showbirthday_=/i','showbirthday=',$newparam); // Restore correct parameter +$newparam.='&viewweek=1'; + +echo '
    '; +echo ''; +echo ''; +echo '' ; +echo '
    '; + + +// Table : +echo ''; + +echo ''; +echo ''; +$i=0; +while ($i < 7) +{ + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + echo '\n"; + $i++; +} +echo "\n"; + +echo ''; +echo ''; +$i=0; +while ($i < 7) +{ + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + for ($h = $begin_h; $h < $end_h; $h++) + { + echo '"; + } + echo "\n"; + $i++; +} +echo "\n"; + + +// Define $usernames +$usernames = array(); //init +$usernamesid = array(); +/* Use this to have list of users only if users have events */ +if (! empty($conf->global->AGENDA_SHOWOWNERONLY_ONPERUSERVIEW)) +{ + foreach ($eventarray as $daykey => $notused) + { + // Get all assigned users for each event + foreach ($eventarray[$daykey] as $index => $event) + { + $event->fetch_userassigned(); + $listofuserid=$event->userassigned; + foreach($listofuserid as $userid => $tmp) + { + if (! in_array($userid, $usernamesid)) $usernamesid[$userid] = $userid; + } + } + } +} +/* Use this list to have for all users */ +else +{ + $sql = "SELECT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity"; + $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; + if ($usergroup > 0) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug ON u.rowid = ug.fk_user"; + $sql.= " WHERE u.entity IN (".getEntity('user',1).")"; + if ($usergroup > 0) $sql.= " AND ug.fk_usergroup = ".$usergroup; + if (GETPOST("usertodo","int",3) > 0) $sql.=" AND u.rowid = ".GETPOST("usertodo","int",3); + //print $sql; + $resql=$db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($resql); + $usernamesid[$obj->rowid]=$obj->rowid; + $i++; + } + } + } + else dol_print_error($db); +} +//var_dump($usernamesid); +foreach($usernamesid as $id) +{ + $tmpuser=new User($db); + $result=$tmpuser->fetch($id); + $usernames[]=$tmpuser; +} + +/* +if ($filtert > 0) +{ + $tmpuser = new User($db); + $tmpuser->fetch($filtert); + $usernames[] = $tmpuser; +} +else if ($usergroup) +{ + $tmpgroup = new UserGroup($db); + $tmpgroup->fetch($usergroup); + $usernames = $tmpgroup->listUsersForGroup(); +} +else +{ + $tmpgroup = new UserGroup($db); + //$tmpgroup->fetch($usergroup); No fetch, we want all users for all groups + $usernames = $tmpgroup->listUsersForGroup(); +}*/ + +// Load array of colors by type +$colorsbytype=array(); +$labelbytype=array(); +$sql="SELECT code, color, libelle FROM ".MAIN_DB_PREFIX."c_actioncomm"; +$resql=$db->query($sql); +while ($obj = $db->fetch_object($resql)) +{ + $colorsbytype[$obj->code]=$obj->color; + $labelbytype[$obj->code]=$obj->libelle; +} + +// Loop on each user to show calendar +$todayarray=dol_getdate($now,'fast'); +$sav = $tmpday; +$showheader = true; +$var = false; +foreach ($usernames as $username) +{ + $var = ! $var; + echo ""; + echo ''; + $tmpday = $sav; + + // Lopp on each day of week + $i = 0; + for ($iter_day = 0; $iter_day < 7; $iter_day++) + { + if (($i + 1) < $begin_d || ($i + 1) > $end_d) + { + $i++; + continue; + } + + // Show days of the current week + $curtime = dol_time_plus_duree($firstdaytoshow, $iter_day, 'd'); + $tmparray = dol_getdate($curtime,'fast'); + $tmpday = $tmparray['mday']; + $tmpmonth = $tmparray['mon']; + $tmpyear = $tmparray['year']; + + $style='cal_current_month'; + if ($iter_day == 6) $style.=' cal_other_month'; + $today=0; + if ($todayarray['mday']==$tmpday && $todayarray['mon']==$tmpmonth && $todayarray['year']==$tmpyear) $today=1; + if ($today) $style='cal_today_peruser'; + + show_day_events2($username, $tmpday, $tmpmonth, $tmpyear, $monthshown, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, $showheader, $colorsbytype, $var); + + $i++; + } + echo "\n"; + $showheader = false; +} + +echo "
    '; + echo $langs->trans("Day".(($i+(isset($conf->global->MAIN_START_WEEK)?$conf->global->MAIN_START_WEEK:1)) % 7)); + print "
    "; + if ($i) print dol_print_date(dol_time_plus_duree($firstdaytoshow, $i, 'd'),'day'); + else print dol_print_date($firstdaytoshow,'day'); + echo "
    '; + print ''.sprintf("%02d",$h).''; + print "
    ' . $username->getNomUrl(1). '
    \n"; + + +if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) +{ + $langs->load("commercial"); + print '
    '.$langs->trans("Legend").':
    '; + foreach($colorsbytype as $code => $color) + { + if ($color) + { + print '
     
    '; + print $langs->trans("Action".$code)!="Action".$code?$langs->trans("Action".$code):$labelbytype[$code]; + //print $code; + print '
    '; + } + } + //$color=sprintf("%02x%02x%02x",$theme_datacolor[0][0],$theme_datacolor[0][1],$theme_datacolor[0][2]); + print '
     
    '; + print $langs->trans("Other"); + print '
    '; + /* TODO Show this if at least one cumulated event + print '
     
    '; + print $langs->trans("SeveralEvents"); + print '
    '; + */ +} + +// Add js code to manage click on a box +print ''; + + + +llxFooter(); + +$db->close(); + + + + +/** + * Show event of a particular day for a user + * + * @param string $username Login + * @param int $day Day + * @param int $month Month + * @param int $year Year + * @param int $monthshown Current month shown in calendar view + * @param string $style Style to use for this day + * @param array $eventarray Array of events + * @param int $maxprint Nb of actions to show each day on month view (0 means no limit) + * @param int $maxnbofchar Nb of characters to show for event line + * @param string $newparam Parameters on current URL + * @param int $showinfo Add extended information (used by day view) + * @param int $minheight Minimum height for each event. 60px by default. + * @param boolean $showheader Show header + * @param array $colorsbytype Array with colors by type + * @param string $var true or false for alternat style on tr/td + * @return void + */ +function show_day_events2($username, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint=0, $maxnbofchar=16, $newparam='', $showinfo=0, $minheight=60, $showheader=false, $colorsbytype=array(), $var=false) +{ + global $db; + global $user, $conf, $langs, $hookmanager, $action; + global $filter, $filtera, $filtert, $filterd, $status, $actioncode; // Filters used into search form + global $theme_datacolor; // Array with a list of different we can use (come from theme) + global $cachethirdparties, $cachecontacts, $colorindexused; + global $begin_h, $end_h; + + $cases1 = array(); // Color first half hour + $cases2 = array(); // Color second half hour + + $curtime = dol_mktime(0, 0, 0, $month, $day, $year); + + $i=0; $nummytasks=0; $numother=0; $numbirthday=0; $numical=0; $numicals=array(); + $ymd=sprintf("%04d",$year).sprintf("%02d",$month).sprintf("%02d",$day); + + $nextindextouse=count($colorindexused); // At first run, this is 0, so fist user has 0, next 1, ... + //if ($username->id && $day==1) var_dump($eventarray); + + // We are in a particular day for $username, now we scan all events + foreach ($eventarray as $daykey => $notused) + { + $annee = date('Y',$daykey); + $mois = date('m',$daykey); + $jour = date('d',$daykey); + //print $annee.'-'.$mois.'-'.$jour.' '.$year.'-'.$month.'-'.$day."
    \n"; + + if ($day==$jour && $month==$mois && $year==$annee) // Is it the day we are looking for when calling function ? + { + // Scan all event for this date + foreach ($eventarray[$daykey] as $index => $event) + { + $keysofuserassigned=array_keys($event->userassigned); + if (! in_array($username->id,$keysofuserassigned)) continue; // We discard record if event is from another user than user we want to show + //if ($username->id != $event->userownerid) continue; // We discard record if event is from another user than user we want to show + + $parameters=array(); + $reshook=$hookmanager->executeHooks('formatEvent',$parameters,$event,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + + $ponct=($event->date_start_in_calendar == $event->date_end_in_calendar); + + // Define $color (Hex string like '0088FF') and $cssclass of event + $color=-1; $cssclass=''; $colorindex=-1; + if (in_array($user->id, $keysofuserassigned)) + { + $nummytasks++; $cssclass='family_mytasks'; + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $color=$event->type_color; + } + else if ($event->type_code == 'ICALEVENT') + { + $numical++; + if (! empty($event->icalname)) + { + if (! isset($numicals[dol_string_nospecial($event->icalname)])) { + $numicals[dol_string_nospecial($event->icalname)] = 0; + } + $numicals[dol_string_nospecial($event->icalname)]++; + } + + $color=$event->icalcolor; + $cssclass=(! empty($event->icalname)?'family_'.dol_string_nospecial($event->icalname):'family_other unsortable'); + } + else if ($event->type_code == 'BIRTHDAY') + { + $numbirthday++; $colorindex=2; $cssclass='family_birthday unsortable'; $color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]); + } + else + { + $numother++; $cssclass='family_other'; + if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) $color=$event->type_color; + } + + if ($color < 0) // Color was not forced. Set color according to color index. + { + // Define color index if not yet defined + $idusertouse=($event->userownerid?$event->userownerid:0); + if (isset($colorindexused[$idusertouse])) + { + $colorindex=$colorindexused[$idusertouse]; // Color already assigned to this user + } + else + { + $colorindex=$nextindextouse; + $colorindexused[$idusertouse]=$colorindex; + if (! empty($theme_datacolor[$nextindextouse+1])) $nextindextouse++; // Prepare to use next color + } + // Define color + $color=sprintf("%02x%02x%02x",$theme_datacolor[$colorindex][0],$theme_datacolor[$colorindex][1],$theme_datacolor[$colorindex][2]); + } + //$cssclass=$cssclass.' '.$cssclass.'_day_'.$ymd; + + // Define all rects with event (cases1 is first half hour, cases2 is second half hour) + for ($h = $begin_h; $h < $end_h; $h++) + { + //if ($username->id == 1 && $day==1) print 'h='.$h; + $newcolor = ''; //init + if (empty($event->fulldayevent)) + { + $a = dol_mktime((int) $h,0,0,$month,$day,$year,false,false); + $b = dol_mktime((int) $h,30,0,$month,$day,$year,false,false); + $c = dol_mktime((int) $h+1,0,0,$month,$day,$year,false,false); + + $dateendtouse=$event->date_end_in_calendar; + if ($dateendtouse==$event->date_start_in_calendar) $dateendtouse++; + + //print dol_print_date($event->date_start_in_calendar,'dayhour').'-'.dol_print_date($a,'dayhour').'-'.dol_print_date($b,'dayhour').'
    '; + + if ($event->date_start_in_calendar < $b && $dateendtouse > $a) + { + $busy=$event->transparency; + $cases1[$h][$event->id]['busy']=$busy; + $cases1[$h][$event->id]['string']=dol_print_date($event->date_start_in_calendar,'dayhour'); + if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) + { + $tmpa=dol_getdate($event->date_start_in_calendar,true); + $tmpb=dol_getdate($event->date_end_in_calendar,true); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $cases1[$h][$event->id]['string'].='-'.dol_print_date($event->date_end_in_calendar,'hour'); + else $cases1[$h][$event->id]['string'].='-'.dol_print_date($event->date_end_in_calendar,'dayhour'); + } + $cases1[$h][$event->id]['string'].=' - '.$event->label; + $cases1[$h][$event->id]['typecode']=$event->type_code; + if ($event->socid) + { + //$cases1[$h][$event->id]['string'].='xxx'; + } + $cases1[$h][$event->id]['color']=$color; + } + if ($event->date_start_in_calendar < $c && $dateendtouse > $b) + { + $busy=$event->transparency; + $cases2[$h][$event->id]['busy']=$busy; + $cases2[$h][$event->id]['string']=dol_print_date($event->date_start_in_calendar,'dayhour'); + if ($event->date_end_in_calendar && $event->date_end_in_calendar != $event->date_start_in_calendar) + { + $tmpa=dol_getdate($event->date_start_in_calendar,true); + $tmpb=dol_getdate($event->date_end_in_calendar,true); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) $cases2[$h][$event->id]['string'].='-'.dol_print_date($event->date_end_in_calendar,'hour'); + else $cases2[$h][$event->id]['string'].='-'.dol_print_date($event->date_end_in_calendar,'dayhour'); + } + $cases2[$h][$event->id]['string'].=' - '.$event->label; + $cases2[$h][$event->id]['typecode']=$event->type_code; + if ($event->socid) + { + //$cases2[$h][$event->id]['string'].='xxx'; + } + $cases2[$h][$event->id]['color']=$color; + } + } + else + { + $busy=$event->transparency; + $cases1[$h][$event->id]['busy']=$busy; + $cases2[$h][$event->id]['busy']=$busy; + $cases1[$h][$event->id]['string']=$event->label; + $cases2[$h][$event->id]['string']=$event->label; + $cases1[$h][$event->id]['typecode']=$event->type_code; + $cases2[$h][$event->id]['typecode']=$event->type_code; + $cases1[$h][$event->id]['color']=$color; + $cases2[$h][$event->id]['color']=$color; + } + } + $i++; + } + + break; // We found the date we were looking for. No need to search anymore. + } + } + + for ($h = $begin_h; $h < $end_h; $h++) + { + $color1='';$color2=''; + $style1='';$style2=''; + $string1=' ';$string2=' '; + $title1='';$title2=''; + if (isset($cases1[$h]) && $cases1[$h] != '') + { + //$title1.=count($cases1[$h]).' '.(count($cases1[$h])==1?$langs->trans("Event"):$langs->trans("Events")); + if (count($cases1[$h]) > 1) $title1.=count($cases1[$h]).' '.(count($cases1[$h])==1?$langs->trans("Event"):$langs->trans("Events")); + $string1=' '; + if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) $style1='peruser_notbusy'; + else $style1='peruser_busy'; + foreach($cases1[$h] as $id => $ev) + { + if ($ev['busy']) $style1='peruser_busy'; + } + } + if (isset($cases2[$h]) && $cases2[$h] != '') + { + //$title2.=count($cases2[$h]).' '.(count($cases2[$h])==1?$langs->trans("Event"):$langs->trans("Events")); + if (count($cases2[$h]) > 1) $title2.=count($cases2[$h]).' '.(count($cases2[$h])==1?$langs->trans("Event"):$langs->trans("Events")); + $string2=' '; + if (empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) $style2='peruser_notbusy'; + else $style2='peruser_busy'; + foreach($cases2[$h] as $id => $ev) + { + if ($ev['busy']) $style2='peruser_busy'; + } + } + + + if ($h == $begin_h) echo '
    '; + else echo ''; + if (count($cases1[$h]) == 1) // 1 seul evenement + { + $ids=array_keys($cases1[$h]); + $output = array_slice($cases1[$h], 0, 1); + if ($output[0]['string']) $title1.=($title1?' - ':'').$output[0]['string']; + if ($output[0]['color']) $color1 = $output[0]['color']; + } + else if (count($cases1[$h]) > 1) $color1='222222'; + + if (count($cases2[$h]) == 1) // 1 seul evenement + { + $ids=array_keys($cases2[$h]); + $output = array_slice($cases2[$h], 0, 1); + if ($output[0]['string']) $title2.=($title2?' - ':'').$output[0]['string']; + if ($output[0]['color']) $color2 = $output[0]['color']; + } + else if (count($cases2[$h]) > 1) $color2='222222'; + $ids1='';$ids2=''; + if (count($cases1[$h]) && array_keys($cases1[$h])) $ids1=join(',',array_keys($cases1[$h])); + if (count($cases2[$h]) && array_keys($cases2[$h])) $ids2=join(',',array_keys($cases2[$h])); + //var_dump($cases1[$h]); + print ''; + print ''; + print '
    '; + print $string1; + print ''; + print $string2; + print '
    '; + print '
    '; diff --git a/htdocs/comm/address.php b/htdocs/comm/address.php index 8e892845c66..0ffcb351500 100644 --- a/htdocs/comm/address.php +++ b/htdocs/comm/address.php @@ -95,7 +95,7 @@ if ($action == 'add' || $action == 'update') } elseif ($origin == 'shipment') { - header("Location: ../expedition/fiche.php?id=".$originid); + header("Location: ../expedition/card.php?id=".$originid); exit; } else @@ -106,7 +106,7 @@ if ($action == 'add' || $action == 'update') } else { - $mesg = $object->error; + setEventMessage($object->error, 'errors'); $action='create'; } } @@ -135,7 +135,7 @@ if ($action == 'add' || $action == 'update') } elseif ($origin == 'shipment') { - header("Location: ../expedition/fiche.php?id=".$originid); + header("Location: ../expedition/card.php?id=".$originid); exit; } else @@ -147,8 +147,8 @@ if ($action == 'add' || $action == 'update') else { $reload = 0; - $mesg = $object->error; - $actino= "edit"; + setEventMessage($object->error, 'errors'); + $action= "edit"; } } @@ -181,9 +181,6 @@ $form = new Form($db); $formcompany = new FormCompany($db); $countrynotdefined=$langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -dol_htmloutput_errors($mesg); - - if ($action == 'create') { if ($user->rights->societe->creer) @@ -307,7 +304,7 @@ elseif ($action == 'edit') $societe->fetch($socid); $head = societe_prepare_head($societe); - dol_fiche_head($head, 'card', $societe->nom); + dol_fiche_head($head, 'card', $societe->name); print_titre($langs->trans("EditAddress")); print "
    \n"; @@ -410,7 +407,7 @@ else $societe->fetch($object->socid); $head = societe_prepare_head($societe); - dol_fiche_head($head, 'customer', $societe->nom); + dol_fiche_head($head, 'customer', $societe->name); // Confirmation delete diff --git a/htdocs/comm/admin/index.html b/htdocs/comm/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/admin/propal_extrafields.php b/htdocs/comm/admin/propal_extrafields.php index 434d2fc1972..2a1a2286db5 100644 --- a/htdocs/comm/admin/propal_extrafields.php +++ b/htdocs/comm/admin/propal_extrafields.php @@ -36,7 +36,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -69,7 +69,7 @@ $linkback=''.$langs->trans("BackToM print_fiche_titre($langs->trans("PropalSetup"),$linkback,'setup'); -$head = propal_admin_prepare_head(null); +$head = propal_admin_prepare_head(); dol_fiche_head($head, 'attributes', $langs->trans("Proposals"), 0, 'propal'); diff --git a/htdocs/comm/admin/propaldet_extrafields.php b/htdocs/comm/admin/propaldet_extrafields.php index c9c28105466..40dbad4ef94 100644 --- a/htdocs/comm/admin/propaldet_extrafields.php +++ b/htdocs/comm/admin/propaldet_extrafields.php @@ -43,7 +43,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -74,7 +74,7 @@ llxHeader('',$langs->trans("PropalSetup")); $linkback=''.$langs->trans("BackToModuleList").''; print_fiche_titre($langs->trans("PropalSetup"),$linkback,'setup'); -$head = propal_admin_prepare_head(null); +$head = propal_admin_prepare_head(); dol_fiche_head($head, 'attributeslines', $langs->trans("Proposals"), 0, 'propal'); diff --git a/htdocs/comm/fiche.php b/htdocs/comm/card.php similarity index 91% rename from htdocs/comm/fiche.php rename to htdocs/comm/card.php index 7ba1cc8bc48..8a4df52748c 100644 --- a/htdocs/comm/fiche.php +++ b/htdocs/comm/card.php @@ -5,7 +5,7 @@ * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2008 Raphael Bertrand (Resultic) - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2013 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify @@ -23,7 +23,7 @@ */ /** - * \file htdocs/comm/fiche.php + * \file htdocs/comm/card.php * \ingroup commercial compta * \brief Page to show customer card of a third party */ @@ -68,7 +68,7 @@ if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="nom"; // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('commcard')); +$hookmanager->initHooks(array('commcard','globalcard')); $object = new Societe($db); @@ -78,6 +78,7 @@ $object = new Societe($db); $parameters = array('socid' => $id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($action == 'setcustomeraccountancycode') @@ -87,7 +88,7 @@ if ($action == 'setcustomeraccountancycode') $result=$object->update($object->id,$user,1,1,0); if ($result < 0) { - $mesgs[]=join(',',$object->errors); + setEventMessage($object->errors, 'errors'); } $action=""; } @@ -288,30 +289,28 @@ if ($id > 0) print ''; // Local Taxes - if($mysoc->country_code=='ES') + if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") { - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") - { - print ''; - print ''; - } - elseif($mysoc->localtax1_assuj=="1") - { - print ''; - } - elseif($mysoc->localtax2_assuj=="1") - { - print ''; - } + print ''; + print ''; } + elseif($mysoc->localtax1_assuj=="1") + { + print ''; + } + elseif($mysoc->localtax2_assuj=="1") + { + print ''; + } + // TVA Intra print '"; print ''; @@ -441,11 +440,11 @@ if ($id > 0) // Status print ''; print ''; } @@ -531,6 +530,7 @@ if ($id > 0) while ($i < $num && $i < $MAXLIST) { $objp = $db->fetch_object($resql); + $var=!$var; print ""; print '\n"; print ''; print ''; - $var=!$var; $i++; } $db->free($resql); @@ -594,7 +593,7 @@ if ($id > 0) print '
    '.$langs->trans('LocalTax1IsUsedES').''; - print yn($object->localtax1_assuj); - print '
    '.$langs->trans('LocalTax2IsUsedES').''; - print yn($object->localtax2_assuj); - print '
    '.$langs->trans("LocalTax1IsUsedES").''; - print yn($object->localtax1_assuj); - print '
    '.$langs->trans("LocalTax2IsUsedES").''; - print yn($object->localtax2_assuj); - print '
    '.$langs->trans('LocalTax1IsUsedES').''; + print yn($object->localtax1_assuj); + print '
    '.$langs->trans('LocalTax2IsUsedES').''; + print yn($object->localtax2_assuj); + print '
    '.$langs->trans("LocalTax1IsUsedES").''; + print yn($object->localtax1_assuj); + print '
    '.$langs->trans("LocalTax2IsUsedES").''; + print yn($object->localtax2_assuj); + print '
    '.$langs->trans('VATIntra').''; @@ -329,11 +328,11 @@ if ($id > 0) print ''; if ($action == 'editconditions') { - $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->cond_reglement_id,'cond_reglement_id',-1,1); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id',1); } else { - $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id,$object->cond_reglement_id,'none'); + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_id, 'none'); } print "
    '.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4).''; - if ($object->stcomm_id != -1) print ''.img_action(0,-1).''; - if ($object->stcomm_id != 0) print ''.img_action(0,0).''; - if ($object->stcomm_id != 1) print ''.img_action(0,1).''; - if ($object->stcomm_id != 2) print ''.img_action(0,2).''; - if ($object->stcomm_id != 3) print ''.img_action(0,3).''; + if ($object->stcomm_id != -1) print ''.img_action(0,-1).''; + if ($object->stcomm_id != 0) print ''.img_action(0,0).''; + if ($object->stcomm_id != 1) print ''.img_action(0,1).''; + if ($object->stcomm_id != 2) print ''.img_action(0,2).''; + if ($object->stcomm_id != 3) print ''.img_action(0,3).''; print '
    '.img_object($langs->trans("ShowPropal"),"propal").' '.$objp->ref.''."\n"; if ( ($db->jdate($objp->dp) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == 1 ) @@ -540,7 +540,6 @@ if ($id > 0) print ''.dol_print_date($db->jdate($objp->dp),'day')."'.price($objp->total_ht).''.$propal_static->LibStatut($objp->fk_statut,5).'
    '; print ''; - print ''; + print ''; print '"; + print ""; print '"; - print ''."\n"; + print ''."\n"; print ''."\n"; print ''; diff --git a/htdocs/comm/list.php b/htdocs/comm/list.php index 78d2b14c7bc..b35e4fab7cc 100644 --- a/htdocs/comm/list.php +++ b/htdocs/comm/list.php @@ -48,13 +48,12 @@ $pagenext = $page + 1; if (! $sortorder) $sortorder="ASC"; if (! $sortfield) $sortfield="s.nom"; -$search_nom=GETPOST("search_nom"); +$search_company=GETPOST("search_company"); $search_zipcode=GETPOST("search_zipcode"); $search_town=GETPOST("search_town"); $search_code=GETPOST("search_code"); $search_compta=GETPOST("search_compta"); $search_status = GETPOST("search_status",'int'); -if ($search_status=='') $search_status=1; // always display activ customer first // Load sale and categ filters $search_sale = GETPOST("search_sale"); @@ -73,25 +72,23 @@ $hookmanager->initHooks(array('customerlist')); $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x")) +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { - $search_categ=''; - $catid=''; - $search_sale=''; - $socname=""; - $search_nom=""; + $search_sale=""; + $search_categ=""; + $catid=""; + $search_company=""; $search_zipcode=""; $search_town=""; - $search_idprof1=''; - $search_idprof2=''; - $search_idprof3=''; - $search_idprof4=''; - $seach_status=1; + $search_code=''; + $search_compta=''; + $search_status=''; } - +if ($search_status=='') $search_status=1; // always display activ customer first /* * view @@ -121,8 +118,8 @@ if ($catid > 0) $sql.= " AND cs.fk_categorie = ".$catid; if ($catid == -2) $sql.= " AND cs.fk_categorie IS NULL"; if ($search_categ > 0) $sql.= " AND cs.fk_categorie = ".$search_categ; if ($search_categ == -2) $sql.= " AND cs.fk_categorie IS NULL"; -if ($search_nom) { - $sql .= natural_search('s.nom', $search_nom); +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); } if ($search_zipcode) $sql.= " AND s.zip LIKE '".$db->escape($search_zipcode)."%'"; if ($search_town) { @@ -149,13 +146,13 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($conf->liste_limit +1, $offset); -dol_syslog('comm/list.php: sql='.$sql,LOG_DEBUG); +dol_syslog('comm/list.php:', LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $param = "&search_nom=".$search_nom."&search_code=".$search_code."&search_zipcode=".$search_zipcode."&search_town=".$search_town; + $param = "&search_company=".$search_company."&search_code=".$search_code."&search_zipcode=".$search_zipcode."&search_town=".$search_town; if ($search_categ != '') $param.='&search_categ='.$search_categ; if ($search_sale != '') $param.='&search_sale='.$search_sale; if ($search_status != '') $param.='&search_status='.$search_status; @@ -206,7 +203,7 @@ if ($result) print ''; print ''; print ''; print ''; @@ -269,7 +265,7 @@ if ($result) print ''; print ''; - + $parameters=array('obj' => $obj); $formconfirm=$hookmanager->executeHooks('printFieldListValue',$parameters); // Note that $action and $object may have been modified by hook diff --git a/htdocs/comm/mailing/fiche.php b/htdocs/comm/mailing/card.php similarity index 88% rename from htdocs/comm/mailing/fiche.php rename to htdocs/comm/mailing/card.php index d803de28357..ef9f29815c4 100644 --- a/htdocs/comm/mailing/fiche.php +++ b/htdocs/comm/mailing/card.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/comm/mailing/fiche.php + * \file htdocs/comm/mailing/card.php * \ingroup mailing * \brief Fiche mailing, onglet general */ @@ -52,7 +52,7 @@ $extrafields = new ExtraFields($db); $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('mailingcard')); +$hookmanager->initHooks(array('mailingcard','globalcard')); // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) $object->substitutionarray=array( @@ -94,6 +94,13 @@ $object->substitutionarrayfortest=array( //,'__PERSONALIZED__' => 'TESTPersonalized' // Not used yet ); +// List of sending methods +$listofmethods=array(); +$listofmethods['mail']='PHP mail function'; +//$listofmethods['simplemail']='Simplemail class'; +$listofmethods['smtps']='SMTP/SMTPS socket library'; + + /* * Actions @@ -101,13 +108,14 @@ $object->substitutionarrayfortest=array( $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'); // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { if (empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) { - $mesg='
    '.$langs->trans("NoCloneOptionsSpecified").'
    '; + setEventMessage($langs->trans("NoCloneOptionsSpecified"), 'errors'); } else { @@ -119,7 +127,7 @@ if ($action == 'confirm_clone' && $confirm == 'yes') } else { - $mesg=$object->error; + setEventMessage($object->error, 'errors'); } } $action=''; @@ -130,16 +138,17 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') { if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) { + //TODO: What is this for? // Pour des raisons de securite, on ne permet pas cette fonction via l'IHM, // on affiche donc juste un message - $mesg='
    '.$langs->trans("MailingNeedCommand").'
    '; - $mesg.='
    '; - $mesg.='

    '.$langs->trans("MailingNeedCommand2").'
    '; + setEventMessage($langs->trans("MailingNeedCommand"), 'warnings'); + setEventMessage('', 'warnings'); + setEventMessage($langs->trans("MailingNeedCommand2"), 'warnings'); $action=''; } else if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0) { - $mesg='
    '.$langs->trans("NotEnoughPermissions").'
    '; + setEventMessage($langs->trans("NotEnoughPermissions"), 'warnings'); $action=''; } else @@ -173,7 +182,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$object->id; - dol_syslog("fiche.php: select targets sql=".$sql, LOG_DEBUG); + dol_syslog("card.php: select targets", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -181,7 +190,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') if ($num) { - dol_syslog("comm/mailing/fiche.php: nb of targets = ".$num, LOG_DEBUG); + dol_syslog("comm/mailing/card.php: nb of targets = ".$num, LOG_DEBUG); $now=dol_now(); @@ -279,7 +288,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') // Mail successful $nbok++; - dol_syslog("comm/mailing/fiche.php: ok for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); + dol_syslog("comm/mailing/card.php: ok for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sql.=" SET statut=1, date_envoi=".$db->idate($now)." WHERE rowid=".$obj->rowid; @@ -295,7 +304,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') { //Update status communication of thirdparty prospect $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")"; - dol_syslog("fiche.php: set prospect thirdparty status sql=".$sql, LOG_DEBUG); + dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG); $resql2=$db->query($sql); if (! $resql2) { @@ -304,7 +313,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') //Update status communication of contact prospect $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; - dol_syslog("fiche.php: set prospect contact status sql=".$sql, LOG_DEBUG); + dol_syslog("card.php: set prospect contact status", LOG_DEBUG); $resql2=$db->query($sql); if (! $resql2) @@ -322,7 +331,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') // Mail failed $nbko++; - dol_syslog("comm/mailing/fiche.php: error for #".$i.($mail->error?' - '.$mail->error:''), LOG_WARNING); + dol_syslog("comm/mailing/card.php: error for #".$i.($mail->error?' - '.$mail->error:''), LOG_WARNING); $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sql.=" SET statut=-1, date_envoi=".$db->idate($now)." WHERE rowid=".$obj->rowid; @@ -363,7 +372,7 @@ if ($action == 'sendallconfirmed' && $confirm == 'yes') } $sql="UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$object->id; - dol_syslog("comm/mailing/fiche.php: update global status sql=".$sql, LOG_DEBUG); + dol_syslog("comm/mailing/card.php: update global status", LOG_DEBUG); $resql2=$db->query($sql); if (! $resql2) { @@ -390,7 +399,7 @@ if ($action == 'send' && empty($_POST["cancel"])) $object->sendto = $_POST["sendto"]; if (! $object->sendto) { - $mesg='
    '.$langs->trans("ErrorFieldRequired",$langs->trans("MailTo")).'
    '; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("MailTo")), 'errors'); $error++; } @@ -430,11 +439,11 @@ if ($action == 'send' && empty($_POST["cancel"])) $result=$mailfile->sendfile(); if ($result) { - $mesg='
    '.$langs->trans("MailSuccessfulySent",$mailfile->getValidAddress($object->email_from,2),$mailfile->getValidAddress($object->sendto,2)).'
    '; + setEventMessage($langs->trans("MailSuccessfulySent",$mailfile->getValidAddress($object->email_from,2),$mailfile->getValidAddress($object->sendto,2))); } else { - $mesg='
    '.$langs->trans("ResultKo").'
    '.$mailfile->error.' '.$result.'
    '; + setEventMessage($langs->trans("ResultKo").'
    '.$mailfile->error.' '.$result, 'errors'); } $action=''; @@ -444,6 +453,8 @@ if ($action == 'send' && empty($_POST["cancel"])) // Action add emailing if ($action == 'add') { + $mesgs = array(); + $object->email_from = trim($_POST["from"]); $object->email_replyto = trim($_POST["replyto"]); $object->email_errorsto = trim($_POST["errorsto"]); @@ -453,26 +464,32 @@ if ($action == 'add') $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); - if (! $object->titre) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle")); - if (! $object->sujet) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic")); - if (! $object->body) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage")); + if (! $object->titre) { + $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle")); + } + if (! $object->sujet) { + $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic")); + } + if (! $object->body) { + $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage")); + } - if (! $mesg) + if (!count($mesgs)) { if ($object->create($user) >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } - $mesg=$object->error; + $mesgs[] = $object->error; } - $mesg='
    '.$mesg.'
    '; + setEventMessage($mesgs, 'errors'); $action="create"; } // Action update description of emailing -if ($action == 'settitre' || $action == 'setemail_from' || $actino == 'setreplyto' || $action == 'setemail_errorsto') +if ($action == 'settitre' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto') { $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1); @@ -480,9 +497,12 @@ if ($action == 'settitre' || $action == 'setemail_from' || $actino == 'setreplyt else if ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from','alpha')); else if ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto','alpha')); else if ($action == 'setemail_errorsto') $object->email_errorsto = trim(GETPOST('email_errorsto','alpha')); - - else if ($action == 'settitre' && empty($object->titre)) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle")); - else if ($action == 'setfrom' && empty($object->email_from)) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailFrom")); + else if ($action == 'settitre' && empty($object->titre)) { + $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle")); + } + else if ($action == 'setfrom' && empty($object->email_from)) { + $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailFrom")); + } if (! $mesg) { @@ -491,10 +511,10 @@ if ($action == 'settitre' || $action == 'setemail_from' || $actino == 'setreplyt header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } - $mesg=$object->error; + $mesg = $object->error; } - $mesg='
    '.$mesg.'
    '; + setEventMessage($mesg, 'errors'); $action=""; } @@ -534,25 +554,31 @@ if ($action == 'update' && empty($_POST["removedfile"]) && empty($_POST["cancel" if (! $isupload) { + $mesgs = array(); + $object->sujet = trim($_POST["sujet"]); $object->body = trim($_POST["body"]); $object->bgcolor = trim($_POST["bgcolor"]); $object->bgimage = trim($_POST["bgimage"]); - if (! $object->sujet) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic")); - if (! $object->body) $mesg.=($mesg?'
    ':'').$langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage")); + if (! $object->sujet) { + $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic")); + } + if (! $object->body) { + $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage")); + } - if (! $mesg) + if (!count($mesgs)) { if ($object->update($user) >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } - $mesg=$object->error; + $mesgs[] =$object->error; } - $mesg='
    '.$mesg.'
    '; + setEventMessage($mesgs, 'errors'); $action="edit"; } else @@ -598,7 +624,7 @@ if ($action == 'confirm_reset' && $confirm == 'yes') } else { - $mesg=$object->error; + setEventMessage($object->error, 'errors'); $db->rollback(); } } @@ -613,7 +639,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') { if ($object->delete($object->id)) { - $url= (! empty($urlfrom) ? $urlfrom : 'liste.php'); + $url= (! empty($urlfrom) ? $urlfrom : 'list.php'); header("Location: ".$url); exit; } @@ -646,8 +672,6 @@ if ($action == 'create') print_fiche_titre($langs->trans("NewMailing")); - dol_htmloutput_mesg($mesg); - print '
    '; + print ''; print ''; } $i = 0; @@ -721,7 +720,7 @@ if ($id > 0) $fichinter_static->statut=$objp->fk_statut; print ""; - print ''."\n"; + print ''."\n"; //print ''."\n"; print ''."\n"; print ''."\n"; @@ -837,19 +836,19 @@ if ($id > 0) if (! empty($conf->commande->enabled) && $user->rights->commande->creer) { $langs->load("orders"); - print ''; + print ''; } if ($user->rights->contrat->creer) { $langs->load("contracts"); - print ''; + print ''; } if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer) { $langs->load("fichinter"); - print ''; + print ''; } // Add invoice @@ -858,7 +857,7 @@ if ($id > 0) if (! empty($conf->deplacement->enabled)) { $langs->load("trips"); - print ''; + print ''; } if (! empty($conf->facture->enabled)) @@ -890,7 +889,7 @@ if ($id > 0) { if ($user->rights->agenda->myactions->create) { - print ''; + print ''; } else { @@ -928,8 +927,7 @@ else dol_print_error($db,'Bad value for socid parameter'); } -dol_htmloutput_mesg('',$mesgs); - // End of page llxFooter(); + $db->close(); diff --git a/htdocs/comm/contact.php b/htdocs/comm/contact.php index 279044ccf25..a80796fe574 100644 --- a/htdocs/comm/contact.php +++ b/htdocs/comm/contact.php @@ -59,12 +59,12 @@ llxHeader('','Contacts'); if ($type == "c" || $type == "p") { $label = $langs->trans("Customers"); - $urlfiche="fiche.php"; + $urlfiche="card.php"; } if ($type == "f") { $label = $langs->trans("Suppliers"); - $urlfiche="fiche.php"; + $urlfiche="card.php"; } /* @@ -72,7 +72,7 @@ if ($type == "f") * */ -$sql = "SELECT s.rowid, s.nom, st.libelle as stcomm"; +$sql = "SELECT s.rowid, s.nom as name, st.libelle as stcomm"; $sql.= ", p.rowid as cidp, p.name, p.firstname, p.email, p.phone"; $sql.= " FROM ".MAIN_DB_PREFIX."c_stcomm as st,"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; @@ -154,12 +154,12 @@ if ($resql) $var=!$var; print ""; - print ''; + print ''; print ""; print '\n"; + print "rowid."\">$obj->name\n"; print ''; diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 98653992025..4129b561ed1 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -78,9 +78,9 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) print '
    '.$langs->trans("LastOrders",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' ('.$num.')'; print ''; //if($num2 > 0) print ''; //else print ''; @@ -608,7 +607,7 @@ if ($id > 0) $objp = $db->fetch_object($resql); $var=!$var; print ""; - print '\n"; print ''; print ''; @@ -649,7 +648,7 @@ if ($id > 0) print ''; print ''; + print '
    '.$langs->trans("LastOrders",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' ('.$num.')'.img_picto($langs->trans("Statistics"),'stats').''.img_picto($langs->trans("CreateInvoiceForThisCustomer"),'object_bill').''.img_picto($langs->trans("NoOrdersToInvoice"),'object_bill').'
    '.img_object($langs->trans("ShowOrder"),"order").' '.$objp->ref."\n"; + print ''.img_object($langs->trans("ShowOrder"),"order").' '.$objp->ref."\n"; print ''.dol_print_date($db->jdate($objp->dc),'day')."'.price($objp->total_ht).''.$commande_static->LibStatut($objp->fk_statut,$objp->facture,5).'
    '; - print '
    '.$langs->trans("LastContracts",($num<=$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllContracts").' ('.$num.')
    '.$langs->trans("AllContracts").' ('.$num.')
    '.img_object($langs->trans("ShowPropal"),"propal").' '.$objp->ref.''.img_object($langs->trans("ShowPropal"),"propal").' '.$objp->ref.''.dol_print_date($db->jdate($objp->startdate)).''.convertSecondToTime($objp->duration).''.$fichinter_static->getLibStatut(5).'
    '.img_object($langs->trans("ShowContact"),"contact"); - print ' '.$obj->name.''.img_object($langs->trans("ShowContact"),"contact"); + print ' '.$obj->name.'$obj->firstname'.img_object($langs->trans("ShowCompany"),"company").' '; - print "rowid."\">$obj->nom'.dol_print_phone($obj->email,$obj->cidp,$obj->rowid,'AC_EMAIL').'
    '; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print "
    '.$langs->trans("SearchAProposal").'
    '.$langs->trans("Ref").'::
    '.$langs->trans("Other").':
    :
    \n"; print "
    \n"; @@ -91,12 +91,12 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { $var=false; print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; + print ':'; + print ''; print ''; print "
    '.$langs->trans("SearchACustomerOrder").'
    '; - print $langs->trans("Ref").':
    '.$langs->trans("Other").':
    :

    \n"; } @@ -105,14 +105,31 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $var=false; - print '
    '; + print ''; print ''; print ''; print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; + print ''; + print "
    '.$langs->trans("SearchAContract").'
    '.$langs->trans("Ref").'::
    '.$langs->trans("Other").':
    :
    \n"; + print "
    "; +} + +// Search contract +if (! empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire) +{ + $var=false; + print '
    '; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; print ''; print "
    '.$langs->trans("SearchAnIntervention").'
    :
    :
    \n"; print "
    "; @@ -217,7 +234,7 @@ if (! empty($conf->commande->enabled) && $user->rights->commande->lire) { $var=!$var; $obj = $db->fetch_object($resql); - print '
    '.img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.'
    '.img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.''; $companystatic->id=$obj->socid; $companystatic->name=$obj->name; @@ -417,7 +434,7 @@ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire && 0) // TO while ($i < $num) { $obj = $db->fetch_object($resql); - print "
    contratid."\">".img_object($langs->trans("ShowContract","contract"))." ".$obj->ref."
    contratid."\">".img_object($langs->trans("ShowContract","contract"))." ".$obj->ref."'; $companystatic->id=$objp->rowid; $companystatic->name=$objp->name; @@ -444,7 +461,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) { $langs->load("propal"); - $sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; + $sql = "SELECT s.nom as name, s.rowid, p.rowid as propalid, p.total as total_ttc, p.total_ht, p.ref, p.fk_statut, p.datep as dp, p.fin_validite as dfv"; $sql.= " 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"; @@ -497,7 +514,7 @@ if (! empty($conf->propal->enabled) && $user->rights->propal->lire) print "'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,44).''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,44).''; print dol_print_date($db->jdate($obj->dp),'day').''.price($obj->total_ttc).'
    '; - print ''; + print ''; print ''; @@ -234,7 +231,6 @@ if ($result) print ''; - print '  '; print ''; print ''.$thirdpartystatic->getLibStatut(3); print '
    '; print ''; print ''; @@ -724,16 +748,27 @@ else { // Define message to recommand from command line - // Pour des raisons de securite, on ne permet pas cette fonction via l'IHM, - // on affiche donc juste un message + $sendingmode=$conf->global->MAIN_MAIL_SENDMODE; + if (empty($sendingmode)) $sendingmode='mail'; // If not defined, we use php mail function - if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) + if (! empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') + { + // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent. + // You ensure that every user is using its own SMTP server. + $linktoadminemailbefore=''; + $linktoadminemailend=''; + setEventMessage($langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]), 'warnings'); + setEventMessage($langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']), 'warnings'); + if (! empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) setEventMessage($langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS), 'warnings'); + $_GET["action"]=''; + } + else if (empty($conf->global->MAILING_LIMIT_SENDBYWEB)) { // Pour des raisons de securite, on ne permet pas cette fonction via l'IHM, // on affiche donc juste un message - $mesgembedded.='
    '.$langs->trans("MailingNeedCommand").'
    '; - $mesgembedded.='
    '; - $mesgembedded.='

    '.$langs->trans("MailingNeedCommand2").'
    '; + setEventMessage($langs->trans("MailingNeedCommand"), 'warnings'); + setEventMessage('', 'warnings'); + setEventMessage($langs->trans("MailingNeedCommand2"), 'warnings'); $_GET["action"]=''; } else @@ -747,13 +782,13 @@ else } $text.=$langs->trans('ConfirmSendingEmailing').'
    '; $text.=$langs->trans('LimitSendingEmailing',$conf->global->MAILING_LIMIT_SENDBYWEB); - print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id,$langs->trans('SendMailing'),$text,'sendallconfirmed',$formquestion,'',1,260); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id,$langs->trans('SendMailing'),$text,'sendallconfirmed',$formquestion,'',1,270); } } print '
    '.$langs->trans("MailTitle").'
    '.$langs->trans("MailFrom").'
    '; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; print ''; print ''; + print ''; + print '"; + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0 ) // Localtax1 + { + print '"; + } + + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 + { + print '"; + } + print '"; + } + + print "
    '.$langs->trans("Ref").''; @@ -829,9 +864,6 @@ else print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneEMailing'),$langs->trans('ConfirmCloneEMailing',$object->ref),'confirm_clone',$formquestion,'yes',2,240); } - - dol_htmloutput_mesg($mesg); - /* * Boutons d'action */ @@ -840,12 +872,12 @@ else { print "\n\n
    \n"; - if (($object->statut == 0 || $object->statut == 1) && $user->rights->mailing->creer) + if (($object->statut == 0) && $user->rights->mailing->creer) { print ''.$langs->trans("EditMailing").''; } - //print ''.$langs->trans("PreviewMailing").''; + //print ''.$langs->trans("PreviewMailing").''; if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send) { @@ -916,12 +948,6 @@ else print '

    '; } - if (! empty($mesgembedded)) - { - dol_htmloutput_mesg($mesgembedded,'','warning',1); - print '
    '; - } - // Affichage formulaire de TEST if ($action == 'test') { @@ -1017,8 +1043,6 @@ else * Mailing en mode edition */ - dol_htmloutput_mesg($mesg); - print ''; // Ref @@ -1061,7 +1085,7 @@ else print ""; print "\n"; - print ''."\n"; + print ''."\n"; print ''; print ''; print ''; diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index d6599f204f1..75f2399017b 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -2,6 +2,7 @@ /* Copyright (C) 2004 Rodolphe Quiedeville * Copyright (C) 2005-2013 Laurent Destailleur * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2014 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -26,6 +27,7 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/mailings/modules_mailings.php'; require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmailing.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; @@ -36,8 +38,6 @@ $langs->load("mails"); if (! $user->rights->mailing->lire || $user->societe_id > 0) accessforbidden(); -$mesg = ''; - $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -54,6 +54,7 @@ $action=GETPOST("action"); $search_lastname=GETPOST("search_lastname"); $search_firstname=GETPOST("search_firstname"); $search_email=GETPOST("search_email"); +$search_dest_status=GETPOST('search_dest_status'); // Search modules dirs $modulesdir = dolGetModulesDirs('/mailings'); @@ -97,11 +98,10 @@ if ($action == 'add') $result=$obj->add_to_target($id,$filtersarray); } } - if ($result > 0) { setEventMessage($langs->trans("XTargetsAdded",$result),'mesgs'); - + header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } @@ -144,7 +144,7 @@ if ($action == 'delete') } else { - header("Location: liste.php"); + header("Location: list.php"); exit; } } @@ -166,10 +166,10 @@ if ($_POST["button_removefilter"]) /* * View */ - llxHeader('',$langs->trans("Mailing"),'EN:Module_EMailing|FR:Module_Mailing|ES:Módulo_Mailing'); $form = new Form($db); +$formmailing = new FormMailing($db); if ($object->fetch($id) >= 0) { @@ -180,7 +180,7 @@ if ($object->fetch($id) >= 0) print '
    '; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; print ''; print ''; - /* - print '"; - */ - $nbofrecipient=$obj->getNbOfRecipients(''); + try { + $nbofrecipient=$obj->getNbOfRecipients(''); + } + catch(Exception $e) + { + dol_syslog($e->getMessage(), LOG_ERR); + } + print ''; print ''; @@ -359,6 +366,7 @@ if ($object->fetch($id) >= 0) if ($search_lastname) $sql.= " AND mc.lastname LIKE '%".$db->escape($search_lastname)."%'"; if ($search_firstname) $sql.= " AND mc.firstname LIKE '%".$db->escape($search_firstname)."%'"; if ($search_email) $sql.= " AND mc.email LIKE '%".$db->escape($search_email)."%'"; + if (!empty($search_dest_status)) $sql.= " AND mc.statut=".$db->escape($search_dest_status)." "; $sql .= $db->order($sortfield,$sortorder); $sql .= $db->plimit($conf->liste_limit+1, $offset); @@ -378,7 +386,9 @@ if ($object->fetch($id) >= 0) print ''; print ''; - $cleartext='
    '.$langs->trans("ToClearAllRecipientsClickHere").': '.''; + if ($allowaddtarget) { + $cleartext='
    '.$langs->trans("ToClearAllRecipientsClickHere").': '.''; + } print_barre_liste($langs->trans("MailSelectedRecipients").$cleartext,$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,"",$num,$object->nbemail,''); @@ -401,7 +411,7 @@ if ($object->fetch($id) >= 0) print_liste_field_titre($langs->trans("OtherInformations"),$_SERVER["PHP_SELF"],"",$param,"","",$sortfield,$sortorder); print_liste_field_titre($langs->trans("Source"),$_SERVER["PHP_SELF"],"",$param,"",'align="center"',$sortfield,$sortorder); - // Date sendinf + // Date sending if ($object->statut < 2) { print '
    '; @@ -414,6 +424,11 @@ if ($object->fetch($id) >= 0) // Statut print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"mc.statut",$param,'','align="right"',$sortfield,$sortorder); + //Search Icon + print ''; + print ''; // Ligne des champs de filtres @@ -435,7 +450,20 @@ if ($object->fetch($id) >= 0) print ' '; print ''; // Source - print ''; + + // Date sending + print ''; + //Statut + print ''; + //Search Icon + print ''; print ''; @@ -506,12 +534,12 @@ if ($object->fetch($id) >= 0) { print ''; print ''; } + + //Sreach Icon + print ''; print ''; $i++; diff --git a/htdocs/comm/mailing/class/index.html b/htdocs/comm/mailing/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/mailing/class/mailing.class.php b/htdocs/comm/mailing/class/mailing.class.php index 99b1a2f4419..2f8f7f18e4e 100644 --- a/htdocs/comm/mailing/class/mailing.class.php +++ b/htdocs/comm/mailing/class/mailing.class.php @@ -60,6 +60,9 @@ class Mailing extends CommonObject var $extraparams=array(); + public $statut_dest=array(); + public $statuts=array(); + /** * Constructor @@ -75,6 +78,12 @@ class Mailing extends CommonObject $this->statuts[1] = 'MailingStatusValidated'; $this->statuts[2] = 'MailingStatusSentPartialy'; $this->statuts[3] = 'MailingStatusSentCompletely'; + + $this->statut_dest[-1] = 'MailingStatusError'; + $this->statut_dest[1] = 'MailingStatusSent'; + $this->statut_dest[2] = 'MailingStatusRead'; + $this->statut_dest[3] = 'MailingStatusNotContact'; + } /** @@ -109,7 +118,7 @@ class Mailing extends CommonObject $this->titre = $langs->trans("NoTitle"); } - dol_syslog("Mailing::Create sql=".$sql); + dol_syslog("Mailing::Create", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -122,7 +131,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Create ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -132,7 +140,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Create ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -157,7 +164,7 @@ class Mailing extends CommonObject $sql .= ", bgimage = '".($this->bgimage?$this->bgimage:null)."'"; $sql .= " WHERE rowid = ".$this->id; - dol_syslog("Mailing::Update sql=".$sql); + dol_syslog("Mailing::Update", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -166,7 +173,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Update ".$this->error, LOG_ERR); return -1; } } @@ -192,7 +198,7 @@ class Mailing extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."mailing as m"; $sql.= " WHERE m.rowid = ".$rowid; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -325,7 +331,7 @@ class Mailing extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."mailing_cibles "; $sql.= " WHERE fk_mailing = ".$fromid; - dol_syslog(get_class($this)."::createFromClone sql=".$sql); + dol_syslog(get_class($this)."::createFromClone", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -348,7 +354,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::createFromClone ".$this->error, LOG_ERR); return -1; } @@ -384,7 +389,7 @@ class Mailing extends CommonObject $sql .= " SET statut = 1, date_valid = '".$this->db->idate($now)."', fk_user_valid=".$user->id; $sql .= " WHERE rowid = ".$this->id; - dol_syslog("Mailing::valid sql=".$sql, LOG_DEBUG); + dol_syslog("Mailing::valid", LOG_DEBUG); if ($this->db->query($sql)) { return 1; @@ -392,7 +397,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Valid ".$this->error, LOG_ERR); return -1; } } @@ -409,7 +413,7 @@ class Mailing extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing"; $sql.= " WHERE rowid = ".$rowid; - dol_syslog("Mailing::delete sql=".$sql, LOG_DEBUG); + dol_syslog("Mailing::delete", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -418,7 +422,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Valid ".$this->error, LOG_ERR); return -1; } } @@ -436,7 +439,7 @@ class Mailing extends CommonObject $sql.= " SET statut = 0"; $sql.= " WHERE fk_mailing = ".$this->id; - dol_syslog("Mailing::reset_targets_status sql=".$sql, LOG_DEBUG); + dol_syslog("Mailing::reset_targets_status", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -445,7 +448,6 @@ class Mailing extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog("Mailing::Valid ".$this->error, LOG_ERR); return -1; } } @@ -512,5 +514,60 @@ class Mailing extends CommonObject } } + + /** + * Renvoi le libelle d'un statut donne + * + * @param int $statut Id statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label + */ + static public function libStatutDest($statut,$mode=0) + { + global $langs; + $langs->load('mails'); + + if ($mode == 0) + { + return $langs->trans($this->statut_dest[$statut]); + } + if ($mode == 1) + { + return $langs->trans($this->statut_dest[$statut]); + } + if ($mode == 2) + { + if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error(); + if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4'); + if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6'); + if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8'); + } + if ($mode == 3) + { + if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error(); + if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4'); + if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6'); + if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8'); + } + if ($mode == 4) + { + if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error(); + if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4'); + if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6'); + if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8'); + } + if ($mode == 5) + { + if ($statut==-1) return $langs->trans("MailingStatusError").' '.img_error(); + if ($statut==1) return $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4'); + if ($statut==2) return $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6'); + if ($statut==3) return $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut8'); + } + + + + + } + } diff --git a/htdocs/comm/mailing/index.php b/htdocs/comm/mailing/index.php index a0175bad448..5c6ae896e42 100644 --- a/htdocs/comm/mailing/index.php +++ b/htdocs/comm/mailing/index.php @@ -51,7 +51,7 @@ print '
    '; // Recherche emails $var=false; -print ''; +print ''; print ''; print '
    '.$langs->trans("Ref").''; @@ -218,11 +218,9 @@ if ($object->fetch($id) >= 0) print ""; - dol_htmloutput_mesg($mesg); - $var=!$var; - $allowaddtarget=($object->statut == 0 || $object->statut == 1); + $allowaddtarget=($object->statut == 0); // Show email selectors if ($allowaddtarget && $user->rights->mailing->creer) @@ -278,7 +276,8 @@ if ($object->fetch($id) >= 0) $obj = new $classname($db); - $qualified=1; + // Check dependencies + $qualified=(isset($obj->enabled)?$obj->enabled:1); foreach ($obj->require_module as $key) { if (! $conf->$key->enabled || (! $user->admin && $obj->require_admin)) @@ -306,12 +305,14 @@ if ($object->fetch($id) >= 0) print img_object($langs->trans("Module").': '.get_class($obj),$obj->picto).' '.$obj->getDesc(); print ''; - print $modulename; - print "'; if ($nbofrecipient >= 0) { @@ -324,7 +325,13 @@ if ($object->fetch($id) >= 0) print ''; - $filter=$obj->formFilter(); + try { + $filter=$obj->formFilter(); + } + catch(Exception $e) + { + dol_syslog($e->getMessage(), LOG_ERR); + } if ($filter) print $filter; else print $langs->trans("None"); print ' '; + print ' '; + print '
    '; + print ''; + print ' '; + print ''; + print ' '; + print ''; + print $formmailing->selectDestinariesStatus($search_dest_status,'search_dest_status',1); + print ''; print ''; print '  '; print ''; @@ -497,7 +525,7 @@ if ($object->fetch($id) >= 0) { print ' '.$langs->trans("MailingStatusNotSent"); - if ($user->rights->mailing->creer) { + if ($user->rights->mailing->creer && $allowaddtarget) { print ''.img_delete($langs->trans("RemoveRecipient")); } print ''.$obj->date_envoi.''; - if ($obj->statut==-1) print $langs->trans("MailingStatusError").' '.img_error(); - if ($obj->statut==1) print $langs->trans("MailingStatusSent").' '.img_picto($langs->trans("MailingStatusSent"),'statut4'); - if ($obj->statut==2) print $langs->trans("MailingStatusRead").' '.img_picto($langs->trans("MailingStatusRead"),'statut6'); - if ($obj->statut==3) print $langs->trans("MailingStatusNotContact").' '.img_picto($langs->trans("MailingStatusNotContact"),'statut5'); + print $object::libStatutDest($obj->statut,2); print '
    '; print ''; @@ -162,7 +162,7 @@ if ($result) print ''; print ''; print ''; - print ''; + print ''; $num = $db->num_rows($result); if ($num > 0) @@ -176,7 +176,7 @@ if ($result) $var=!$var; print ""; - print ''; + print ''; print ''; print ''; print ''; diff --git a/htdocs/comm/mailing/liste.php b/htdocs/comm/mailing/list.php similarity index 97% rename from htdocs/comm/mailing/liste.php rename to htdocs/comm/mailing/list.php index 617096561a3..ef2e2c48bf8 100644 --- a/htdocs/comm/mailing/liste.php +++ b/htdocs/comm/mailing/list.php @@ -17,7 +17,7 @@ */ /** - * \file htdocs/comm/mailing/liste.php + * \file htdocs/comm/mailing/list.php * \ingroup mailing * \brief Liste des mailings */ @@ -82,7 +82,6 @@ else $sql.= $db->plimit($conf->liste_limit +1, $offset); } -dol_syslog("sql=".$sql); //print $sql; $result = $db->query($sql); if ($result) @@ -137,7 +136,7 @@ if ($result) $var=!$var; print ""; - print ''; print ''; // Date creation diff --git a/htdocs/comm/propal.php b/htdocs/comm/propal.php index e3be3ac8361..0ac5d78aead 100644 --- a/htdocs/comm/propal.php +++ b/htdocs/comm/propal.php @@ -5,10 +5,11 @@ * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2006 Andre Cianfarani - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2010-2011 Philippe Grand * Copyright (C) 2012-2013 Christophe Battarel * Copyright (C) 2013-2014 Florian Henry + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -51,6 +52,7 @@ $langs->load('bills'); $langs->load('orders'); $langs->load('products'); $langs->load("deliveries"); +$langs->load('sendings'); if (! empty($conf->margin->enabled)) $langs->load('margins'); @@ -64,6 +66,7 @@ $origin = GETPOST('origin', 'alpha'); $originid = GETPOST('originid', 'int'); $confirm = GETPOST('confirm', 'alpha'); $lineid = GETPOST('lineid', 'int'); +$contactid = GETPOST('contactid','int'); // PDF $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); @@ -74,8 +77,7 @@ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (! empty($co $NBLINES = 4; // Security check -if (! empty($user->societe_id)) - $socid = $user->societe_id; +if (! empty($user->societe_id)) $socid = $user->societe_id; $result = restrictedArea($user, 'propal', $id); $object = new Propal($db); @@ -94,7 +96,7 @@ if ($id > 0 || ! empty($ref)) { } // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('propalcard')); +$hookmanager->initHooks(array('propalcard','globalcard')); $permissionnote = $user->rights->propale->creer; // Used by the include of actions_setnotes.inc.php @@ -103,16 +105,20 @@ $permissionnote = $user->rights->propale->creer; // Used by the include of actio */ $parameters = array('socid' => $socid); -$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some - // hooks +$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_setnotes.inc.php'; // Must be include, not includ_once // Action clone object -if ($action == 'confirm_clone' && $confirm == 'yes') { - if (1 == 0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) { +if ($action == 'confirm_clone' && $confirm == 'yes') +{ + if (1 == 0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) + { setEventMessage($langs->trans("NoCloneOptionsSpecified"), 'errors'); - } else { + } + else + { if ($object->id > 0) { $result = $object->createFromClone($socid); if ($result > 0) { @@ -127,7 +133,8 @@ if ($action == 'confirm_clone' && $confirm == 'yes') { } // Delete proposal -else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->propal->supprimer) { +else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->propal->supprimer) +{ $result = $object->delete($user); if ($result > 0) { header('Location: ' . DOL_URL_ROOT . '/comm/propal/list.php'); @@ -139,7 +146,8 @@ else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->prop } // Remove line -else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->propal->creer) { +else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->propal->creer) +{ $result = $object->deleteline($lineid); // reorder lines if ($result) @@ -150,11 +158,11 @@ else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights-> $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id); @@ -162,19 +170,29 @@ else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights-> } // Validation -else if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->propal->valider) { +else if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->propal->valider) +{ $result = $object->valid($user); - if ($result >= 0) { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { - $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); - $outputlangs->setDefaultLang($newlang); + if ($result >= 0) + { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { $tmp=getListOfModels($db, 'propal'); $keys=array_keys($tmp); $model=$keys[0]; } + $ret = $object->fetch($id); // Reload to get new records + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); } - $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } else { $langs->load("errors"); @@ -183,8 +201,9 @@ else if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->pr } } -else if ($action == 'setdate' && $user->rights->propal->creer) { - $datep = dol_mktime(12, 0, 0, $_POST ['remonth'], $_POST ['reday'], $_POST ['reyear']); +else if ($action == 'setdate' && $user->rights->propal->creer) +{ + $datep = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); if (empty($datep)) { $error ++; @@ -196,23 +215,29 @@ else if ($action == 'setdate' && $user->rights->propal->creer) { if ($result < 0) dol_print_error($db, $object->error); } -} else if ($action == 'setecheance' && $user->rights->propal->creer) { - $result = $object->set_echeance($user, dol_mktime(12, 0, 0, $_POST ['echmonth'], $_POST ['echday'], $_POST ['echyear'])); +} +else if ($action == 'setecheance' && $user->rights->propal->creer) +{ + $result = $object->set_echeance($user, dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear'])); if ($result < 0) dol_print_error($db, $object->error); -} else if ($action == 'setdate_livraison' && $user->rights->propal->creer) { - $result = $object->set_date_livraison($user, dol_mktime(12, 0, 0, $_POST ['liv_month'], $_POST ['liv_day'], $_POST ['liv_year'])); +} +else if ($action == 'setdate_livraison' && $user->rights->propal->creer) +{ + $result = $object->set_date_livraison($user, dol_mktime(12, 0, 0, $_POST['liv_month'], $_POST['liv_day'], $_POST['liv_year'])); if ($result < 0) dol_print_error($db, $object->error); } // Positionne ref client -else if ($action == 'set_ref_client' && $user->rights->propal->creer) { - $object->set_ref_client($user, $_POST ['ref_client']); +else if ($action == 'set_ref_client' && $user->rights->propal->creer) +{ + $object->set_ref_client($user, $_POST['ref_client']); } // Create proposal -else if ($action == 'add' && $user->rights->propal->creer) { +else if ($action == 'add' && $user->rights->propal->creer) +{ $object->socid = $socid; $object->fetch_thirdparty(); @@ -237,11 +262,13 @@ else if ($action == 'add' && $user->rights->propal->creer) { $error ++; } - if (! $error) { + if (! $error) + { $db->begin(); // Si on a selectionne une propal a copier, on realise la copie - if (GETPOST('createmode') == 'copy' && GETPOST('copie_propal')) { + if (GETPOST('createmode') == 'copy' && GETPOST('copie_propal')) + { if ($object->fetch(GETPOST('copie_propal')) > 0) { $object->ref = GETPOST('ref'); $object->datep = $datep; @@ -249,13 +276,15 @@ else if ($action == 'add' && $user->rights->propal->creer) { $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->fk_delivery_address = GETPOST('fk_address'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->duree_validite = $duration; $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->remise_percent = GETPOST('remise_percent'); $object->remise_absolue = GETPOST('remise_absolue'); $object->socid = GETPOST('socid'); - $object->contactid = GETPOST('contactidp'); + $object->contactid = GETPOST('contactid'); $object->fk_project = GETPOST('projectid'); $object->modelpdf = GETPOST('model'); $object->author = $user->id; // deprecated @@ -274,11 +303,12 @@ else if ($action == 'add' && $user->rights->propal->creer) { $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->fk_delivery_address = GETPOST('fk_address'); + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->duree_validite = GETPOST('duree_validite'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); - - $object->contactid = GETPOST('contactidp'); + $object->fk_account = GETPOST('fk_account', 'int'); + $object->contactid = GETPOST('contactid'); $object->fk_project = GETPOST('projectid'); $object->modelpdf = GETPOST('model'); $object->author = $user->id; // deprecated @@ -287,12 +317,13 @@ else if ($action == 'add' && $user->rights->propal->creer) { $object->origin = GETPOST('origin'); $object->origin_id = GETPOST('originid'); - for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) { - if ($_POST ['idprod' . $i]) { + for($i = 1; $i <= $conf->global->PRODUCT_SHOW_WHEN_CREATE; $i ++) + { + if ($_POST['idprod' . $i]) { $xid = 'idprod' . $i; $xqty = 'qty' . $i; $xremise = 'remise' . $i; - $object->add_product($_POST [$xid], $_POST [$xqty], $_POST [$xremise]); + $object->add_product($_POST[$xid], $_POST[$xqty], $_POST[$xremise]); } } @@ -304,43 +335,193 @@ else if ($action == 'add' && $user->rights->propal->creer) { } } - if (! $error) { - $id = $object->create($user); + if (! $error) + { + if ($origin && $originid) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { + $element = $regs [1]; + $subelement = $regs [2]; + } - if ($id > 0) { + // For compatibility + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; + $subelement = 'propal'; + } + if ($element == 'contract') { + $element = $subelement = 'contrat'; + } + if ($element == 'inter') { + $element = $subelement = 'ficheinter'; + } + if ($element == 'shipping') { + $element = $subelement = 'expedition'; + } + + $object->origin = $origin; + $object->origin_id = $originid; + + // Possibility to add external linked objects with hooks + $object->linked_objects [$object->origin] = $object->origin_id; + if (is_array($_POST['other_linked_objects']) && ! empty($_POST['other_linked_objects'])) { + $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); + } + + $id = $object->create($user); + if ($id > 0) + { + dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + + $classname = ucfirst($subelement); + $srcobject = new $classname($db); + + dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines"); + $result = $srcobject->fetch($object->origin_id); + + if ($result > 0) + { + $lines = $srcobject->lines; + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) + { + $srcobject->fetch_lines(); + $lines = $srcobject->lines; + } + + $fk_parent_line=0; + $num=count($lines); + for ($i=0;$i<$num;$i++) + { + $label=(! empty($lines[$i]->label)?$lines[$i]->label:''); + $desc=(! empty($lines[$i]->desc)?$lines[$i]->desc:$lines[$i]->libelle); + + // Positive line + $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); + + // Date start + $date_start = false; + if ($lines[$i]->date_debut_prevue) + $date_start = $lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) + $date_start = $lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) + $date_start = $lines[$i]->date_start; + + // Date end + $date_end = false; + if ($lines[$i]->date_fin_prevue) + $date_end = $lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) + $date_end = $lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) + $date_end = $lines[$i]->date_end; + + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { + $fk_parent_line = 0; + } + + // Extrafields + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) { + $lines[$i]->fetch_optionals($lines[$i]->rowid); + $array_option = $lines[$i]->array_options; + } + + $tva_tx=get_default_tva($mysoc, $object->thirdparty); + + $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, $lines[$i]->remise_percent, 'HT', 0, $lines[$i]->info_bits, $product_type, $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $date_start, $date_end, $array_option); + + if ($result > 0) { + $lineid = $result; + } else { + $lineid = 0; + $error ++; + break; + } + + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) { + $fk_parent_line = $result; + } + } + + // Hooks + $parameters = array('objFrom' => $srcobject); + $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if ($reshook < 0) + $error ++; + } else { + setEventMessages($srcobject->error, $srcobject->errors, 'errors'); + $error ++; + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $error ++; + } + } // Standard creation + else + { + $id = $object->create($user); + } + + if ($id > 0) + { // Insertion contact par defaut si defini - if (GETPOST('contactidp') > 0) { - $result = $object->add_contact(GETPOST('contactidp'), 'CUSTOMER', 'external'); - if ($result < 0) { - $error ++; + if (GETPOST('contactid') > 0) + { + $result = $object->add_contact(GETPOST('contactid'), 'CUSTOMER', 'external'); + if ($result < 0) + { + $error++; setEventMessage($langs->trans("ErrorFailedToAddContact"), 'errors'); } } - if (! $error) { + if (! $error) + { $db->commit(); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) { - $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); - $outputlangs->setDefaultLang($newlang); - } - $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'propal'); $keys=array_keys($tmp); $model=$keys[0]; + } + + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id); exit(); - } else { - $db->rollback(); } - } else { - dol_print_error($db, $object->error); + else + { + $db->rollback(); + $action='create'; + } + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); - exit(); + $action='create'; } } } @@ -354,7 +535,7 @@ else if ($action == 'classifybilled' && $user->rights->propal->cloturer) { // Reopen proposal else if ($action == 'confirm_reopen' && $user->rights->propal->cloturer && ! GETPOST('cancel')) { // prevent browser refresh from reopening proposal several times - if ($object->statut == 2 || $object->statut == 3) { + if ($object->statut == 2 || $object->statut == 3 || $object->statut == 4) { $object->reopen($user, 1); } } @@ -372,166 +553,45 @@ else if ($action == 'setstatut' && $user->rights->propal->cloturer && ! GETPOST( } } -// Add file in email form -if (GETPOST('addfile')) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_printipp.inc.php'; - // Set tmp user directory TODO Use a dedicated directory for temp mails files - $vardir = $conf->user->dir_output . "/" . $user->id; - $upload_dir_tmp = $vardir . '/temp'; - - dol_add_file_process($upload_dir_tmp, 0, 0); - $action = 'presend'; -} - -// Remove file in email form -if (GETPOST('removedfile')) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - - // Set tmp user directory - $vardir = $conf->user->dir_output . "/" . $user->id; - $upload_dir_tmp = $vardir . '/temp'; - - // TODO Delete only files that was uploaded from email form - dol_remove_file_process($_POST ['removedfile'], 0); - $action = 'presend'; -} /* * Send mail */ -if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! GETPOST('cancel')) { - $langs->load('mails'); - if ($object->id > 0) { - if ($_POST ['sendto']) { - // Le destinataire a ete fourni via le champ libre - $sendto = $_POST ['sendto']; - $sendtoid = 0; - } elseif ($_POST ['receiver'] != '-1') { - // Recipient was provided from combo list - if ($_POST ['receiver'] == 'thirdparty') // Id of third party - { - $sendto = $object->client->email; - $sendtoid = 0; - } else // Id du contact - { - $sendto = $object->client->contact_get_property($_POST ['receiver'], 'email'); - $sendtoid = $_POST ['receiver']; - } - } +// Actions to send emails +$actiontypecode='AC_PROP'; +$trigger_name='PROPAL_SENTBYMAIL'; +$paramname='id'; +$mode='emailfromproposal'; +include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (dol_strlen($sendto)) { - $langs->load("commercial"); - $from = $_POST ['fromname'] . ' <' . $_POST ['frommail'] . '>'; - $replyto = $_POST ['replytoname'] . ' <' . $_POST ['replytomail'] . '>'; - $message = $_POST ['message']; - $sendtocc = $_POST ['sendtocc']; - $deliveryreceipt = $_POST ['deliveryreceipt']; - - if (dol_strlen($_POST ['subject'])) - $subject = $_POST ['subject']; - else - $subject = $langs->transnoentities('Propal') . ' ' . $object->ref; - $actiontypecode = 'AC_PROP'; - $actionmsg = $langs->transnoentities('MailSentBy') . ' ' . $from . ' ' . $langs->transnoentities('To') . ' ' . $sendto . ".\n"; - if ($message) { - $actionmsg .= $langs->transnoentities('MailTopic') . ": " . $subject . "\n"; - $actionmsg .= $langs->transnoentities('TextUsedInTheMessageBody') . ":\n"; - $actionmsg .= $message; - } - $actionmsg2 = $langs->transnoentities('Action' . $actiontypecode); - - // Create form object - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $attachedfiles = $formmail->get_attached_files(); - $filepath = $attachedfiles ['paths']; - $filename = $attachedfiles ['names']; - $mimetype = $attachedfiles ['mimes']; - - // Envoi de la propal - require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, - 1); - if ($mailfile->error) { - setEventMessage($mailfile->error, 'errors'); - } else { - $result = $mailfile->sendfile(); - if ($result) { - // Initialisation donnees - $object->sendtoid = $sendtoid; - $object->actiontypecode = $actiontypecode; - $object->actionmsg = $actionmsg; - $object->actionmsg2 = $actionmsg2; - $object->fk_element = $object->id; - $object->elementtype = $object->element; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface = new Interfaces($db); - $result = $interface->run_triggers('PROPAL_SENTBYMAIL', $object, $user, $langs, $conf); - if ($result < 0) { - $error++; - $object->errors = $interface->errors; - } - // Fin appel triggers - - if (! $error) { - // Redirect here - // This avoid sending mail twice if going out and then back to page - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)); - setEventMessage($mesg); - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id); - exit(); - } else { - dol_print_error($db); - } - } else { - $langs->load("other"); - if ($mailfile->error) { - $mesg .= $langs->trans('ErrorFailedToSendMail', $from, $sendto); - $mesg .= '
    ' . $mailfile->error; - } else { - $mesg .= 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; - } - setEventMessage($mesg, 'errors'); - } - } - } else { - $langs->load("other"); - setEventMessage($langs->trans('ErrorMailRecipientIsEmpty') . '!', 'errors'); - dol_syslog($langs->trans('ErrorMailRecipientIsEmpty')); - } - } else { - $langs->load("other"); - setEventMessage($langs->trans('ErrorFailedToReadEntity', $langs->trans("Proposal")), 'errors'); - dol_syslog($langs->trans('ErrorFailedToReadEntity', $langs->trans("Proposal"))); - } -} // Go back to draft -if ($action == 'modif' && $user->rights->propal->creer) { +if ($action == 'modif' && $user->rights->propal->creer) +{ $object->set_draft($user); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { // Define output language $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } else if ($action == "setabsolutediscount" && $user->rights->propal->creer) { - if ($_POST ["remise_id"]) { + if ($_POST["remise_id"]) { if ($object->id > 0) { - $result = $object->insert_discount($_POST ["remise_id"]); + $result = $object->insert_discount($_POST["remise_id"]); if ($result < 0) { setEventMessage($object->error, 'errors'); } @@ -569,7 +629,7 @@ else if ($action == 'addline' && $user->rights->propal->creer) { if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST ["options_" . $key]); + unset($_POST["options_" . $key]); } } @@ -606,18 +666,22 @@ else if ($action == 'addline' && $user->rights->propal->creer) { $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); // If prices fields are update - $tva_tx = get_default_tva($mysoc, $object->client, $prod->id); - $tva_npr = get_default_npr($mysoc, $object->client, $prod->id); + $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); + $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; // On defini prix unitaire - if (! empty($conf->global->PRODUIT_MULTIPRICES) && $object->client->price_level) + if (! empty($conf->global->PRODUIT_MULTIPRICES) && $object->thirdparty->price_level) { - $pu_ht = $prod->multiprices[$object->client->price_level]; - $pu_ttc = $prod->multiprices_ttc[$object->client->price_level]; - $price_min = $prod->multiprices_min[$object->client->price_level]; - $price_base_type = $prod->multiprices_base_type[$object->client->price_level]; - if (isset($prod->multiprices_tva_tx[$object->client->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->client->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->client->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->client->price_level]; + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; } elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { @@ -628,30 +692,15 @@ else if ($action == 'addline' && $user->rights->propal->creer) { $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result >= 0) { + if ($result) { if (count($prodcustprice->lines) > 0) { - $found = true; - $pu_ht = price($prodcustprice->lines[0]->price); - $pu_ttc = price($prodcustprice->lines[0]->price_ttc); - $price_base_type = $prodcustprice->lines[0]->price_base_type; - $prod->tva_tx = $prodcustprice->lines[0]->tva_tx; - }else { - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + $pu_ht = price($prodcustprice->lines [0]->price); + $pu_ttc = price($prodcustprice->lines [0]->price_ttc); + $price_base_type = $prodcustprice->lines [0]->price_base_type; + $prod->tva_tx = $prodcustprice->lines [0]->tva_tx; } - }else { - setEventMessage($prodcustprice->error,'errors'); } } - else - { - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; - } // if price ht is forced (ie: calculated by margin rate and cost price) if (! empty($price_ht)) { @@ -678,7 +727,7 @@ else if ($action == 'addline' && $user->rights->propal->creer) { if (empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id'); if (empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -723,8 +772,8 @@ else if ($action == 'addline' && $user->rights->propal->creer) { $date_end = dol_mktime(0, 0, 0, GETPOST('date_end' . $predef . 'month'), GETPOST('date_end' . $predef . 'day'), GETPOST('date_end' . $predef . 'year')); // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->client); - $localtax2_tx = get_localtax($tva_tx, 2, $object->client); + $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty); $info_bits = 0; if ($tva_npr) @@ -745,30 +794,30 @@ else if ($action == 'addline' && $user->rights->propal->creer) { $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - unset($_POST ['prod_entry_mode']); + unset($_POST['prod_entry_mode']); - unset($_POST ['qty']); - unset($_POST ['type']); - unset($_POST ['remise_percent']); - unset($_POST ['price_ht']); - unset($_POST ['price_ttc']); - unset($_POST ['tva_tx']); - unset($_POST ['product_ref']); - unset($_POST ['product_label']); - unset($_POST ['product_desc']); - unset($_POST ['fournprice']); - unset($_POST ['buying_price']); - unset($_POST ['np_marginRate']); - unset($_POST ['np_markRate']); - unset($_POST ['dp_desc']); - unset($_POST ['idprod']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); unset($_POST['date_starthour']); unset($_POST['date_startmin']); @@ -804,8 +853,8 @@ else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('sa // Define vat_rate $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $object->client); - $localtax2_rate = get_localtax($vat_rate, 2, $object->client); + $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); $pu_ht = GETPOST('price_ht'); // Add buying price @@ -823,7 +872,7 @@ else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('sa if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST ["options_" . $key]); + unset($_POST["options_" . $key]); } } @@ -840,8 +889,8 @@ else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('sa $type = $product->type; $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->client->price_level)) - $price_min = $product->multiprices_min [$object->client->price_level]; + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + $price_min = $product->multiprices_min [$object->thirdparty->price_level]; $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); @@ -873,25 +922,25 @@ else if ($action == 'updateligne' && $user->rights->propal->creer && GETPOST('sa $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - unset($_POST ['qty']); - unset($_POST ['type']); - unset($_POST ['productid']); - unset($_POST ['remise_percent']); - unset($_POST ['price_ht']); - unset($_POST ['price_ttc']); - unset($_POST ['tva_tx']); - unset($_POST ['product_ref']); - unset($_POST ['product_label']); - unset($_POST ['product_desc']); - unset($_POST ['fournprice']); - unset($_POST ['buying_price']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['productid']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); } else { $db->rollback(); @@ -915,11 +964,11 @@ else if ($action == 'builddoc' && $user->rights->propal->creer) { $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - $result = propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db, $result); @@ -948,17 +997,17 @@ else if ($action == 'remove_file' && $user->rights->propal->creer) { // Set project else if ($action == 'classin' && $user->rights->propal->creer) { - $object->setProject($_POST ['projectid']); + $object->setProject($_POST['projectid']); } // Delai de livraison else if ($action == 'setavailability' && $user->rights->propal->creer) { - $result = $object->availability($_POST ['availability_id']); + $result = $object->availability($_POST['availability_id']); } // Origine de la propale else if ($action == 'setdemandreason' && $user->rights->propal->creer) { - $result = $object->demand_reason($_POST ['demand_reason_id']); + $result = $object->demand_reason($_POST['demand_reason_id']); } // Conditions de reglement @@ -967,11 +1016,11 @@ else if ($action == 'setconditions' && $user->rights->propal->creer) { } else if ($action == 'setremisepercent' && $user->rights->propal->creer) { - $result = $object->set_remise_percent($user, $_POST ['remise_percent']); + $result = $object->set_remise_percent($user, $_POST['remise_percent']); } else if ($action == 'setremiseabsolue' && $user->rights->propal->creer) { - $result = $object->set_remise_absolue($user, $_POST ['remise_absolue']); + $result = $object->set_remise_absolue($user, $_POST['remise_absolue']); } // Mode de reglement @@ -979,6 +1028,16 @@ else if ($action == 'setmode' && $user->rights->propal->creer) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); } +// bank account +else if ($action == 'setbankaccount' && $user->rights->propal->creer) { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); +} + +// shipping method +else if ($action == 'setshippingmethod' && $user->rights->propal->creer) { + $result=$object->setShippingMethod(GETPOST('shipping_method_id', 'int')); +} + /* * Ordonnancement des lignes */ @@ -991,11 +1050,11 @@ else if ($action == 'up' && $user->rights->propal->creer) { $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id . '#' . GETPOST('rowid')); @@ -1010,11 +1069,11 @@ else if ($action == 'down' && $user->rights->propal->creer) { $outputlangs = $langs; if (! empty($conf->global->MAIN_MULTILANGS)) { $outputlangs = new Translate("", $conf); - $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->client->default_lang); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($id); // Reload to get new records - propale_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $id . '#' . GETPOST('rowid')); @@ -1047,11 +1106,13 @@ else if ($action == 'down' && $user->rights->propal->creer) { $action = 'edit_extras'; } -if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->propal->creer) { - if ($action == 'addcontact') { +if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->propal->creer) +{ + if ($action == 'addcontact') + { if ($object->id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $result = $object->add_contact($contactid, $_POST ["type"], $_POST ["source"]); + $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]); } if ($result >= 0) { @@ -1105,13 +1166,71 @@ $companystatic = new Societe($db); $now = dol_now(); // Add new proposal -if ($action == 'create') { +if ($action == 'create') +{ print_fiche_titre($langs->trans("NewProp")); $soc = new Societe($db); if ($socid > 0) $res = $soc->fetch($socid); + // Load objectsrc + if (! empty($origin) && ! empty($originid)) + { + // Parse element/subelement (ex: project_task) + $element = $subelement = $origin; + if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { + $element = $regs [1]; + $subelement = $regs [2]; + } + + if ($element == 'project') { + $projectid = $originid; + } else { + // For compatibility + if ($element == 'order' || $element == 'commande') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; + $subelement = 'propal'; + } + if ($element == 'contract') { + $element = $subelement = 'contrat'; + } + if ($element == 'shipping') { + $element = $subelement = 'expedition'; + } + + dol_include_once('/' . $element . '/class/' . $subelement . '.class.php'); + + $classname = ucfirst($subelement); + $objectsrc = new $classname($db); + $objectsrc->fetch($originid); + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + { + $objectsrc->fetch_lines(); + } + $objectsrc->fetch_thirdparty(); + + $projectid = (! empty($objectsrc->fk_project) ? $objectsrc->fk_project : ''); + $ref_client = (! empty($objectsrc->ref_client) ? $objectsrc->ref_client : ''); + $ref_int = (! empty($objectsrc->ref_int) ? $objectsrc->ref_int : ''); + + $soc = $objectsrc->thirdparty; + + $cond_reglement_id = (! empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(! empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); + $mode_reglement_id = (! empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(! empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); + $remise_percent = (! empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(! empty($soc->remise_percent)?$soc->remise_percent:0)); + $remise_absolue = (! empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(! empty($soc->remise_absolue)?$soc->remise_absolue:0)); + $dateinvoice = (empty($dateinvoice)?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$dateinvoice); + + // Replicate extrafields + $objectsrc->fetch_optionals($originid); + $object->array_options = $objectsrc->array_options; + } + } + $object = new Propal($db); print ''; @@ -1148,12 +1267,16 @@ if ($action == 'create') { } print '
    ' . "\n"; - // Contacts - if ($socid > 0) { + // Contacts (ask contact only if thirdparty already defined). TODO do this also into order and invoice. + if ($socid > 0) + { print "'; + } + if ($socid > 0) + { // Ligne info remises tiers print ''; + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && $conf->module->banque->enabled) { + print ''; + } + // What trigger creation print ''; + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + } + // Delivery date (or manufacturing) print ''; print ''; print ''; @@ -1250,16 +1387,62 @@ if ($action == 'create') { print $object->showOptionals($extrafields, 'edit'); } - print "
    '.$langs->trans("SearchAMailing").'
    '.$langs->trans("LastMailings",$limit).''.$langs->trans("DateCreation").''.$langs->trans("NbOfEMails").''.$langs->trans("AllEMailings").'
    '.$langs->trans("AllEMailings").'
    '.img_object($langs->trans("ShowEMail"),"email").' '.$obj->rowid.''.img_object($langs->trans("ShowEMail"),"email").' '.$obj->rowid.''.dol_trunc($obj->titre,38).''.dol_print_date($db->jdate($obj->date_creat),'day').''.($obj->nbemail?$obj->nbemail:"0").'
    '; + print ''; print img_object($langs->trans("ShowEMail"),"email").' '.stripslashes($obj->rowid).''.$obj->titre.'
    " . $langs->trans("DefaultContact") . ''; - $form->select_contacts($soc->id, $setcontact, 'contactidp', 1, $srccontactslist); + $form->select_contacts($soc->id, $contactid, 'contactid', 1, $srccontactslist); print '
    ' . $langs->trans('Discounts') . ''; if ($soc->remise_percent) @@ -1188,6 +1311,13 @@ if ($action == 'create') { $form->select_types_paiements($soc->mode_reglement_id, 'mode_reglement_id'); print '
    ' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
    ' . $langs->trans('Source') . ''; $form->selectInputReason('', 'demand_reason_id', "SRC_PROP", 1); @@ -1198,6 +1328,13 @@ if ($action == 'create') { $form->selectAvailabilityDelay('', 'availability_id', '', 1); print '
    ' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print '
    ' . $langs->trans("DeliveryDate") . ''; @@ -1235,7 +1372,7 @@ if ($action == 'create') { $numprojet = $formproject->select_projects($soc->id, $projectid); if ($numprojet == 0) { $langs->load("projects"); - print '   ' . $langs->trans("AddProject") . ''; + print '   ' . $langs->trans("AddProject") . ''; } print '
    "; + + // Lines from source + if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) + { + // TODO for compatibility + if ($origin == 'contrat') { + // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva + $objectsrc->remise_absolue = $remise_absolue; + $objectsrc->remise_percent = $remise_percent; + $objectsrc->update_price(1, - 1, 1); + } + + print "\n"; + print "\n"; + print '' . "\n"; + print '' . "\n"; + print '' . "\n"; + print ''; + print ''; + + $newclassname = $classname; + if ($newclassname == 'Propal') + $newclassname = 'CommercialProposal'; + elseif ($newclassname == 'Commande') + $newclassname = 'Order'; + elseif ($newclassname == 'Expedition') + $newclassname = 'Sending'; + elseif ($newclassname == 'Fichinter') + $newclassname = 'Intervention'; + + print '
    ' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
    ' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . '
    ' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . "
    ' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . "
    ' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . "
    ' . $langs->trans('TotalTTC') . '' . price($objectsrc->total_ttc) . "
    \n"; + + print '
    '; + /* * Combobox pour la fonction de copie */ - if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) { - print ''; - } + if (empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print ''; if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print ''; if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) @@ -1303,7 +1486,8 @@ if ($action == 'create') { print ''; } - if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) { + if (! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) + { print '
    ' . $langs->trans("CreateEmptyPropal") . '
    '; if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) { $lib = $langs->trans("ProductsAndServices"); @@ -1332,6 +1516,7 @@ if ($action == 'create') { } if (! empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE) || ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE)) print '

    '; + $langs->load("bills"); print '
    '; print ''; @@ -1339,6 +1524,22 @@ if ($action == 'create') { print '
    '; print ""; + + + // Show origin lines + if (! empty($origin) && ! empty($originid) && is_object($objectsrc)) { + print '
    '; + + $title = $langs->trans('ProductsAndServices'); + print_titre($title); + + print ''; + + $objectsrc->printOriginLinesList(); + + print '
    '; + } + } else { /* * Show object in view mode @@ -1390,7 +1591,7 @@ if ($action == 'create') { $numref = $object->getNextNumRef($soc); if (empty($numref)) { $error ++; - dol_htmloutput_errors($object->error); + setEventMessage($object->error, 'errors'); } } else { $numref = $object->ref; @@ -1596,6 +1797,25 @@ if ($action == 'create') { print '
'; + print ''; + if ($action != 'editshippingmethod' && $user->rights->propal->creer) + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; + print '
'; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
'; print ''; @@ -1664,7 +1884,8 @@ if ($action == 'create') { print ''; } - if ($soc->outstanding_limit) { + if ($soc->outstanding_limit) + { // Outstanding Bill print ''; } - // Other attributes (TODO Move this into an include) - $res = $object->fetch_optionals($object->id, $extralabels); - $parameters = array('colspan' => ' colspan="3"'); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified - // by - // hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - foreach ($extrafields->attribute_label as $key => $label) { - if ($action == 'edit_extras') { - $value = (isset($_POST ["options_" . $key]) ? $_POST ["options_" . $key] : $object->array_options ["options_" . $key]); - } else { - $value = $object->array_options ["options_" . $key]; - } - if ($extrafields->attribute_type [$key] == 'separate') { - print $extrafields->showSeparator($key); - } else { - print 'attribute_required [$key])) - print ' class="fieldrequired"'; - print '>' . $label . '' . "\n"; - } - } + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_PROPOSAL) && $conf->banque->enabled) + { + // Bank Account + print ''; + print ''; } + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + // Amount HT print ''; print ''; @@ -1741,13 +1939,13 @@ if ($action == 'create') { print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1") // Localtax1 + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { print ''; print ''; print ''; } - if ($mysoc->localtax2_assuj == "1") // Localtax2 + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 { print ''; print ''; @@ -1806,7 +2004,7 @@ if ($action == 'create') { { $var = true; - // Add free products/services + // Add products/services form $object->formAddObjectLine(1, $mysoc, $soc); $parameters = array(); @@ -1872,7 +2070,7 @@ if ($action == 'create') { // else on // page. { - print '' . $langs->trans("AddAction") . ''; + print '' . $langs->trans("AddAction") . ''; } // Edit if ($object->statut == 1 && $user->rights->propal->creer) { @@ -1880,7 +2078,7 @@ if ($action == 'create') { } // ReOpen - if (($object->statut == 2 || $object->statut == 3) && $user->rights->propal->cloturer) { + if (($object->statut == 2 || $object->statut == 3 || $object->statut == 4) && $user->rights->propal->cloturer) { print ''; } @@ -1896,7 +2094,7 @@ if ($action == 'create') { // Create an order if (! empty($conf->commande->enabled) && $object->statut == 2) { if ($user->rights->commande->creer) { - print ''; + print ''; } } @@ -1905,7 +2103,7 @@ if ($action == 'create') { $langs->load("contracts"); if ($user->rights->contrat->creer) { - print ''; + print ''; } } @@ -1985,26 +2183,31 @@ if ($action == 'create') { */ if ($action == 'presend') { + $object->fetch_projet(); + $ref = dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $fileparams = dol_most_recent_file($conf->propal->dir_output . '/' . $ref, preg_quote($ref, '/')); $file = $fileparams ['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->thirdparty->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('commercial'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - - $result = propale_pdf_create($db, $object, GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db, $result); exit(); @@ -2019,6 +2222,7 @@ if ($action == 'create') { // Create form object include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -2031,9 +2235,9 @@ if ($action == 'create') { $formmail->withtocc = $liste; $formmail->withtoccc = (! empty($conf->global->MAIN_EMAIL_USECCC) ? $conf->global->MAIN_EMAIL_USECCC : false); if (empty($object->ref_client)) { - $formmail->withtopic = $langs->trans('SendPropalRef', '__PROPREF__'); + $formmail->withtopic = $outputlangs->trans('SendPropalRef', '__PROPREF__'); } else if (! empty($object->ref_client)) { - $formmail->withtopic = $langs->trans('SendPropalRef', '__PROPREF__(__REFCLIENT__)'); + $formmail->withtopic = $outputlangs->trans('SendPropalRef', '__PROPREF__ (__REFCLIENT__)'); } $formmail->withfile = 2; $formmail->withbody = 1; @@ -2041,11 +2245,13 @@ if ($action == 'create') { $formmail->withcancel = 1; // Tableau des substitutions - $formmail->substit ['__PROPREF__'] = $object->ref; - $formmail->substit ['__SIGNATURE__'] = $user->signature; - $formmail->substit ['__REFCLIENT__'] = $object->ref_client; - $formmail->substit ['__PERSONALIZED__'] = ''; - $formmail->substit ['__CONTACTCIVNAME__'] = ''; + $formmail->substit['__PROPREF__'] = $object->ref; + $formmail->substit['__SIGNATURE__'] = $user->signature; + $formmail->substit['__REFCLIENT__'] = $object->ref_client; + $formmail->substit['__THIRPARTY_NAME__'] = $object->thirdparty->name; + $formmail->substit['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); + $formmail->substit['__PERSONALIZED__'] = ''; + $formmail->substit['__CONTACTCIVNAME__'] = ''; // Find the good contact adress $custcontact = ''; @@ -2054,7 +2260,7 @@ if ($action == 'create') { if (is_array($contactarr) && count($contactarr) > 0) { foreach ($contactarr as $contact) { - if ($contact ['libelle'] == $langs->trans('TypeContact_propal_external_CUSTOMER')) { + if ($contact ['libelle'] == $langs->trans('TypeContact_propal_external_CUSTOMER')) { // TODO Use code and not label $contactstatic = new Contact($db); $contactstatic->fetch($contact ['id']); $custcontact = $contactstatic->getFullName($langs, 1); @@ -2062,15 +2268,15 @@ if ($action == 'create') { } if (! empty($custcontact)) { - $formmail->substit ['__CONTACTCIVNAME__'] = $custcontact; + $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; } } // Tableau des parametres complementaires - $formmail->param ['action'] = 'send'; - $formmail->param ['models'] = 'propal_send'; - $formmail->param ['id'] = $object->id; - $formmail->param ['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; + $formmail->param['action'] = 'send'; + $formmail->param['models'] = 'propal_send'; + $formmail->param['id'] = $object->id; + $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; // Init list of files if (GETPOST("mode") == 'init') { $formmail->clear_attached_files(); diff --git a/htdocs/comm/propal/apercu.php b/htdocs/comm/propal/apercu.php index ce80783c731..87281e7ea63 100644 --- a/htdocs/comm/propal/apercu.php +++ b/htdocs/comm/propal/apercu.php @@ -3,7 +3,8 @@ * Copyright (C) 2004 Eric Seigne * Copyright (C) 2004-2007 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2011 Juanjo Menent + * Copyright (C) 2014 Frederic France * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,14 +23,13 @@ /** * \file htdocs/comm/propal/apercu.php * \ingroup propal - * \brief Page de l'onglet apercu d'une propal + * \brief Preview tab of propal */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $langs->load('propal'); $langs->load("bills"); @@ -44,18 +44,11 @@ $result = restrictedArea($user, 'propal', $id); /* - * View + * View Mode */ llxHeader(); -$form = new Form($db); - -/* *************************************************************************** */ -/* */ -/* Mode fiche */ -/* */ -/* *************************************************************************** */ if ($id > 0 || ! empty($ref)) { @@ -73,29 +66,30 @@ if ($id > 0 || ! empty($ref)) /* * Propal */ - print '
'; @@ -1653,7 +1873,7 @@ if ($action == 'create') { print ''; $proj = new Project($db); $proj->fetch($object->fk_project); - print ''; + print ''; print $proj->ref; print ''; print '
'; print $langs->trans('OutstandingBill'); @@ -1675,53 +1896,30 @@ if ($action == 'create') { print '
'; - // Convert date into timestamp format - if (in_array($extrafields->attribute_type [$key], array('date','datetime'))) { - $value = isset($_POST ["options_" . $key]) ? dol_mktime($_POST ["options_" . $key . "hour"], $_POST ["options_" . $key . "min"], 0, $_POST ["options_" . $key . "month"], $_POST ["options_" . $key . "day"], $_POST ["options_" . $key . "year"]) : $db->jdate($object->array_options ['options_' . $key]); - } - - if ($action == 'edit_extras' && $user->rights->propal->creer && GETPOST('attribute') == $key) { - print '
'; - print ''; - print ''; - print ''; - print ''; - - print $extrafields->showInputField($key, $value); - - print ''; - - print '
'; - } else { - print $extrafields->showOutputField($key, $value); - if ($object->statut == 0 && $user->rights->propal->creer) - print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; - } - print '
'; + print ''; + if ($action != 'editbankaccount' && $user->rights->propal->creer) + print ''; + print '
'; + print $langs->trans('BankAccount'); + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print '
'; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '
' . $langs->trans('AmountHT') . '' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, '', $langs, 0, - 1, - 1, $conf->currency) . '
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, '', $langs, 0, - 1, - 1, $conf->currency) . '
'; + print '
'; - // Ref - print ''; + // Ref + print ''; + print ''; + print ''; - // Ref client - print ''; - print ''; + // Ref client + print ''; + print ''; + print ''; - $rowspan=2; - // Tiers - print ''; - print ''; + // Thirdparty + print ''; + print ''; + print ''; - // Ligne info remises tiers + // Status + print ''; + print ''; + print ''; + + // Discount print ''; + print '.'; + print ''; - // ligne - // partie Gauche - print ''; + // Date + print ''; + print ''; - // partie Droite sur $rowspan lignes - print ''; + print ''; + print ''; + + // Total VAT - left part + print ''; + print ''; + print ''; + + // Total TTC - left part + print ''; + print ''; + print ''; + + print '
'.$langs->trans('Ref').''.$object->ref.'
'.$langs->trans('Ref').''.$object->ref.'
'; - print ''; - print '
'; - print $langs->trans('RefCustomer').''; - print '
'; - print '
'; - print $object->ref_client; - print '
'.$langs->trans('RefCustomer').''.$object->ref_client.'
'.$langs->trans('Company').''.$soc->getNomUrl(1).'
'.$langs->trans('Company').''.$soc->getNomUrl(1).'
'.$langs->trans("Status").''.$object->getLibStatut(4).'
'.$langs->trans('Discounts').''; if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_percent); else print $langs->trans("CompanyHasNoRelativeDiscount"); @@ -103,44 +97,43 @@ if ($id > 0 || ! empty($ref)) print '. '; if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount",$absolute_discount,$langs->trans("Currency".$conf->currency)); else print $langs->trans("CompanyHasNoAbsoluteDiscount"); - print '.'; - print '
'.$langs->trans('Date').''; - print dol_print_date($object->date,'daytext'); - print '
'.$langs->trans('Date').''.dol_print_date($object->date,'daytext').''; + // Right part with $rowspan lines + $rowspan=4; + print ''; - /* - * Documents - */ - $objectref = dol_sanitizeFileName($object->ref); - $dir_output = $conf->propal->dir_output . "/"; - $filepath = $dir_output . $objectref . "/"; - $file = $filepath . $objectref . ".pdf"; - $filedetail = $filepath . $objectref . "-detail.pdf"; + /* + * Documents + */ + $objectref = dol_sanitizeFileName($object->ref); + $dir_output = $conf->propal->dir_output . "/"; + $filepath = $dir_output . $objectref . "/"; + $file = $filepath . $objectref . ".pdf"; + $filedetail = $filepath . $objectref . "-detail.pdf"; $relativepath = $objectref.'/'.$objectref.'.pdf'; $relativepathdetail = $objectref.'/'.$objectref.'-detail.pdf'; // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png") - $fileimage = $file.'_preview.png'; // If PDF has 1 page + $fileimage = $file.'_preview.png'; // If PDF has 1 page $fileimagebis = $file.'_preview-0.pdf.png'; // If PDF has more than one page $relativepathimage = $relativepath.'_preview.png'; - $var=true; + $var=true; // Si fichier PDF existe if (file_exists($file)) { $encfile = urlencode($file); - print_titre($langs->trans("Documents")); - print ''; + print '
'; + print ''; - print ""; + print ''; print ''; @@ -166,13 +159,25 @@ if ($id > 0 || ! empty($ref)) } } - print ""; - print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("Documents").'
".$langs->trans("Propal")." PDF
'.$langs->trans("Proposal").' PDF'.$object->ref.'.pdf
'.$langs->trans('AmountHT').''.price($object->price).''.$langs->trans("Currency".$conf->currency).'
'; + // Total HT - left part + print '
'.$langs->trans('AmountHT').'' . price($object->total_ht, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountVAT').'' . price($object->total_tva, '', $langs, 0, - 1, - 1, $conf->currency) . '
'.$langs->trans('AmountTTC').'' . price($object->total_ttc, '', $langs, 0, - 1, - 1, $conf->currency) . '
'; dol_fiche_end(); } @@ -183,10 +188,13 @@ if ($id > 0 || ! empty($ref)) } } +print ''; +print ''; +print '
'; +print '
'; // Si fichier png PDF d'1 page trouve if (file_exists($fileimage)) { - print ''; + print ''; } // Si fichier png PDF de plus d'1 page trouve elseif (file_exists($fileimagebis)) @@ -199,13 +207,15 @@ elseif (file_exists($fileimagebis)) if (file_exists($dir_output.$preview)) { - print '

'; + print '

'; } } } - print '

'; +print '
'; -$db->close(); llxFooter(); + +$db->close(); diff --git a/htdocs/comm/propal/class/index.html b/htdocs/comm/propal/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 846bb5acb10..fb9d5257d49 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -6,10 +6,11 @@ * Copyright (C) 2005-2013 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2008 Raphael Bertrand - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2010-2011 Philippe Grand * Copyright (C) 2012-2014 Christophe Battarel * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -79,6 +80,7 @@ class Propal extends CommonObject var $cond_reglement_id; var $cond_reglement_code; + var $fk_account; // Id of bank account var $mode_reglement_id; var $mode_reglement_code; var $remise; @@ -91,6 +93,7 @@ class Propal extends CommonObject var $fk_address; var $address_type; var $address; + var $shipping_method_id; var $availability_id; var $availability_code; var $demand_reason_id; @@ -355,7 +358,7 @@ class Propal extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, '', $localtaxes_type); $total_ht = $tabprice[0]; @@ -451,7 +454,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR); $this->db->rollback(); return -1; } @@ -518,7 +520,7 @@ class Propal extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type,'', $localtaxes_type); $total_ht = $tabprice[0]; @@ -613,7 +615,6 @@ class Propal extends CommonObject { $this->error=$this->db->error(); $this->db->rollback(); - dol_syslog(get_class($this)."::updateline Error=".$this->error, LOG_ERR); return -1; } } @@ -666,7 +667,7 @@ class Propal extends CommonObject * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >=0 if OK */ - function create($user='', $notrigger=0) + function create($user, $notrigger=0) { global $langs,$conf,$mysoc,$hookmanager; $error=0; @@ -732,8 +733,10 @@ class Propal extends CommonObject $sql.= ", fin_validite"; $sql.= ", fk_cond_reglement"; $sql.= ", fk_mode_reglement"; + $sql.= ", fk_account"; $sql.= ", ref_client"; $sql.= ", date_livraison"; + $sql.= ", fk_shipping_method"; $sql.= ", fk_availability"; $sql.= ", fk_input_reason"; $sql.= ", fk_projet"; @@ -757,15 +760,17 @@ class Propal extends CommonObject $sql.= ", ".($this->fin_validite!=''?"'".$this->db->idate($this->fin_validite)."'":"null"); $sql.= ", ".$this->cond_reglement_id; $sql.= ", ".$this->mode_reglement_id; + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ", '".$this->db->escape($this->ref_client)."'"; $sql.= ", ".($this->date_livraison!=''?"'".$this->db->idate($this->date_livraison)."'":"null"); + $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); $sql.= ", ".$this->availability_id; $sql.= ", ".$this->demand_reason_id; $sql.= ", ".($this->fk_project?$this->fk_project:"null"); $sql.= ", ".$conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -776,7 +781,7 @@ class Propal extends CommonObject $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."propal SET ref='".$this->ref."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; @@ -857,6 +862,8 @@ class Propal extends CommonObject $resql=$this->update_price(1); if ($resql) { + $action='update'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('propaldao')); @@ -877,24 +884,22 @@ class Propal extends CommonObject if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('PROPAL_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } } else - { + { + $this->error=$this->db->lasterror(); $error++; } } } else - { + { + $this->error=$this->db->lasterror(); $error++; } @@ -906,16 +911,13 @@ class Propal extends CommonObject } else { - $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create -2 ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } } else { - $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create -1 ".$this->error, LOG_ERR); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } @@ -933,7 +935,7 @@ class Propal extends CommonObject { $this->products=$this->lines; - return $this->create(); + return $this->create($user); } /** @@ -1033,14 +1035,10 @@ class Propal extends CommonObject if ($reshook < 0) $error++; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_CLONE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('PROPAL_CLONE',$user); + if ($result < 0) { $error++; } + // End call triggers } // End @@ -1083,6 +1081,8 @@ class Propal extends CommonObject $sql.= ", p.fk_input_reason"; $sql.= ", p.fk_cond_reglement"; $sql.= ", p.fk_mode_reglement"; + $sql.= ', p.fk_account'; + $sql.= ", p.fk_shipping_method"; $sql.= ", c.label as statut_label"; $sql.= ", ca.code as availability_code, ca.label as availability"; $sql.= ", dr.code as demand_reason_code, dr.label as demand_reason"; @@ -1098,7 +1098,7 @@ class Propal extends CommonObject if ($ref) $sql.= " AND p.ref='".$ref."'"; else $sql.= " AND p.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1136,6 +1136,7 @@ class Propal extends CommonObject $this->datep = $this->db->jdate($obj->dp); // deprecated $this->fin_validite = $this->db->jdate($obj->dfv); $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; $this->availability_id = $obj->fk_availability; $this->availability_code = $obj->availability_code; $this->availability = $obj->availability; @@ -1147,6 +1148,7 @@ class Propal extends CommonObject $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement; + $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; $this->cond_reglement_id = $obj->fk_cond_reglement; $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement; @@ -1249,7 +1251,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return -1; } @@ -1269,7 +1270,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return -1; } } @@ -1282,6 +1282,8 @@ class Propal extends CommonObject */ function update_extrafields($user) { + $action='update'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('propaldao')); @@ -1344,71 +1346,77 @@ class Propal extends CommonObject { $num = $this->ref; } + $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."propal"; $sql.= " SET ref = '".$num."',"; $sql.= " fk_statut = 1, date_valid='".$this->db->idate($now)."', fk_user_valid=".$user->id; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - dol_syslog(get_class($this).'::valid sql='.$sql); - if ($this->db->query($sql)) + dol_syslog(get_class($this)."::valid", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) + { + dol_print_error($this->db); + $error++; + } + + // Trigger calls + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('PROPAL_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + + if (! $error) { - if (! $notrigger) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } + $this->oldref = $this->ref; - if (! $error) - { - // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { - // Rename of propal directory ($this->ref = old ref, $num = new ref) - // to not lose the linked files - $oldref = dol_sanitizeFileName($this->ref); - $newref = dol_sanitizeFileName($num); - $dirsource = $conf->propal->dir_output.'/'.$oldref; - $dirdest = $conf->propal->dir_output.'/'.$newref; - if (file_exists($dirsource)) - { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + // Rename directory if dir was a temporary ref + if (preg_match('/^[\(]?PROV/i', $this->ref)) + { + // Rename of propal directory ($this->ref = old ref, $num = new ref) + // to not lose the linked files + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->propal->dir_output.'/'.$oldref; + $dirdest = $conf->propal->dir_output.'/'.$newref; - if (@rename($dirsource, $dirdest)) - { + if (file_exists($dirsource)) + { + dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + if (@rename($dirsource, $dirdest)) + { + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->propal->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } + } + } + } - dol_syslog("Rename ok"); - // Deleting old PDF in new rep - dol_delete_file($conf->propal->dir_output.'/'.$newref.'/'.$oldref.'*.*'); - } - } - } + $this->ref=$num; + $this->brouillon=0; + $this->statut = 1; + $this->user_valid_id=$user->id; + $this->datev=$now; - $this->ref=$num; - $this->brouillon=0; - $this->statut = 1; - $this->user_valid_id=$user->id; - $this->datev=$now; - - $this->db->commit(); - return 1; - } - else - { - $this->db->rollback(); - return -2; - } + $this->db->commit(); + return 1; } else { - $this->db->rollback(); - return -1; + $this->db->rollback(); + return -1; } } } @@ -1435,7 +1443,7 @@ class Propal extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."propal SET datep = '".$this->db->idate($date)."'"; $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - dol_syslog(get_class($this)."::set_date sql=".$sql); + dol_syslog(get_class($this)."::set_date", LOG_DEBUG); if ($this->db->query($sql) ) { $this->date = $date; @@ -1445,7 +1453,6 @@ class Propal extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::set_date ".$this->error, LOG_ERR); return -1; } } @@ -1472,7 +1479,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_echeance Erreur SQL".$this->error, LOG_ERR); return -1; } } @@ -1625,7 +1631,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_remise_percent Error sql=$sql"); return -1; } } @@ -1660,7 +1665,6 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_remise_absolue Error sql=$sql"); return -1; } } @@ -1692,7 +1696,7 @@ class Propal extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::reopen sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::reopen", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -1701,25 +1705,24 @@ class Propal extends CommonObject { if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_REOPEN',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('PROPAL_REOPEN',$user); + if ($result < 0) { $error++; } + // End call triggers } } // Commit or rollback if ($error) { - foreach($this->errors as $errmsg) - { - dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); - $this->error.=($this->error?', '.$errmsg:$errmsg); - } + if (!empty($this->errors)) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + } $this->db->rollback(); return -1*$error; } @@ -1756,8 +1759,14 @@ class Propal extends CommonObject $resql=$this->db->query($sql); if ($resql) { + $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf; + $trigger_name='PROPAL_CLOSE_REFUSED'; + if ($statut == 2) { + $trigger_name='PROPAL_CLOSE_SIGNED'; + $modelpdf=$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf; + // The connected company is classified as a client $soc=new Societe($this->db); $soc->id = $this->socid; @@ -1769,59 +1778,41 @@ class Propal extends CommonObject $this->db->rollback(); return -2; } + } + if ($statut == 4) + { + $trigger_name='PROPAL_CLASSIFY_BILLED'; + } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $outputlangs = new Translate("",$conf); - $newlang=(GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang); - $outputlangs->setDefaultLang($newlang); - } - //$ret=$object->fetch($id); // Reload to get new records - propale_pdf_create($this->db, $this, $conf->global->PROPALE_ADDON_PDF_ODT_TOBILL?$conf->global->PROPALE_ADDON_PDF_ODT_TOBILL:$this->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + // Define output language + $outputlangs = $langs; + if (! empty($conf->global->MAIN_MULTILANGS)) + { + $outputlangs = new Translate("",$conf); + $newlang=(GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang); + $outputlangs->setDefaultLang($newlang); + } + //$ret=$object->fetch($id); // Reload to get new records + $this->generateDocument($modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_CLOSE_SIGNED',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger($trigger_name,$user); + if ($result < 0) { $error++; } + // End call triggers + + if ( ! $error ) + { + $this->db->commit(); + return 1; } else { - - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - // Define output language - $outputlangs = $langs; - if (! empty($conf->global->MAIN_MULTILANGS)) - { - $outputlangs = new Translate("",$conf); - $newlang=(GETPOST('lang_id') ? GETPOST('lang_id') : $this->client->default_lang); - $outputlangs->setDefaultLang($newlang); - } - //$ret=$object->fetch($id); // Reload to get new records - propale_pdf_create($this->db, $this, $conf->global->PROPALE_ADDON_PDF_ODT_CLOSED?$conf->global->PROPALE_ADDON_PDF_ODT_CLOSED:$this->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_CLOSE_REFUSED',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + $this->db->rollback(); + return -1; } - - $this->db->commit(); - return 1; } else { @@ -2018,7 +2009,7 @@ class Propal extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."facture"; $sql.= " WHERE rowid IN (".implode(',',$linkedInvoices).")"; - dol_syslog(get_class($this)."::InvoiceArrayList sql=".$sql); + dol_syslog(get_class($this)."::InvoiceArrayList", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -2072,15 +2063,11 @@ class Propal extends CommonObject $this->db->begin(); - if (! $error && ! $notrigger) + if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PROPAL_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } + // Call trigger + $result=$this->call_trigger('PROPAL_DELETE',$user); + if ($result < 0) { $error++; } // End call triggers } @@ -2151,14 +2138,13 @@ class Propal extends CommonObject if (! $error) { - dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); + dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG); $this->db->commit(); return 1; } else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return 0; } @@ -2166,7 +2152,6 @@ class Propal extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -3; } @@ -2174,15 +2159,12 @@ class Propal extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } } else { - $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2560,16 +2542,21 @@ class Propal extends CommonObject { $mybool=false; - $file = $conf->global->PROPALE_ADDON.".php"; - $classname = $conf->global->PROPALE_ADDON; + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + $file = $conf->global->PROPALE_ADDON.".php"; + $classname = $conf->global->PROPALE_ADDON; + + // Include file with class + foreach ($conf->file->dol_document_root as $dirroot) + { + $dir = $dirroot.$reldir."/core/modules/propale/"; + // Load file with numbering class (if found) + $mybool|=@include_once $dir.$file; + } + } - // Include file with class - foreach ($conf->file->dol_document_root as $dirroot) - { - $dir = $dirroot."/core/modules/propale/"; - // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; - } if (! $mybool) { @@ -2658,7 +2645,7 @@ class Propal extends CommonObject $sql.= ' WHERE pt.fk_propal = '.$this->id; $sql.= ' ORDER BY pt.rang ASC, pt.rowid'; - dol_syslog(get_class($this).'::getLinesArray sql='.$sql,LOG_DEBUG); + dol_syslog(get_class($this).'::getLinesArray', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -2709,11 +2696,45 @@ class Propal extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::getLinesArray Error sql=$sql, error=".$this->error,LOG_ERR); return -1; } } + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force model to use ('' to not force) + * @param Translate $outputlangs Object langs to use for output + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$user,$langs; + + $langs->load("propale"); + + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->PROPALE_ADDON_PDF)) + { + $modele = $conf->global->PROPALE_ADDON_PDF; + } + else + { + $modele = 'azur'; + } + } + + $modelpath = "core/modules/propale/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + + } @@ -2878,7 +2899,7 @@ class PropaleLigne extends CommonObject $error=0; - dol_syslog("PropaleLigne::insert rang=".$this->rang); + dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters if (empty($this->tva_tx)) $this->tva_tx=0; @@ -2946,7 +2967,7 @@ class PropaleLigne extends CommonObject $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= ')'; - dol_syslog(get_class($this).'::insert sql='.$sql, LOG_DEBUG); + dol_syslog(get_class($this).'::insert', LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2964,14 +2985,14 @@ class PropaleLigne extends CommonObject if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEPROPAL_INSERT',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEPROPAL_INSERT',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -2980,7 +3001,6 @@ class PropaleLigne extends CommonObject else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this).'::insert Error '.$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2999,7 +3019,7 @@ class PropaleLigne extends CommonObject $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."propaldet WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::delete sql=".$sql, LOG_DEBUG); + dol_syslog("PropaleLigne::delete", LOG_DEBUG); if ($this->db->query($sql) ) { @@ -3015,14 +3035,14 @@ class PropaleLigne extends CommonObject } } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEPROPAL_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEPROPAL_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; } - // Fin appel triggers + // End call triggers $this->db->commit(); @@ -3031,7 +3051,6 @@ class PropaleLigne extends CommonObject else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog("PropaleLigne::delete Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -3110,7 +3129,7 @@ class PropaleLigne extends CommonObject $sql.= " , date_end=".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3126,14 +3145,14 @@ class PropaleLigne extends CommonObject if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEPROPAL_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEPROPAL_UPDATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -3142,7 +3161,6 @@ class PropaleLigne extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -3165,7 +3183,7 @@ class PropaleLigne extends CommonObject $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("PropaleLigne::update_total sql=$sql"); + dol_syslog("PropaleLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -3176,7 +3194,6 @@ class PropaleLigne extends CommonObject else { $this->error=$this->db->error(); - dol_syslog("PropaleLigne::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } diff --git a/htdocs/comm/propal/index.php b/htdocs/comm/propal/index.php index f89b6bfda86..de51cf63104 100644 --- a/htdocs/comm/propal/index.php +++ b/htdocs/comm/propal/index.php @@ -127,7 +127,7 @@ if ($resql) $var=!$var; print "
'.$propalstatic->LibStatut($status,0).''.(isset($vals[$status])?$vals[$status]:0).''.(isset($vals[$status])?$vals[$status]:0).'
'; print ''; - print ''; + print ''; if ($num) { @@ -433,7 +433,7 @@ if (! empty($conf->propal->enabled)) print ''; - print ''; + print ''; print ''; @@ -453,7 +453,7 @@ if (! empty($conf->propal->enabled)) */ /*if (! empty($conf->propal->enabled)) { - $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom as name, s.rowid as socid"; $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"; @@ -471,7 +471,7 @@ if (! empty($conf->propal->enabled)) print '
'.$langs->trans("ProposalsToProcess").' ('.$num.')
'.$langs->trans("ProposalsToProcess").' ('.$num.')
'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,24).''.$propalstatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; print ''; - print ''; + print ''; if ($num) { @@ -505,7 +505,7 @@ if (! empty($conf->propal->enabled)) print ''; - print ''; + print ''; print ''; diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index ba0a49f2772..66b36e0320f 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -56,6 +56,8 @@ $search_societe=GETPOST('search_societe','alpha'); $search_montant_ht=GETPOST('search_montant_ht','alpha'); $search_author=GETPOST('search_author','alpha'); $search_town=GETPOST('search_town','alpha'); +$viewstatut=$db->escape(GETPOST('viewstatut')); +$object_statut=$db->escape(GETPOST('propal_statut')); $sall=GETPOST("sall"); $mesg=(GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); @@ -78,6 +80,26 @@ if (! empty($socid)) } $result = restrictedArea($user, $module, $objectid, $dbtable); +if (GETPOST("button_removefilter") || GETPOST("button_removefilter_x")) // Both tests are required to be compatible with all browsers +{ + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_refcustomer=''; + $search_societe=''; + $search_montant_ht=''; + $search_author=''; + $search_town=''; + $year=''; + $month=''; + $viewstatut=''; + $object_statut=''; +} + +if($object_statut != '') +$viewstatut=$object_statut; + // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('propallist')); @@ -91,22 +113,8 @@ $hookmanager->initHooks(array('propallist')); $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -// Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x")) -{ - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_societe=''; - $search_montant_ht=''; - $search_author=''; - $search_town=''; - $year=''; - $month=''; -} /* @@ -131,17 +139,12 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -$viewstatut=$db->escape(GETPOST('viewstatut')); -$object_statut = $db->escape(GETPOST('propal_statut')); -if($object_statut != '') -$viewstatut=$object_statut; - if (! $sortfield) $sortfield='p.datep'; if (! $sortorder) $sortorder='DESC'; $limit = $conf->liste_limit; -$sql = 'SELECT s.rowid, s.nom, s.town, s.client, s.code_client,'; +$sql = 'SELECT s.rowid, s.nom as name, s.town, s.client, s.code_client,'; $sql.= ' p.rowid as propalid, p.note_private, p.total_ht, p.ref, p.ref_client, p.fk_statut, p.fk_user_author, p.datep as dp, p.fin_validite as dfv,'; if (! $user->rights->societe->client->voir && ! $socid) $sql .= " sc.fk_soc, sc.fk_user,"; $sql.= ' u.login'; @@ -245,7 +248,7 @@ if ($result) if ($search_montant_ht) $param.='&search_montant_ht='.$search_montant_ht; if ($search_author) $param.='&search_author='.$search_author; if ($search_town) $param.='&search_town='.$search_town; - print_barre_liste($langs->trans('ListOfProposals').' '.($socid?'- '.$soc->nom:''), $page, $_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); + print_barre_liste($langs->trans('ListOfProposals').' '.($socid?'- '.$soc->name:''), $page, $_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); // Lignes des champs de filtre print ''; @@ -321,8 +324,12 @@ if ($result) print ''; - print ''; + print "\n"; $var=true; @@ -370,11 +377,11 @@ if ($result) print $objp->ref_client; print ''; - $url = DOL_URL_ROOT.'/comm/fiche.php?socid='.$objp->rowid; + $url = DOL_URL_ROOT.'/comm/card.php?socid='.$objp->rowid; // Company $companystatic->id=$objp->rowid; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; $companystatic->client=$objp->client; $companystatic->code_client=$objp->code_client; print '\n"; // Date end validity diff --git a/htdocs/comm/propal/tpl/index.html b/htdocs/comm/propal/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/prospect/class/index.html b/htdocs/comm/prospect/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/comm/prospect/list.php b/htdocs/comm/prospect/list.php index 58a384df6d0..3501d94aafd 100644 --- a/htdocs/comm/prospect/list.php +++ b/htdocs/comm/prospect/list.php @@ -48,7 +48,6 @@ $search_state = GETPOST("search_state"); $search_datec = GETPOST("search_datec"); $search_categ = GETPOST("search_categ",'int'); $search_status = GETPOST("search_status",'int'); -if ($search_status=='') $search_status=1; // always display activ customer first $catid = GETPOST("catid",'int'); $sortfield = GETPOST("sortfield",'alpha'); @@ -154,6 +153,21 @@ $sts = array(-1,0,1,2,3); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('prospectlist')); +// Do we click on purge search criteria ? +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $socname=""; + $stcomm=""; + $search_nom=""; + $search_zipcode=""; + $search_town=""; + $search_state=""; + $search_datec=""; + $search_categ=""; + $search_status=""; +} + +if ($search_status=='') $search_status=1; // always display active customer first /* * Actions @@ -161,6 +175,7 @@ $hookmanager->initHooks(array('prospectlist')); $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if ($action == 'cstc') { @@ -177,7 +192,7 @@ if ($action == 'cstc') $formother=new FormOther($db); $form=new Form($db); -$sql = "SELECT s.rowid, s.nom, s.zip, s.town, s.datec, s.status as status, s.code_client, s.client,"; +$sql = "SELECT s.rowid, s.nom as name, s.zip, s.town, s.datec, s.status as status, s.code_client, s.client,"; $sql.= " st.libelle as stcomm, s.prefix_comm, s.fk_stcomm, s.fk_prospectlevel,"; $sql.= " d.nom as departement"; if ((!$user->rights->societe->client->voir && !$socid) || $search_sale) $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) @@ -233,7 +248,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= " ORDER BY $sortfield $sortorder, s.nom ASC"; $sql.= $db->plimit($conf->liste_limit+1, $offset); -dol_syslog('comm/prospect/list.php sql='.$sql,LOG_DEBUG); +dol_syslog('comm/prospect/list.php', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -242,7 +257,7 @@ if ($resql) if ($num == 1 && $socname) { $obj = $db->fetch_object($resql); - header("Location: fiche.php?socid=".$obj->rowid); + header("Location: card.php?socid=".$obj->rowid); exit; } else @@ -360,7 +375,7 @@ if ($resql) // Print these two select print $langs->trans("From").' '; print ' '; - print $langs->trans("To").' '; + print $langs->trans("to").' '; print ''; @@ -377,9 +392,9 @@ if ($resql) print ''; // Print the search button - print ''; + print '\n"; $parameters=array(); $formconfirm=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook @@ -401,7 +416,7 @@ if ($resql) print ''; print ''; - print '\n"; + print '\n"; print '\n"; print ''; diff --git a/htdocs/compta/prelevement/fiche-stat.php b/htdocs/compta/prelevement/fiche-stat.php index 37b6c708b96..0e9174ef034 100644 --- a/htdocs/compta/prelevement/fiche-stat.php +++ b/htdocs/compta/prelevement/fiche-stat.php @@ -106,7 +106,6 @@ if ($prev_id) /* * Stats - * */ $ligne=new LignePrelevement($db,$user); @@ -121,6 +120,8 @@ if ($prev_id) $num = $db->num_rows($resql); $i = 0; + print_fiche_titre($langs->trans("StatisticsByLineStatus"),'',''); + print"\n\n"; print '
'.$langs->trans("OnProcessOrders").' ('.$num.')
'.$langs->trans("OnProcessOrders").' ('.$num.')
'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.$propalstatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; $formpropal->selectProposalStatus($viewstatut,1); print ''; + + print ''; + print ''; + print ''; print '
'; @@ -388,7 +395,7 @@ if ($result) // Date proposal print ''; - print dol_print_date($db->jdate($obj->dp), 'day'); + print dol_print_date($db->jdate($objp->dp), 'day'); print "'; - print ''; - print ''; + print ''; + print "
'; $prospectstatic->id=$obj->rowid; - $prospectstatic->nom=$obj->nom; + $prospectstatic->name=$obj->name; $prospectstatic->status=$obj->status; $prospectstatic->code_client=$obj->code_client; $prospectstatic->client=$obj->client; diff --git a/htdocs/comm/prospect/recap-prospect.php b/htdocs/comm/prospect/recap-prospect.php index 1eb30f02b55..5d7358a806e 100644 --- a/htdocs/comm/prospect/recap-prospect.php +++ b/htdocs/comm/prospect/recap-prospect.php @@ -64,8 +64,8 @@ if ($socid > 0) print ''; - // Nom - print ''; + // Name + print ''; // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field diff --git a/htdocs/comm/recap-client.php b/htdocs/comm/recap-client.php index bb079a34169..ec54e553bdb 100644 --- a/htdocs/comm/recap-client.php +++ b/htdocs/comm/recap-client.php @@ -63,8 +63,8 @@ if ($socid > 0) print '
'.$langs->trans("Name").''.$societe->nom.'
'.$langs->trans("Thirdpary").''.$societe->getNomUrl(1).'
'; - // Nom - print ''; + // Name + print ''; // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php index 5fc0c7ec9bb..fe3e39d266d 100644 --- a/htdocs/comm/remise.php +++ b/htdocs/comm/remise.php @@ -71,7 +71,7 @@ if (GETPOST("action") == 'setremise') } else { - $errmesg=$soc->error; + setEventMessage($soc->error, 'errors'); } } @@ -97,8 +97,6 @@ if ($socid > 0) $objsoc->id=$socid; $objsoc->fetch($socid); - dol_htmloutput_errors($errmesg); - $head = societe_prepare_head($objsoc); dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"),0,'company'); @@ -186,7 +184,7 @@ if ($socid > 0) print ''; print ''; print ''; - print ''; + print ''; print ''; $i++; } diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index db35db04b14..79f952fe7fd 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -65,17 +65,17 @@ if ($action == 'confirm_split' && GETPOST("confirm") == 'yes') if (! $res > 0) { $error++; - $mesg='
'.$langs->trans("ErrorFailedToLoadDiscount").'
'; + setEventMessage($langs->trans("ErrorFailedToLoadDiscount"), 'errors'); } if (! $error && price2num($_POST["amount_ttc_1"]+$_POST["amount_ttc_2"]) != $discount->amount_ttc) { $error++; - $mesg='
'.$langs->trans("TotalOfTwoDiscountMustEqualsOriginal").'
'; + setEventMessage($langs->trans("TotalOfTwoDiscountMustEqualsOriginal"), 'errors'); } if (! $error && $discount->fk_facture_line) { $error++; - $mesg='
'.$langs->trans("ErrorCantSplitAUsedDiscount").'
'; + setEventMessage($langs->trans("ErrorCantSplitAUsedDiscount"), 'errors'); } if (! $error) { @@ -140,7 +140,7 @@ if ($action == 'setremise') $error=0; if (empty($_POST["desc"])) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->trans("ReasonDiscount")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("ReasonDiscount")), 'errors'); $error++; } @@ -166,13 +166,13 @@ if ($action == 'setremise') else { $error++; - $mesg='
'.$soc->error.'
'; + setEventMessage($soc->error, 'errors'); } } } else { - $mesg='
'.$langs->trans("ErrorFieldFormat",$langs->trans("NewGlobalDiscount")).'
'; + setEventMessage($langs->trans("ErrorFieldFormat",$langs->trans("NewGlobalDiscount")), 'errors'); } } @@ -194,7 +194,7 @@ if (GETPOST("action") == 'confirm_remove' && GETPOST("confirm")=='yes') } else { - $mesg='
'.$discount->error.'
'; + setEventMessage($discount->error, 'errors'); $db->rollback(); } } @@ -211,8 +211,6 @@ llxHeader('',$langs->trans("GlobalDiscount")); if ($socid > 0) { - dol_htmloutput_mesg($mesg); - // On recupere les donnees societes par l'objet $objsoc = new Societe($db); $objsoc->id=$socid; @@ -369,7 +367,7 @@ if ($socid > 0) print ''; print ''; print ''; if ($user->rights->societe->creer || $user->rights->facture->creer) { @@ -526,7 +524,7 @@ if ($socid > 0) print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/commande/apercu.php b/htdocs/commande/apercu.php index 97671510bfd..839ca73d5b9 100644 --- a/htdocs/commande/apercu.php +++ b/htdocs/commande/apercu.php @@ -167,7 +167,7 @@ if ($id > 0 || ! empty($ref)) // Client print ""; print ''; print ''; @@ -206,7 +206,7 @@ if ($id > 0 || ! empty($ref)) // Si fichier png PDF d'1 page trouve if (file_exists($fileimage)) { - print ''; + print ''; } // Si fichier png PDF de plus d'1 page trouve elseif (file_exists($fileimagebis)) @@ -219,13 +219,12 @@ elseif (file_exists($fileimagebis)) if (file_exists($dir_output.$preview)) { - print '

'; + print '

'; } } } -print ''; - -$db->close(); llxFooter(); + +$db->close(); diff --git a/htdocs/commande/fiche.php b/htdocs/commande/card.php similarity index 82% rename from htdocs/commande/fiche.php rename to htdocs/commande/card.php index e0950bdccc7..1291d6cce26 100644 --- a/htdocs/commande/fiche.php +++ b/htdocs/commande/card.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2013 Regis Houssin * Copyright (C) 2006 Andre Cianfarani @@ -9,6 +9,7 @@ * Copyright (C) 2012-2013 Christophe Battarel * Copyright (C) 2012 Marcos García * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -25,7 +26,7 @@ */ /** - * \file htdocs/commande/fiche.php + * \file htdocs/commande/card.php * \ingroup commande * \brief Page to show customer order */ @@ -52,6 +53,7 @@ $langs->load('companies'); $langs->load('bills'); $langs->load('propal'); $langs->load('deliveries'); +$langs->load('sendings'); $langs->load('products'); if (! empty($conf->margin->enabled)) $langs->load('margins'); @@ -65,8 +67,6 @@ $lineid = GETPOST('lineid', 'int'); $origin = GETPOST('origin', 'alpha'); $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility -$mesg = GETPOST('mesg'); - // PDF $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); @@ -90,7 +90,7 @@ if ($id > 0 || ! empty($ref)) { } // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('ordercard')); +$hookmanager->initHooks(array('ordercard','globalcard')); $permissionnote = $user->rights->commande->creer; // Used by the include of actions_setnotes.inc.php @@ -100,6 +100,7 @@ $permissionnote = $user->rights->commande->creer; // Used by the include of acti $parameters = array('socid' => $socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); include DOL_DOCUMENT_ROOT . '/core/actions_setnotes.inc.php'; // Must be include, not includ_once @@ -108,7 +109,7 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->commande-> { if (1==0 && ! GETPOST('clone_content') && ! GETPOST('clone_receivers')) { - $mesg='

'.$langs->trans("NoCloneOptionsSpecified").'
'; + setEventMessage($langs->trans("NoCloneOptionsSpecified"), 'errors'); } else { @@ -171,14 +172,14 @@ else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights-> if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id'); if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret = $object->fetch($object->id); // Reload to get new records - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -201,7 +202,7 @@ else if ($action == 'add' && $user->rights->commande->creer) { $datelivraison = dol_mktime(12, 0, 0, GETPOST('liv_month'), GETPOST('liv_day'), GETPOST('liv_year')); if ($datecommande == '') { - $mesg = '
' . $langs->trans('ErrorFieldRequired', $langs->transnoentities('Date')) . '
'; + setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentities('Date')), 'errors'); $action = 'create'; $error ++; } @@ -227,11 +228,13 @@ else if ($action == 'add' && $user->rights->commande->creer) { $object->modelpdf = GETPOST('model'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->availability_id = GETPOST('availability_id'); $object->demand_reason_id = GETPOST('demand_reason_id'); $object->date_livraison = $datelivraison; + $object->shipping_method_id = GETPOST('shipping_method_id', 'int'); $object->fk_delivery_address = GETPOST('fk_address'); - $object->contactid = GETPOST('contactidp'); + $object->contactid = GETPOST('contactid'); // If creation from another object of another module (Example: origin=propal, originid=1) if (! empty($origin) && ! empty($originid)) { @@ -346,11 +349,11 @@ else if ($action == 'add' && $user->rights->commande->creer) { if ($reshook < 0) $error ++; } else { - $mesg = $srcobject->error; + setEventMessage($srcobject->error, 'errors'); $error ++; } } else { - $mesg = $object->error; + setEventMessage($object->error, 'errors'); $error ++; } } else { @@ -369,11 +372,11 @@ else if ($action == 'add' && $user->rights->commande->creer) { // If some invoice's lines already known $NBLINES = 8; for($i = 1; $i <= $NBLINES; $i ++) { - if ($_POST ['idprod' . $i]) { + if ($_POST['idprod' . $i]) { $xid = 'idprod' . $i; $xqty = 'qty' . $i; $xremise = 'remise_percent' . $i; - $object->add_product($_POST [$xid], $_POST [$xqty], $_POST [$xremise]); + $object->add_product($_POST[$xid], $_POST[$xqty], $_POST[$xremise]); } } } @@ -381,10 +384,10 @@ else if ($action == 'add' && $user->rights->commande->creer) { // Insert default contacts if defined if ($object_id > 0) { - if (GETPOST('contactidp')) { - $result = $object->add_contact(GETPOST('contactidp'), 'CUSTOMER', 'external'); + if (GETPOST('contactid')) { + $result = $object->add_contact(GETPOST('contactid'), 'CUSTOMER', 'external'); if ($result < 0) { - $mesg = '
' . $langs->trans("ErrorFailedToAddContact") . '
'; + setEventMessage($langs->trans("ErrorFailedToAddContact"), 'errors'); $error ++; } } @@ -401,8 +404,7 @@ else if ($action == 'add' && $user->rights->commande->creer) { } else { $db->rollback(); $action = 'create'; - if (! $mesg) - $mesg = '
' . $object->error . '
'; + setEventMessage($object->error, 'errors'); } } } @@ -441,7 +443,7 @@ else if ($action == 'setdate' && $user->rights->commande->creer) { $result = $object->set_date($user, $date); if ($result < 0) { - $mesg = '
' . $object->error . '
'; + setEventMessage($object->error, 'errors'); } } @@ -451,7 +453,7 @@ else if ($action == 'setdate_livraison' && $user->rights->commande->creer) { $result = $object->set_date_livraison($user, $datelivraison); if ($result < 0) { - $mesg = '
' . $object->error . '
'; + setEventMessage($object->error, 'errors'); } } @@ -483,18 +485,28 @@ else if ($action == 'setconditions' && $user->rights->commande->creer) { $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($object->id); // Reload to get new records - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } } +// bank account +else if ($action == 'setbankaccount' && $user->rights->commande->creer) { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); +} + +// shipping method +else if ($action == 'setshippingmethod' && $user->rights->commande->creer) { + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); +} + else if ($action == 'setremisepercent' && $user->rights->commande->creer) { $result = $object->set_remise($user, GETPOST('remise_percent')); } @@ -535,7 +547,7 @@ else if ($action == 'addline' && $user->rights->commande->creer) { if (is_array($extralabelsline)) { // Get extra fields foreach ($extralabelsline as $key => $value) { - unset($_POST ["options_" . $key]); + unset($_POST["options_" . $key]); } } @@ -578,18 +590,24 @@ else if ($action == 'addline' && $user->rights->commande->creer) { $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : ''); // Update if prices fields are defined - $tva_tx = get_default_tva($mysoc, $object->client, $prod->id); - $tva_npr = get_default_npr($mysoc, $object->client, $prod->id); + $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); + $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); + $pu_ht = $prod->price; + $pu_ttc = $prod->price_ttc; + $price_min = $prod->price_min; + $price_base_type = $prod->price_base_type; // multiprix - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->client->price_level)) + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) { - $pu_ht = $prod->multiprices [$object->client->price_level]; - $pu_ttc = $prod->multiprices_ttc [$object->client->price_level]; - $price_min = $prod->multiprices_min [$object->client->price_level]; - $price_base_type = $prod->multiprices_base_type [$object->client->price_level]; + $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; + $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; + $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; + $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; if (isset($prod->multiprices_tva_tx[$object->client->price_level])) $tva_tx=$prod->multiprices_tva_tx[$object->client->price_level]; if (isset($prod->multiprices_recuperableonly[$object->client->price_level])) $tva_npr=$prod->multiprices_recuperableonly[$object->client->price_level]; + $tva_tx=$prod->multiprices_tva_tx[$object->thirdparty->price_level]; + $tva_npr=$prod->multiprices_recuperableonly[$object->thirdparty->price_level]; } elseif (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { @@ -600,30 +618,21 @@ else if ($action == 'addline' && $user->rights->commande->creer) { $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result >= 0) { - if (count($prodcustprice->lines) > 0) { - $found = true; - $pu_ht = price($prodcustprice->lines[0]->price); - $pu_ttc = price($prodcustprice->lines[0]->price_ttc); - $price_base_type = $prodcustprice->lines[0]->price_base_type; - $prod->tva_tx = $prodcustprice->lines[0]->tva_tx; - } else { - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; + if ($result >= 0) + { + if (count($prodcustprice->lines) > 0) + { + $pu_ht = price($prodcustprice->lines [0]->price); + $pu_ttc = price($prodcustprice->lines [0]->price_ttc); + $price_base_type = $prodcustprice->lines [0]->price_base_type; + $prod->tva_tx = $prodcustprice->lines [0]->tva_tx; } - } else { + } + else + { setEventMessage($prodcustprice->error,'errors'); } } - else - { - $pu_ht = $prod->price; - $pu_ttc = $prod->price_ttc; - $price_min = $prod->price_min; - $price_base_type = $prod->price_base_type; - } // if price ht is forced (ie: calculated by margin rate and cost price) if (! empty($price_ht)) { @@ -650,7 +659,7 @@ else if ($action == 'addline' && $user->rights->commande->creer) { if (empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id'); if (empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -692,8 +701,8 @@ else if ($action == 'addline' && $user->rights->commande->creer) { $buyingprice = (GETPOST('buying_price' . $predef) ? GETPOST('buying_price' . $predef) : ''); // Local Taxes - $localtax1_tx = get_localtax($tva_tx, 1, $object->client); - $localtax2_tx = get_localtax($tva_tx, 2, $object->client); + $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty); $desc = dol_htmlcleanlastbr($desc); @@ -716,32 +725,32 @@ else if ($action == 'addline' && $user->rights->commande->creer) { $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); if (! empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - unset($_POST ['prod_entry_mode']); + unset($_POST['prod_entry_mode']); - unset($_POST ['qty']); - unset($_POST ['type']); - unset($_POST ['remise_percent']); - unset($_POST ['price_ht']); - unset($_POST ['price_ttc']); - unset($_POST ['tva_tx']); - unset($_POST ['product_ref']); - unset($_POST ['product_label']); - unset($_POST ['product_desc']); - unset($_POST ['fournprice']); - unset($_POST ['buying_price']); - unset($_POST ['np_marginRate']); - unset($_POST ['np_markRate']); - unset($_POST ['dp_desc']); - unset($_POST ['idprod']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); + unset($_POST['np_marginRate']); + unset($_POST['np_markRate']); + unset($_POST['dp_desc']); + unset($_POST['idprod']); unset($_POST['date_starthour']); unset($_POST['date_startmin']); @@ -782,8 +791,8 @@ else if ($action == 'updateligne' && $user->rights->commande->creer && GETPOST(' // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); - $localtax1_rate = get_localtax($vat_rate, 1, $object->client); - $localtax2_rate = get_localtax($vat_rate, 2, $object->client); + $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty); + $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty); // Add buying price $fournprice = (GETPOST('fournprice') ? GETPOST('fournprice') : ''); @@ -796,7 +805,7 @@ else if ($action == 'updateligne' && $user->rights->commande->creer && GETPOST(' // Unset extrafield POST Data if (is_array($extralabelsline)) { foreach ($extralabelsline as $key => $value) { - unset($_POST ["options_" . $key]); + unset($_POST["options_" . $key]); } } @@ -809,8 +818,8 @@ else if ($action == 'updateligne' && $user->rights->commande->creer && GETPOST(' $type = $product->type; $price_min = $product->price_min; - if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->client->price_level)) - $price_min = $product->multiprices_min [$object->client->price_level]; + if (! empty($conf->global->PRODUIT_MULTIPRICES) && ! empty($object->thirdparty->price_level)) + $price_min = $product->multiprices_min [$object->thirdparty->price_level]; $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); @@ -840,28 +849,28 @@ else if ($action == 'updateligne' && $user->rights->commande->creer && GETPOST(' if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id'); if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } $ret = $object->fetch($object->id); // Reload to get new records - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } - unset($_POST ['qty']); - unset($_POST ['type']); - unset($_POST ['productid']); - unset($_POST ['remise_percent']); - unset($_POST ['price_ht']); - unset($_POST ['price_ttc']); - unset($_POST ['tva_tx']); - unset($_POST ['product_ref']); - unset($_POST ['product_label']); - unset($_POST ['product_desc']); - unset($_POST ['fournprice']); - unset($_POST ['buying_price']); + unset($_POST['qty']); + unset($_POST['type']); + unset($_POST['productid']); + unset($_POST['remise_percent']); + unset($_POST['price_ht']); + unset($_POST['price_ttc']); + unset($_POST['tva_tx']); + unset($_POST['product_ref']); + unset($_POST['product_label']); + unset($_POST['product_desc']); + unset($_POST['fournprice']); + unset($_POST['buying_price']); } else { setEventMessage($object->error, 'errors'); } @@ -892,27 +901,31 @@ else if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->co if (! $idwarehouse || $idwarehouse == -1) { $error++; - $mesgs[]='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); $action=''; } } if (! $error) { $result = $object->valid($user, $idwarehouse); - if ($result >= 0) { + if ($result >= 0) + { // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { $tmp=getListOfModels($db, 'order'); $keys=array_keys($tmp); $model=$keys[0]; } + $ret = $object->fetch($id); // Reload to get new records + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } } } @@ -937,28 +950,30 @@ else if ($action == 'confirm_modif' && $user->rights->commande->creer) { if (! $idwarehouse || $idwarehouse == -1) { $error++; - $mesgs[]='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); $action=''; } } if (! $error) { $result = $object->set_draft($user, $idwarehouse); - if ($result >= 0) { + if ($result >= 0) + { // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $ret = $object->fetch($object->id); // Reload to get new records - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { $tmp=getListOfModels($db, 'order'); $keys=array_keys($tmp); $model=$keys[0]; } + $ret = $object->fetch($id); // Reload to get new records + $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); } } } @@ -990,7 +1005,7 @@ else if ($action == 'confirm_cancel' && $confirm == 'yes' && $user->rights->comm if (! $idwarehouse || $idwarehouse == -1) { $error++; - $mesgs[]='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); $action=''; } } @@ -1017,14 +1032,15 @@ else if ($action == 'up' && $user->rights->commande->creer) { if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '#' . GETPOST('rowid')); exit(); @@ -1039,13 +1055,14 @@ else if ($action == 'down' && $user->rights->commande->creer) { if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '#' . GETPOST('rowid')); exit(); @@ -1068,12 +1085,12 @@ else if ($action == 'builddoc') // In get or post if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; + $newlang = $object->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $result = commande_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db, $result); @@ -1098,15 +1115,6 @@ else if ($action == 'remove_file') { } } -// Print file -else if ($action == 'print_file' and $user->rights->printipp->read) { - require_once DOL_DOCUMENT_ROOT . '/core/class/dolprintipp.class.php'; - $printer = new dolPrintIPP($db, $conf->global->PRINTIPP_HOST, $conf->global->PRINTIPP_PORT, $user->login, $conf->global->PRINTIPP_USER, $conf->global->PRINTIPP_PASSWORD); - $printer->print_file(GETPOST('file', 'alpha'), GETPOST('printer', 'alpha')); - setEventMessage($langs->trans("FileWasSentToPrinter", GETPOST('file'))); - $action = ''; -} - else if ($action == 'update_extras') { // Fill array 'array_options' with data from update form $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); @@ -1134,167 +1142,21 @@ else if ($action == 'update_extras') { $action = 'edit_extras'; } -/* - * Add file in email form -*/ -if (GETPOST('addfile')) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; +include DOL_DOCUMENT_ROOT.'/core/actions_printipp.inc.php'; - // Set tmp user directory TODO Use a dedicated directory for temp mails files - $vardir = $conf->user->dir_output . "/" . $user->id; - $upload_dir_tmp = $vardir . '/temp'; - - dol_add_file_process($upload_dir_tmp, 0, 0); - $action = 'presend'; -} - -/* - * Remove file in email form -*/ -if (GETPOST('removedfile')) { - require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; - - // Set tmp user directory - $vardir = $conf->user->dir_output . "/" . $user->id; - $upload_dir_tmp = $vardir . '/temp'; - - // TODO Delete only files that was uploaded from email form - dol_remove_file_process(GETPOST('removedfile'), 0); - $action = 'presend'; -} /* * Send mail -*/ -if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! GETPOST('cancel')) { - $langs->load('mails'); + */ - if ($object->id > 0) { - // $ref = dol_sanitizeFileName($object->ref); - // $file = $conf->commande->dir_output . '/' . $ref . '/' . $ref . '.pdf'; +// Actions to send emails +$actiontypecode='AC_COM'; +$trigger_name='ORDER_SENTBYMAIL'; +$paramname='id'; +$mode='emailfromorder'; +include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // if (is_readable($file)) - // { - if (GETPOST('sendto')) { - // Le destinataire a ete fourni via le champ libre - $sendto = GETPOST('sendto'); - $sendtoid = 0; - } elseif (GETPOST('receiver') != '-1') { - // Recipient was provided from combo list - if (GETPOST('receiver') == 'thirdparty') // Id of third party - { - $sendto = $object->client->email; - $sendtoid = 0; - } else // Id du contact - { - $sendto = $object->client->contact_get_property(GETPOST('receiver'), 'email'); - $sendtoid = GETPOST('receiver'); - } - } - if (dol_strlen($sendto)) { - $langs->load("commercial"); - - $from = GETPOST('fromname') . ' <' . GETPOST('frommail') . '>'; - $replyto = GETPOST('replytoname') . ' <' . GETPOST('replytomail') . '>'; - $message = GETPOST('message'); - $sendtocc = GETPOST('sendtocc'); - $deliveryreceipt = GETPOST('deliveryreceipt'); - - if ($action == 'send') { - if (dol_strlen(GETPOST('subject'))) - $subject = GETPOST('subject'); - else - $subject = $langs->transnoentities('Order') . ' ' . $object->ref; - $actiontypecode = 'AC_COM'; - $actionmsg = $langs->transnoentities('MailSentBy') . ' ' . $from . ' ' . $langs->transnoentities('To') . ' ' . $sendto . ".\n"; - if ($message) { - $actionmsg .= $langs->transnoentities('MailTopic') . ": " . $subject . "\n"; - $actionmsg .= $langs->transnoentities('TextUsedInTheMessageBody') . ":\n"; - $actionmsg .= $message; - } - $actionmsg2 = $langs->transnoentities('Action' . $actiontypecode); - } - - // Create form object - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; - $formmail = new FormMail($db); - - $attachedfiles = $formmail->get_attached_files(); - $filepath = $attachedfiles ['paths']; - $filename = $attachedfiles ['names']; - $mimetype = $attachedfiles ['mimes']; - - // Send mail - require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, '', $deliveryreceipt, - 1); - if ($mailfile->error) { - $mesg = '
' . $mailfile->error . '
'; - } else { - $result = $mailfile->sendfile(); - if ($result) { - $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)); // Must not - // contains " - - $error = 0; - - // Initialisation donnees - $object->sendtoid = $sendtoid; - $object->actiontypecode = $actiontypecode; - $object->actionmsg = $actionmsg; - $object->actionmsg2 = $actionmsg2; - $object->fk_element = $object->id; - $object->elementtype = $object->element; - - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface = new Interfaces($db); - $result = $interface->run_triggers('ORDER_SENTBYMAIL', $object, $user, $langs, $conf); - if ($result < 0) { - $error ++; - $this->errors = $interface->errors; - } - // Fin appel triggers - - if ($error) { - dol_print_error($db); - } else { - // Redirect here - // This avoid sending mail twice if going out and then back to page - header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&mesg=' . urlencode($mesg)); - exit(); - } - } else { - $langs->load("other"); - $mesg = '
'; - if ($mailfile->error) { - $mesg .= $langs->trans('ErrorFailedToSendMail', $from, $sendto); - $mesg .= '
' . $mailfile->error; - } else { - $mesg .= 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; - } - $mesg .= '
'; - } - } - /* } - else - { - $langs->load("other"); - $mesg='
'.$langs->trans('ErrorMailRecipientIsEmpty').' !
'; - $action='presend'; - dol_syslog('Recipient email is empty'); - }*/ - } else { - $langs->load("errors"); - $mesg = '
' . $langs->trans('ErrorCantReadFile', $file) . '
'; - dol_syslog('Failed to read file: ' . $file); - } - } else { - $langs->load("other"); - $mesg = '
' . $langs->trans('ErrorFailedToReadEntity', $langs->trans("Order")) . '
'; - dol_syslog($langs->trans('ErrorFailedToReadEntity', $langs->trans("Order"))); - } -} if (! $error && ! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->commande->creer) { if ($action == 'addcontact') { @@ -1309,9 +1171,9 @@ if (! $error && ! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->righ } else { if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
' . $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType") . '
'; + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); } else { - $mesg = '
' . $object->error . '
'; + setEventMessage($object->error, 'errors'); } } } @@ -1358,8 +1220,6 @@ $formorder = new FormOrder($db); if ($action == 'create' && $user->rights->commande->creer) { print_fiche_titre($langs->trans('CreateOrder')); - dol_htmloutput_mesg($mesg, $mesgs, 'error'); - $soc = new Societe($db); if ($socid > 0) $res = $soc->fetch($socid); @@ -1406,7 +1266,9 @@ if ($action == 'create' && $user->rights->commande->creer) { $soc = $objectsrc->client; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $availability_id = (!empty($objectsrc->availability_id)?$objectsrc->availability_id:(!empty($soc->availability_id)?$soc->availability_id:0)); + $shipping_method_id = (! empty($objectsrc->shipping_method_id)?$objectsrc->shipping_method_id:(! empty($soc->shipping_method_id)?$soc->shipping_method_id:0)); $demand_reason_id = (!empty($objectsrc->demand_reason_id)?$objectsrc->demand_reason_id:(!empty($soc->demand_reason_id)?$soc->demand_reason_id:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); @@ -1425,7 +1287,9 @@ if ($action == 'create' && $user->rights->commande->creer) { { $cond_reglement_id = $soc->cond_reglement_id; $mode_reglement_id = $soc->mode_reglement_id; + $fk_account = $soc->fk_account; $availability_id = $soc->availability_id; + $shipping_method_id = $soc->shipping_method_id; $demand_reason_id = $soc->demand_reason_id; $remise_percent = $soc->remise_percent; $remise_absolue = 0; @@ -1477,7 +1341,7 @@ if ($action == 'create' && $user->rights->commande->creer) { */ if ($socid > 0) { print "'; // Ligne info remises tiers @@ -1520,11 +1384,26 @@ if ($action == 'create' && $user->rights->commande->creer) { $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id'); print ''; + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) + { + print ''; + } + // Delivery delay print ''; + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + } + // What trigger creation print ''; } // Other attributes - $parameters = array('objectsrc' => $objectsrc,'colspan' => ' colspan="3"'); + $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'socid'=>$socid); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by // hook if (empty($reshook) && ! empty($extrafields->attribute_label)) { @@ -1603,12 +1482,12 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''; print '"; - if ($mysoc->localtax1_assuj == "1") // Localtax1 RE + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE { print '"; } - if ($mysoc->localtax2_assuj == "1") // Localtax2 IRPF + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF { print '"; } @@ -1672,8 +1551,6 @@ if ($action == 'create' && $user->rights->commande->creer) { $now = dol_now(); if ($object->id > 0) { - dol_htmloutput_mesg($mesg, $mesgs); - $product_static = new Product($db); $soc = new Societe($db); @@ -1682,6 +1559,8 @@ if ($action == 'create' && $user->rights->commande->creer) { $author = new User($db); $author->fetch($object->user_author_id); + $res = $object->fetch_optionals($object->id, $extralabels); + $head = commande_prepare_head($object); dol_fiche_head($head, 'order', $langs->trans("CustomerOrder"), 0, 'order'); @@ -1854,14 +1733,14 @@ if ($action == 'create' && $user->rights->commande->creer) { $nbrow ++; // Local taxes - if ($mysoc->localtax1_assuj == "1") - $nbrow ++; - if ($mysoc->localtax2_assuj == "1") - $nbrow ++; + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) + $nbrow++; + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0 ) + $nbrow++; print '
'.$langs->trans("Name").''.$societe->nom.'
'.$langs->trans("Thirdparty").''.$societe->getNomUrl(1).'
'.dol_print_date($db->jdate($obj->dc),"dayhour").''.price2num($obj->remise_percent).'%'.$obj->note.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; print ''.price2num($obj->tva_tx,'MU').'%'.price($obj->amount_ttc).''; - print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; + print ''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''; print ' 
".$langs->trans("Customer")."'; - print ''.$soc->nom.''; + print ''.$soc->getNomUrl(1).''; print '
" . $langs->trans("DefaultContact") . ''; - $form->select_contacts($soc->id, $setcontact, 'contactidp', 1, $srccontactslist); + $form->select_contacts($soc->id, $setcontact, 'contactid', 1, $srccontactslist); print '
' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
' . $langs->trans('AvailabilityPeriod') . ''; $form->selectAvailabilityDelay($availability_id, 'availability_id', '', 1); print '
' . $langs->trans('SendingMethod') . ''; + print $form->selectShippingMethod($shipping_method_id, 'shipping_method_id', '', 1); + print '
' . $langs->trans('Source') . ''; $form->selectInputReason($demand_reason_id, 'demand_reason_id', '', 1); @@ -1537,13 +1416,13 @@ if ($action == 'create' && $user->rights->commande->creer) { print '
' . $langs->trans('Project') . ''; $numprojet = $formproject->select_projects($soc->id, $projectid); if ($numprojet == 0) { - print '   ' . $langs->trans("AddProject") . ''; + print '   ' . $langs->trans("AddProject") . ''; } print '
' . $langs->trans($newclassname) . '' . $objectsrc->getNomUrl(1) . '
' . $langs->trans('TotalHT') . '' . price($objectsrc->total_ht) . '
' . $langs->trans('TotalVAT') . '' . price($objectsrc->total_tva) . "
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($objectsrc->total_localtax1) . "
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($objectsrc->total_localtax2) . "
'; - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = '' . $langs->trans("BackToList") . ''; // Ref print ''; @@ -1982,6 +1861,25 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; print ''; + // Shipping Method + if (! empty($conf->expedition->enabled)) { + print ''; + print ''; + } + // Terms of payment print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; print ''; @@ -137,7 +137,7 @@ if ($resql) print ''; diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php index 92cd8c4c6a9..d11fefbb6cb 100644 --- a/htdocs/compta/prelevement/factures.php +++ b/htdocs/compta/prelevement/factures.php @@ -63,17 +63,17 @@ if ($prev_id) print ''; print ''; print ''; - + // Status print ''; print ''; print ''; - + if($bon->date_trans <> 0) { $muser = new User($db); $muser->fetch($bon->user_trans); - + print ''; @@ -87,19 +87,19 @@ if ($prev_id) print dol_print_date($bon->date_credit,'day'); print ''; } - + print '
' . $langs->trans('Ref') . '
'; + print ''; + if ($action != 'editshippingmethod' && $user->rights->commande->creer) + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; + print '
'; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none'); + } + print '
'; print ''; } - // Other attributes (TODO Move this into an include) - $res = $object->fetch_optionals($object->id, $extralabels); - $parameters = array('colspan' => ' colspan="3"'); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by - // hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - foreach ($extrafields->attribute_label as $key => $label) { - if ($action == 'edit_extras') { - $value = (isset($_POST ["options_" . $key]) ? $_POST ["options_" . $key] : $object->array_options ["options_" . $key]); - } else { - $value = $object->array_options ["options_" . $key]; - } - if ($extrafields->attribute_type [$key] == 'separate') { - print $extrafields->showSeparator($key); - } else { - print 'attribute_required [$key])) - print ' class="fieldrequired"'; - print '>' . $label . '' . "\n"; - } - } - } + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; $rowspan = 4; - if ($mysoc->localtax1_assuj == "1") + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) $rowspan ++; - if ($mysoc->localtax2_assuj == "1") + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) $rowspan ++; - // Total HT + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_ORDER) && ! empty($conf->banque->enabled)) + { + print ''; + print ''; + } + + // Total HT print ''; print ''; @@ -2152,12 +2029,12 @@ if ($action == 'create' && $user->rights->commande->creer) { print ''; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1") // Localtax1 RE + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) // Localtax1 { print ''; print ''; } - if ($mysoc->localtax2_assuj == "1") // Localtax2 IRPF + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) // Localtax2 IRPF { print ''; print ''; @@ -2246,14 +2123,14 @@ if ($action == 'create' && $user->rights->commande->creer) { } // Edit if ($object->statut == 1 && $user->rights->commande->creer) { - print ''; + print ''; } // Create event if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a // "workflow" action so should appears somewhere else on // page. { - print '' . $langs->trans("AddAction") . ''; + print '' . $langs->trans("AddAction") . ''; } // Send if ($object->statut > 0) { @@ -2288,7 +2165,7 @@ if ($action == 'create' && $user->rights->commande->creer) { if ($object->statut > 0 && $object->statut < 3 && $object->getNbOfServicesLines() > 0) { if ($user->rights->ficheinter->creer) { - print ''; + print ''; } else { print ''; } @@ -2305,7 +2182,7 @@ if ($action == 'create' && $user->rights->commande->creer) { $langs->load("contracts"); if ($user->rights->contrat->creer) { - print ''; + print ''; } } @@ -2388,26 +2265,31 @@ if ($action == 'create' && $user->rights->commande->creer) { */ if ($action == 'presend') { + $object->fetch_projet(); + $ref = dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; $fileparams = dol_most_recent_file($conf->commande->dir_output . '/' . $ref, preg_quote($ref, '/')); $file = $fileparams ['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->thirdparty->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('commercial'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - - $result = commande_pdf_create($db, $object, GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db, $result); exit(); @@ -2422,6 +2304,7 @@ if ($action == 'create' && $user->rights->commande->creer) { // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -2434,9 +2317,9 @@ if ($action == 'create' && $user->rights->commande->creer) { $formmail->withtocc = $liste; $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; if (empty($object->ref_client)) { - $formmail->withtopic = $langs->trans('SendOrderRef', '__ORDERREF__'); + $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__'); } else if (! empty($object->ref_client)) { - $formmail->withtopic = $langs->trans('SendOrderRef', '__ORDERREF__(__REFCLIENT__)'); + $formmail->withtopic = $outputlangs->trans('SendOrderRef', '__ORDERREF__ (__REFCLIENT__)'); } $formmail->withfile = 2; $formmail->withbody = 1; @@ -2446,6 +2329,8 @@ if ($action == 'create' && $user->rights->commande->creer) { $formmail->substit ['__ORDERREF__'] = $object->ref; $formmail->substit ['__SIGNATURE__'] = $user->signature; $formmail->substit ['__REFCLIENT__'] = $object->ref_client; + $formmail->substit ['__THIRPARTY_NAME__'] = $object->thirdparty->name; + $formmail->substit ['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); $formmail->substit ['__PERSONALIZED__'] = ''; $formmail->substit ['__CONTACTCIVNAME__'] = ''; @@ -2455,7 +2340,7 @@ if ($action == 'create' && $user->rights->commande->creer) { if (is_array($contactarr) && count($contactarr) > 0) { foreach ($contactarr as $contact) { - if ($contact ['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { + if ($contact['libelle'] == $langs->trans('TypeContact_commande_external_CUSTOMER')) { // TODO Use code and not label $contactstatic = new Contact($db); $contactstatic->fetch($contact ['id']); $custcontact = $contactstatic->getFullName($langs, 1); @@ -2463,15 +2348,15 @@ if ($action == 'create' && $user->rights->commande->creer) { } if (! empty($custcontact)) { - $formmail->substit ['__CONTACTCIVNAME__'] = $custcontact; + $formmail->substit['__CONTACTCIVNAME__'] = $custcontact; } } // Tableau des parametres complementaires - $formmail->param ['action'] = 'send'; - $formmail->param ['models'] = 'order_send'; - $formmail->param ['orderid'] = $object->id; - $formmail->param ['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; + $formmail->param['action'] = 'send'; + $formmail->param['models'] = 'order_send'; + $formmail->param['orderid'] = $object->id; + $formmail->param['returnurl'] = $_SERVER["PHP_SELF"] . '?id=' . $object->id; // Init list of files if (GETPOST("mode") == 'init') { diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 8501f04e8b8..49ba2536bfa 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -3,10 +3,11 @@ * Copyright (C) 2004-2012 Laurent Destailleur * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2011 Jean Heimburger * Copyright (C) 2012-2014 Christophe Battarel * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -60,6 +61,7 @@ class Commande extends CommonOrder var $brouillon; var $cond_reglement_id; var $cond_reglement_code; + var $fk_account; var $mode_reglement_id; var $mode_reglement_code; var $availability_id; @@ -71,6 +73,7 @@ class Commande extends CommonOrder var $date; // Date commande var $date_commande; // Date commande (deprecated) var $date_livraison; // Date livraison souhaitee + var $shipping_method_id; var $fk_remise_except; var $remise_percent; var $total_ht; // Total net of tax @@ -131,18 +134,21 @@ class Commande extends CommonOrder if (! empty($conf->global->COMMANDE_ADDON)) { - $mybool=false; + $mybool=false; + $dirmodels=array_merge(array('/'),(array) $conf->modules_parts['models']); + foreach ($dirmodels as $reldir) + { + $file = $conf->global->COMMANDE_ADDON.".php"; + $classname = $conf->global->COMMANDE_ADDON; - $file = $conf->global->COMMANDE_ADDON.".php"; - $classname = $conf->global->COMMANDE_ADDON; - - // Include file with class - foreach ($conf->file->dol_document_root as $dirroot) - { - $dir = $dirroot."/core/modules/commande/"; - // Load file with numbering class (if found) - $mybool|=@include_once $dir.$file; - } + // Include file with class + foreach ($conf->file->dol_document_root as $dirroot) + { + $dir = $dirroot.$reldir."/core/modules/commande/"; + // Load file with numbering class (if found) + $mybool|=@include_once $dir.$file; + } + } if (! $mybool) { @@ -177,9 +183,10 @@ class Commande extends CommonOrder * * @param User $user User making status change * @param int $idwarehouse Id of warehouse to use for stock decrease + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <=0 if OK, >0 if KO */ - function valid($user, $idwarehouse=0) + function valid($user, $idwarehouse=0, $notrigger=0) { global $conf,$langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -217,9 +224,10 @@ class Commande extends CommonOrder $num = $this->getNextNumRef($soc); } else - { + { $num = $this->ref; } + $this->newref = $num; // Validate $sql = "UPDATE ".MAIN_DB_PREFIX."commande"; @@ -229,12 +237,12 @@ class Commande extends CommonOrder $sql.= " fk_user_valid = ".$user->id; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::valid() sql=".$sql); + dol_syslog(get_class($this)."::valid()", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::valid Echec update - 10 - sql=".$sql, LOG_ERR); dol_print_error($this->db); + $this->error=$this->db->lasterror(); $error++; } @@ -256,36 +264,55 @@ class Commande extends CommonOrder $mouvP->origin = &$this; // We decrement stock of product (and sub-products) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderValidatedInDolibarr",$num)); - if ($result < 0) { $error++; } + if ($result < 0) + { + $error++; + $this->error=$mouvP->error; + } } + if ($error) break; } } } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_VALIDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + if (! $error) { - $this->oldref=''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { - // On renomme repertoire ($this->ref = ancienne ref, $numfa = nouvelle ref) + // On renomme repertoire ($this->ref = ancienne ref, $numfa = nouvelle ref) // in order not to lose the attachments - $comref = dol_sanitizeFileName($this->ref); - $snum = dol_sanitizeFileName($num); - $dirsource = $conf->commande->dir_output.'/'.$comref; - $dirdest = $conf->commande->dir_output.'/'.$snum; + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->commande->dir_output.'/'.$oldref; + $dirdest = $conf->commande->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::valid() rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { - $this->oldref = $comref; - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($conf->commande->dir_output.'/'.$snum.'/'.$comref.'*.*'); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -294,18 +321,8 @@ class Commande extends CommonOrder // Set new ref and current status if (! $error) { - $this->ref = $num; - $this->statut = 1; - } - - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + $this->ref = $num; + $this->statut = 1; } if (! $error) @@ -314,9 +331,8 @@ class Commande extends CommonOrder return 1; } else - { + { $this->db->rollback(); - $this->error=$this->db->lasterror(); return -1; } } @@ -352,7 +368,7 @@ class Commande extends CommonOrder $sql.= " SET fk_statut = 0"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_draft sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_draft", LOG_DEBUG); if ($this->db->query($sql)) { // If stock is decremented on validate order, we must reincrement it @@ -395,7 +411,6 @@ class Commande extends CommonOrder { $this->error=$this->db->error(); $this->db->rollback(); - dol_syslog($this->error, LOG_ERR); return -1; } } @@ -424,16 +439,14 @@ class Commande extends CommonOrder $sql.= ' SET fk_statut=1, facture=0'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_reopen sql=".$sql); + dol_syslog(get_class($this)."::set_reopen", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_REOPEN',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_REOPEN',$user); + if ($result < 0) $error++; + // End call triggers } else { @@ -489,12 +502,10 @@ class Commande extends CommonOrder if ($this->db->query($sql)) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_CLOSE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_CLOSE',$user); + if ($result < 0) $error++; + // End call triggers if (! $error) { @@ -512,7 +523,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->lasterror(); - dol_syslog($this->error, LOG_ERR); $this->db->rollback(); return -1; @@ -540,7 +550,7 @@ class Commande extends CommonOrder $sql.= " WHERE rowid = ".$this->id; $sql.= " AND fk_statut = 1"; - dol_syslog(get_class($this)."::cancel sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::cancel", LOG_DEBUG); if ($this->db->query($sql)) { // If stock is decremented on validate order, we must reincrement it @@ -557,8 +567,11 @@ class Commande extends CommonOrder $mouvP = new MouvementStock($this->db); // We increment stock of product (and sub-products) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("OrderCanceledInDolibarr",$this->ref)); - if ($result < 0) { + if ($result < 0) + { $error++; + $this->error=$mouvP->error; + break; } } } @@ -566,14 +579,10 @@ class Commande extends CommonOrder if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_CANCEL',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_CANCEL',$user); + if ($result < 0) $error++; + // End call triggers } if (! $error) @@ -584,8 +593,6 @@ class Commande extends CommonOrder } else { - $this->error=$mouvP->error; - foreach($this->errors as $errmsg) { dol_syslog(get_class($this)."::cancel ".$errmsg, LOG_ERR); @@ -599,7 +606,6 @@ class Commande extends CommonOrder { $this->error=$this->db->error(); $this->db->rollback(); - dol_syslog($this->error, LOG_ERR); return -1; } } @@ -659,7 +665,8 @@ class Commande extends CommonOrder $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande ("; $sql.= " ref, fk_soc, date_creation, fk_user_author, fk_projet, date_commande, source, note_private, note_public, ref_client, ref_int"; - $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_availability, fk_input_reason, date_livraison, fk_delivery_address"; + $sql.= ", model_pdf, fk_cond_reglement, fk_mode_reglement, fk_account, fk_availability, fk_input_reason, date_livraison, fk_delivery_address"; + $sql.= ", fk_shipping_method"; $sql.= ", remise_absolue, remise_percent"; $sql.= ", entity"; $sql.= ")"; @@ -674,16 +681,18 @@ class Commande extends CommonOrder $sql.= ", '".$this->modelpdf."'"; $sql.= ", ".($this->cond_reglement_id>0?"'".$this->cond_reglement_id."'":"null"); $sql.= ", ".($this->mode_reglement_id>0?"'".$this->mode_reglement_id."'":"null"); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ", ".($this->availability_id>0?"'".$this->availability_id."'":"null"); $sql.= ", ".($this->demand_reason_id>0?"'".$this->demand_reason_id."'":"null"); $sql.= ", ".($this->date_livraison?"'".$this->db->idate($this->date_livraison)."'":"null"); $sql.= ", ".($this->fk_delivery_address>0?$this->fk_delivery_address:'NULL'); + $sql.= ", ".($this->shipping_method_id>0?$this->shipping_method_id:'NULL'); $sql.= ", ".($this->remise_absolue>0?$this->remise_absolue:'NULL'); $sql.= ", ".($this->remise_percent>0?$this->remise_percent:0); $sql.= ", ".$conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -765,9 +774,10 @@ class Commande extends CommonOrder if ($origin == 'propal' && $origin_id) { // On recupere les differents contact interne et externe - $prop = new Propal($this->db, $this->socid, $origin_id); + $prop = new Propal($this->db); + $prop->fetch($origin_id); - // On recupere le commercial suivi propale + // We get ids of sales representatives of proposal $this->userid = $prop->getIdcontact('internal', 'SALESREPFOLL'); if ($this->userid) @@ -776,7 +786,7 @@ class Commande extends CommonOrder $this->add_contact($this->userid[0], 'SALESREPFOLL', 'internal'); } - // On recupere le contact client suivi propale + // We get ids of customer follower of proposal $this->contactid = $prop->getIdcontact('external', 'CUSTOMER'); if ($this->contactid) @@ -791,6 +801,8 @@ class Commande extends CommonOrder if (! $error) { + $action='create'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('orderdao')); @@ -812,12 +824,10 @@ class Commande extends CommonOrder if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_CREATE',$user); + if ($result < 0) $error++; + // End call triggers } if (!$error) { @@ -904,7 +914,7 @@ class Commande extends CommonOrder $modCommande = new $obj; $this->ref = $modCommande->getNextValue($objsoc,$this); - + // Create clone $result=$this->create($user); if ($result < 0) $error++; @@ -920,12 +930,10 @@ class Commande extends CommonOrder if ($reshook < 0) $error++; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_CLONE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_CLONE',$user); + if ($result < 0) $error++; + // End call triggers } // End @@ -1004,9 +1012,11 @@ class Commande extends CommonOrder $this->fk_project = $object->fk_project; $this->cond_reglement_id = $object->cond_reglement_id; $this->mode_reglement_id = $object->mode_reglement_id; + $this->fk_account = $object->fk_account; $this->availability_id = $object->availability_id; $this->demand_reason_id = $object->demand_reason_id; $this->date_livraison = $object->date_livraison; + $this->shipping_method_id = $object->shipping_method_id; $this->fk_delivery_address = $object->fk_delivery_address; $this->contact_id = $object->contactid; $this->ref_client = $object->ref_client; @@ -1141,7 +1151,7 @@ class Commande extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty,$mysoc); $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type,'', $localtaxes_type); $total_ht = $tabprice[0]; @@ -1360,8 +1370,10 @@ class Commande extends CommonOrder $sql = 'SELECT c.rowid, c.date_creation, c.ref, c.fk_soc, c.fk_user_author, 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'; + $sql.= ', c.fk_account'; $sql.= ', c.date_commande'; $sql.= ', c.date_livraison'; + $sql.= ', c.fk_shipping_method'; $sql.= ', c.fk_projet, c.remise_percent, c.remise, c.remise_absolue, c.source, c.facture as billed'; $sql.= ', c.note_private, c.note_public, c.ref_client, c.ref_ext, c.ref_int, c.model_pdf, c.fk_delivery_address, c.extraparams'; $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; @@ -1379,7 +1391,7 @@ class Commande extends CommonOrder 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)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -1419,11 +1431,13 @@ class Commande extends CommonOrder $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->fk_account = $obj->fk_account; $this->availability_id = $obj->fk_availability; $this->availability_code = $obj->availability_code; $this->demand_reason_id = $obj->fk_input_reason; $this->demand_reason_code = $obj->demand_reason_code; $this->date_livraison = $this->db->jdate($obj->date_livraison); + $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null; $this->fk_delivery_address = $obj->fk_delivery_address; $this->extraparams = (array) json_decode($obj->extraparams, true); @@ -1454,13 +1468,11 @@ class Commande extends CommonOrder else { $this->error='Order with id '.$id.' not found sql='.$sql; - dol_syslog(get_class($this).'::fetch '.$this->error); return 0; } } else { - dol_syslog(get_class($this).'::fetch Error rowid='.$id, LOG_ERR); $this->error=$this->db->error(); return -1; } @@ -1563,7 +1575,7 @@ class Commande extends CommonOrder if ($only_product) $sql .= ' AND p.fk_product_type = 0'; $sql .= ' ORDER BY l.rang'; - dol_syslog(get_class($this)."::fetch_lines sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -1628,7 +1640,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog('Commande::fetch_lines: Error '.$this->error, LOG_ERR); return -3; } } @@ -1690,7 +1701,7 @@ class Commande extends CommonOrder $sql.= ' GROUP BY cd.rowid, cd.fk_product'; //print $sql; - dol_syslog(get_class($this)."::loadExpeditions sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::loadExpeditions", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -1708,7 +1719,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::loadExpeditions ".$this->error,LOG_ERR); return -1; } @@ -1923,7 +1933,7 @@ class Commande extends CommonOrder $sql.= ' SET remise_absolue = '.$remise; $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut = 0 ;'; - dol_syslog(get_class($this)."::set_remise_absolue sql=$sql"); + dol_syslog(get_class($this)."::set_remise_absolue", LOG_DEBUG); if ($this->db->query($sql)) { @@ -1955,7 +1965,7 @@ class Commande extends CommonOrder $sql.= " SET date_commande = ".($date ? $this->db->idate($date) : 'null'); $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0"; - dol_syslog(get_class($this)."::set_date sql=$sql",LOG_DEBUG); + dol_syslog(get_class($this)."::set_date",LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1965,7 +1975,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_date ".$this->error,LOG_ERR); return -1; } } @@ -1990,7 +1999,7 @@ class Commande extends CommonOrder $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_date_livraison sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::set_date_livraison", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2000,7 +2009,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_date_livraison ".$this->error,LOG_ERR); return -1; } } @@ -2234,7 +2242,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this).'::set_ref_client Erreur '.$this->error.' - '.$sql, LOG_ERR); return -2; } } @@ -2258,17 +2265,13 @@ class Commande extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande SET facture = 1'; $sql.= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; - dol_syslog(get_class($this)."::classifyBilled sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::classifyBilled", LOG_DEBUG); if ($this->db->query($sql)) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_CLASSIFY_BILLED',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_CLASSIFY_BILLED',$user); + if ($result < 0) $error++; + // End call triggers if (! $error) { @@ -2280,8 +2283,6 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->error(); - foreach($this->errors as $errmsg) { dol_syslog(get_class($this)."::classifyBilled ".$errmsg, LOG_ERR); @@ -2294,7 +2295,6 @@ class Commande extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::classifyBilled Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2370,7 +2370,7 @@ class Commande extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, '', $localtaxes_type); $total_ht = $tabprice[0]; @@ -2495,34 +2495,31 @@ class Commande extends CommonOrder if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers } + //TODO: Check for error after each action. If one failed we rollback, don't waste time to do action if previous fail if (! $error) { // Delete order details $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE fk_commande = ".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if (! $this->db->query($sql) ) { - dol_syslog(get_class($this)."::delete error", LOG_ERR); $error++; + $this->errors[]=$this->db->lasterror(); } // Delete order $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commande WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if (! $this->db->query($sql) ) { - dol_syslog(get_class($this)."::delete error", LOG_ERR); $error++; + $this->errors[]=$this->db->lasterror(); } // Delete linked object @@ -2582,7 +2579,6 @@ class Commande extends CommonOrder } else { - $this->error=$this->db->lasterror(); foreach($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); @@ -2752,7 +2748,7 @@ class Commande extends CommonOrder $result=''; if (! empty($conf->expedition->enabled) && ($option == 1 || $option == 2)) $url = DOL_URL_ROOT.'/expedition/shipment.php?id='.$this->id; - else $url = DOL_URL_ROOT.'/commande/fiche.php?id='.$this->id; + else $url = DOL_URL_ROOT.'/commande/card.php?id='.$this->id; if ($short) return $url; @@ -2960,6 +2956,8 @@ class Commande extends CommonOrder */ function update_extrafields($user) { + $action='create'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('orderdao')); @@ -3060,11 +3058,44 @@ class Commande extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR); return -1; } } + /** + * Create a document onto disk accordign to template module. + * + * @param string $modele Force le mnodele a utiliser ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$user,$langs,$hookmanager; + + $langs->load("orders"); + + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->COMMANDE_ADDON_PDF)) + { + $modele = $conf->global->COMMANDE_ADDON_PDF; + } + else + { + $modele = 'einstein'; + } + } + + $modelpath = "core/modules/commande/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } @@ -3226,7 +3257,7 @@ class OrderLine extends CommonOrderLine $sql = 'DELETE FROM '.MAIN_DB_PREFIX."commandedet WHERE rowid='".$this->rowid."';"; - dol_syslog("OrderLine::delete sql=".$sql); + dol_syslog("OrderLine::delete", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3242,12 +3273,10 @@ class OrderLine extends CommonOrderLine } } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEORDER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEORDER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers if (!$error) { $this->db->commit(); @@ -3265,7 +3294,6 @@ class OrderLine extends CommonOrderLine else { $this->error=$this->db->lasterror(); - dol_syslog("OrderLine::delete ".$this->error, LOG_ERR); return -1; } } @@ -3282,7 +3310,7 @@ class OrderLine extends CommonOrderLine $error=0; - dol_syslog("OrderLine::insert rang=".$this->rang); + dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters if (empty($this->tva_tx)) $this->tva_tx=0; @@ -3350,7 +3378,7 @@ class OrderLine extends CommonOrderLine $sql.= " ".(! empty($this->date_end)?"'".$this->db->idate($this->date_end)."'":"null"); $sql.= ')'; - dol_syslog(get_class($this)."::insert sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3368,12 +3396,10 @@ class OrderLine extends CommonOrderLine if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEORDER_INSERT',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEORDER_INSERT',$user); + if ($result < 0) $error++; + // End call triggers } if (!$error) { @@ -3392,7 +3418,6 @@ class OrderLine extends CommonOrderLine else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -3470,7 +3495,7 @@ class OrderLine extends CommonOrderLine if (! empty($this->rang)) $sql.= ", rang=".$this->rang; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3486,12 +3511,10 @@ class OrderLine extends CommonOrderLine if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEORDER_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEORDER_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers } if (!$error) { @@ -3510,7 +3533,6 @@ class OrderLine extends CommonOrderLine else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -3538,7 +3560,7 @@ class OrderLine extends CommonOrderLine $sql.= ",total_ttc='".price2num($this->total_ttc)."'"; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("OrderLine::update_total sql=$sql"); + dol_syslog("OrderLine::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -3549,7 +3571,6 @@ class OrderLine extends CommonOrderLine else { $this->error=$this->db->error(); - dol_syslog("OrderLine::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } diff --git a/htdocs/commande/class/index.html b/htdocs/commande/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index e4b30a6e60d..c36f19c166b 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -69,11 +69,11 @@ if ($action == 'addcontact' && $user->rights->commande->creer) if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); } else { - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } } @@ -132,7 +132,6 @@ $userstatic=new User($db); /* Mode vue et edition */ /* */ /* *************************************************************************** */ -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { @@ -153,7 +152,7 @@ if ($id > 0 || ! empty($ref)) */ print '
'; @@ -2083,58 +1981,37 @@ if ($action == 'create' && $user->rights->commande->creer) { print '
'; - // Convert date into timestamp format - if (in_array($extrafields->attribute_type [$key], array('date','datetime'))) { - $value = isset($_POST ["options_" . $key]) ? dol_mktime($_POST ["options_" . $key . "hour"], $_POST ["options_" . $key . "min"], 0, $_POST ["options_" . $key . "month"], $_POST ["options_" . $key . "day"], $_POST ["options_" . $key . "year"]) : $db->jdate($object->array_options ['options_' . $key]); - } - - if ($action == 'edit_extras' && $user->rights->commande->creer && GETPOST('attribute') == $key) { - print ''; - print ''; - print ''; - print ''; - print ''; - - print $extrafields->showInputField($key, $value); - - print ''; - print ''; - } else { - print $extrafields->showOutputField($key, $value); - if ($object->statut == 0 && $user->rights->commande->creer) - print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; - } - print '
'; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print '
'; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '
' . $langs->trans('AmountHT') . '' . price($object->total_ht, 1, '', 1, - 1, - 1, $conf->currency) . '
' . $langs->trans('AmountVAT') . '' . price($object->total_tva, 1, '', 1, - 1, - 1, $conf->currency) . '
' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '' . price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency) . '
' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '' . price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency) . '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; print "\n"; - $var=True; + $var=true; while ($i < min($num,$conf->liste_limit)) { @@ -161,7 +161,7 @@ if ($resql) $lien=$lienfin=''; $lien = ''; $lienfin=''; - $name=$obj->nom; + $name=$obj->name; $result.=($lien.img_object($langs->trans("ShowCompany").': '.$name,'company').$lienfin); $result.=$lien.(dol_trunc($name,$maxlen)).$lienfin; diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index d939b106c7f..2d9c80e9d2d 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -106,7 +106,7 @@ if ($id > 0 || ! empty($ref)) print '
'.$langs->trans("Ref").''; diff --git a/htdocs/commande/customer.php b/htdocs/commande/customer.php index 29812903d12..333ce5f7908 100644 --- a/htdocs/commande/customer.php +++ b/htdocs/commande/customer.php @@ -67,7 +67,7 @@ $thirdpartystatic=new Societe($db); * Mode List */ -$sql = "SELECT s.rowid, s.nom, s.client, s.town, s.datec, s.datea"; +$sql = "SELECT s.rowid, s.nom as name, s.client, s.town, s.datec, s.datea"; $sql.= ", st.libelle as stcomm, s.prefix_comm, s.code_client, s.code_compta "; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", sc.fk_soc, sc.fk_user "; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."c_stcomm as st, ".MAIN_DB_PREFIX."commande as c"; @@ -146,7 +146,7 @@ if ($resql) print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print '\n"; + print ''; + print "\n"; // Lines for filters fields print ''; print ''; print ''; print ''; print ''; print ''; print ''; if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { @@ -197,7 +211,7 @@ if ($resql) if ($objp->socid) { $companystatic->id=$objp->socid; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; print $companystatic->getNomUrl(1,'',24); } else print ' '; @@ -218,12 +232,13 @@ if ($resql) if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { print ''; } - + + print ''; print ''; $i++; diff --git a/htdocs/compta/paiement_charge.php b/htdocs/compta/paiement_charge.php index a54a0bcd935..7e26fa5789f 100644 --- a/htdocs/compta/paiement_charge.php +++ b/htdocs/compta/paiement_charge.php @@ -253,7 +253,7 @@ if ($_GET["action"] == 'create') print ''; print "\n"; - $var=True; + $var=true; $total=0; $totalrecu=0; diff --git a/htdocs/compta/payment_sc/fiche.php b/htdocs/compta/payment_sc/card.php similarity index 88% rename from htdocs/compta/payment_sc/fiche.php rename to htdocs/compta/payment_sc/card.php index 3a010bcae37..dc2fad6d35d 100644 --- a/htdocs/compta/payment_sc/fiche.php +++ b/htdocs/compta/payment_sc/card.php @@ -19,10 +19,10 @@ */ /** - * \file htdocs/compta/payment_sc/fiche.php + * \file htdocs/compta/payment_sc/card.php * \ingroup facture * \brief Onglet payment of a social contribution - * \remarks Fichier presque identique a fournisseur/paiement/fiche.php + * \remarks Fichier presque identique a fournisseur/paiement/card.php */ require '../../main.inc.php'; @@ -98,10 +98,12 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->char $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($_REQUEST['lang_id']); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) facture_pdf_create($db, $fac, $fac->modelpdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $fac->generateDocument($fac->modelpdf, $outputlangs); + } } - header('Location: fiche.php?id='.$paiement->id); + header('Location: card.php?id='.$paiement->id); exit; } else @@ -124,7 +126,7 @@ $form = new Form($db); $h=0; -$head[$h][0] = DOL_URL_ROOT.'/compta/payment_sc/fiche.php?id='.$_GET["id"]; +$head[$h][0] = DOL_URL_ROOT.'/compta/payment_sc/card.php?id='.$_GET["id"]; $head[$h][1] = $langs->trans("Card"); $hselected = $h; $h++; @@ -142,7 +144,7 @@ dol_fiche_head($head, $hselected, $langs->trans("PaymentSocialContribution"), 0, */ if ($action == 'delete') { - print $form->formconfirm('fiche.php?id='.$paiement->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); + print $form->formconfirm('card.php?id='.$paiement->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete','',0,2); } @@ -152,7 +154,7 @@ if ($action == 'delete') if ($action == 'valide') { $facid = $_GET['facid']; - print $form->formconfirm('fiche.php?id='.$paiement->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); + print $form->formconfirm('card.php?id='.$paiement->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); } @@ -211,7 +213,7 @@ $sql.= ' WHERE pf.fk_charge = f.rowid AND f.fk_type = pc.id'; $sql.= ' AND f.entity = '.$conf->entity; $sql.= ' AND pf.rowid = '.$paiement->id; -dol_syslog("compta/payment_sc/fiche.php sql=".$sql); +dol_syslog("compta/payment_sc/card.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -291,7 +293,7 @@ if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { if ($user->rights->facture->paiement) { - print ''.$langs->trans('Valid').''; + print ''.$langs->trans('Valid').''; } } } @@ -303,7 +305,7 @@ if ($_GET['action'] == '') { if (! $disable_delete) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } else { diff --git a/htdocs/compta/payment_sc/index.html b/htdocs/compta/payment_sc/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/prelevement/bon.php b/htdocs/compta/prelevement/bon.php deleted file mode 100644 index 20d60c3a55b..00000000000 --- a/htdocs/compta/prelevement/bon.php +++ /dev/null @@ -1,103 +0,0 @@ - - * Copyright (C) 2005 Laurent Destailleur - * Copyright (C) 2010-2012 Juanjo Menent - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/compta/prelevement/bon.php - * \ingroup prelevement - * \brief Fiche apercu du bon de prelevement - */ - -require('../../main.inc.php'); -require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - -$langs->load("banks"); -$langs->load("categories"); -$langs->load("bills"); -$langs->load("categories"); - -// Security check -$socid=0; -$id = GETPOST('id','int'); -$ref = GETPOST('ref','alpha'); -if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'prelevement', $id); - - -llxHeader('','Bon de prelevement'); - -$form = new Form($db); - -if ($id > 0 || ! empty($ref)) -{ - $object = new BonPrelevement($db,""); - - if ($object->fetch($id) == 0) - { - $head = prelevement_prepare_head($object); - dol_fiche_head($head, 'preview', 'Prelevement : '. $object->ref); - - print '
'.$langs->trans('Ref').''; diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index 37e88f37d85..0d2815a6d67 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -63,7 +63,7 @@ print '
'; // Search customer orders $var=false; print ''; -print ''; +print ''; print ''; print ''; print '"; print ''; - print ''; @@ -166,7 +166,7 @@ else */ if (! empty($conf->commande->enabled)) { - $sql = "SELECT c.rowid, c.ref, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; $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"; @@ -187,15 +187,15 @@ if (! empty($conf->commande->enabled)) if ($num) { $i = 0; - $var = True; + $var = true; while ($i < $num) { $var=!$var; $obj = $db->fetch_object($resql); print ""; print '"; - print ''; + print "rowid."\">".img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.""; + print ''; $i++; } } @@ -215,7 +215,7 @@ $max=5; */ $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, c.date_cloture as datec, c.tms as datem,"; -$sql.= " s.nom, s.rowid as socid"; +$sql.= " s.nom as name, s.rowid as socid"; $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"; @@ -238,7 +238,7 @@ if ($resql) if ($num) { $i = 0; - $var = True; + $var = true; while ($i < $num) { $var=!$var; @@ -268,7 +268,7 @@ if ($resql) print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -285,7 +285,7 @@ else dol_print_error($db); */ if (! empty($conf->commande->enabled)) { - $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom as name, s.rowid as socid"; $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"; @@ -303,12 +303,12 @@ if (! empty($conf->commande->enabled)) print '
'.$langs->trans("SearchOrder").'
'; @@ -141,7 +141,7 @@ if ($resql) $var=!$var; print "
'.$commandestatic->LibStatut($status,$bool,0).''.(isset($vals[$status.$bool])?$vals[$status.$bool]:0).' '; + print ''.(isset($vals[$status.$bool])?$vals[$status.$bool]:0).' '; print $commandestatic->LibStatut($status,$bool,3); print ''; print '
'; - print "rowid."\">".img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref."'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).'
'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,24).'
'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.dol_print_date($db->jdate($obj->datem),'day').''.$commandestatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; print ''; - print ''; + print ''; if ($num) { $i = 0; - $var = True; + $var = true; while ($i < $num) { $var=!$var; @@ -337,7 +337,7 @@ if (! empty($conf->commande->enabled)) print ''; - print ''; + print ''; print ''; @@ -356,7 +356,7 @@ if (! empty($conf->commande->enabled)) */ if (! empty($conf->commande->enabled)) { - $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, c.fk_statut, c.facture, s.nom as name, s.rowid as socid"; $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"; @@ -374,12 +374,12 @@ if (! empty($conf->commande->enabled)) print '
'.$langs->trans("OrdersToProcess").' ('.$num.')
'.$langs->trans("OrdersToProcess").' ('.$num.')
'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,24).''.$commandestatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; print ''; - print ''; + print ''; if ($num) { $i = 0; - $var = True; + $var = true; while ($i < $num) { $var=!$var; @@ -408,7 +408,7 @@ if (! empty($conf->commande->enabled)) print ''; - print ''; + print ''; print ''; diff --git a/htdocs/commande/liste.php b/htdocs/commande/list.php similarity index 66% rename from htdocs/commande/liste.php rename to htdocs/commande/list.php index 55323b697f9..2c30f4128c6 100644 --- a/htdocs/commande/liste.php +++ b/htdocs/commande/list.php @@ -22,7 +22,7 @@ */ /** - * \file htdocs/commande/liste.php + * \file htdocs/commande/list.php * \ingroup commande * \brief Page to list orders */ @@ -33,6 +33,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.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.'/commande/class/commande.class.php'; +require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; $langs->load('orders'); $langs->load('deliveries'); @@ -42,9 +43,9 @@ $orderyear=GETPOST("orderyear","int"); $ordermonth=GETPOST("ordermonth","int"); $deliveryyear=GETPOST("deliveryyear","int"); $deliverymonth=GETPOST("deliverymonth","int"); -$sref=GETPOST('sref','alpha'); -$sref_client=GETPOST('sref_client','alpha'); -$snom=GETPOST('snom','alpha'); +$search_ref=GETPOST('search_ref','alpha'); +$search_ref_customer=GETPOST('search_ref_customer','alpha'); +$search_company=GETPOST('search_company','alpha'); $sall=GETPOST('sall'); $socid=GETPOST('socid','int'); $search_user=GETPOST('search_user','int'); @@ -68,6 +69,20 @@ $limit = $conf->liste_limit; $viewstatut=GETPOST('viewstatut'); +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_categ=''; + $search_user=''; + $search_sale=''; + $search_ref=''; + $search_ref_customer=''; + $search_company=''; + $orderyear=''; + $ordermonth=''; + $deliverymonth=''; + $deliveryyear=''; +} // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('orderlist')); @@ -78,24 +93,7 @@ $hookmanager->initHooks(array('orderlist')); $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hook - -// Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x")) -{ - $search_categ=''; - $search_user=''; - $search_sale=''; - $search_ref=''; - $search_refcustomer=''; - $search_societe=''; - $search_montant_ht=''; - $orderyear=''; - $ordermonth=''; - $deliverymonth=''; - $deliveryyear=''; -} - - +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); /* * View @@ -111,7 +109,7 @@ $companystatic = new Societe($db); $help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; llxHeader('',$langs->trans("Orders"),$help_url); -$sql = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,'; +$sql = 'SELECT s.nom as name, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_client,'; $sql.= ' c.date_valid, c.date_commande, c.note_private, c.date_livraison, c.fk_statut, c.facture as facturee'; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= ', '.MAIN_DB_PREFIX.'commande as c'; @@ -126,8 +124,8 @@ $sql.= ' WHERE c.fk_soc = s.rowid'; $sql.= ' AND c.entity = '.$conf->entity; if ($socid) $sql.= ' AND s.rowid = '.$socid; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -if ($sref) { - $sql .= natural_search('c.ref', $sref); +if ($search_ref) { + $sql .= natural_search('c.ref', $search_ref); } if ($sall) { @@ -155,8 +153,9 @@ if ($viewstatut <> '') } if ($viewstatut == -3) // To bill { - $sql.= ' AND c.fk_statut in (1,2,3)'; - $sql.= ' AND c.facture = 0'; // invoice not created + //$sql.= ' AND c.fk_statut in (1,2,3)'; + //$sql.= ' AND c.facture = 0'; // invoice not created + $sql .= ' AND ((c.fk_statut IN (1,2)) OR (c.fk_statut = 3 AND c.facture = 0))'; // validated, in process or closed but not billed } } if ($ordermonth > 0) @@ -185,13 +184,13 @@ else if ($deliveryyear > 0) { $sql.= " AND c.date_livraison BETWEEN '".$db->idate(dol_get_first_day($deliveryyear,1,false))."' AND '".$db->idate(dol_get_last_day($deliveryyear,12,false))."'"; } -if (!empty($snom)) +if (!empty($search_company)) { - $sql .= natural_search('s.nom', $snom); + $sql .= natural_search('s.nom', $search_company); } -if (!empty($sref_client)) +if (!empty($search_ref_customer)) { - $sql.= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\''; + $sql.= ' AND c.ref_client LIKE \'%'.$db->escape($search_ref_customer).'%\''; } if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$search_sale; if ($search_user > 0) @@ -219,7 +218,7 @@ if ($resql) { $soc = new Societe($db); $soc->fetch($socid); - $title = $langs->trans('ListOfOrders') . ' - '.$soc->nom; + $title = $langs->trans('ListOfOrders') . ' - '.$soc->name; } else { @@ -230,7 +229,7 @@ if ($resql) if ($viewstatut == 1) $title.=' - '.$langs->trans('StatusOrderValidatedShort'); if ($viewstatut == 2) - $title.=' - '.$langs->trans('StatusOrderOnProcessShort'); + $title.=' - '.$langs->trans('StatusOrderSentShort'); if ($viewstatut == 3) $title.=' - '.$langs->trans('StatusOrderToBillShort'); if ($viewstatut == 4) @@ -243,15 +242,15 @@ if ($resql) $title.=' - '.$langs->trans('StatusOrderValidated').', '.(empty($conf->expedition->enabled)?'':$langs->trans("StatusOrderSent").', ').$langs->trans('StatusOrderToBill'); $param='&socid='.$socid.'&viewstatut='.$viewstatut; - if ($ordermonth) $param.='&ordermonth='.$ordermonth; - if ($orderyear) $param.='&orderyear='.$orderyear; - if ($deliverymonth) $param.='&deliverymonth='.$deliverymonth; - if ($deliveryyear) $param.='&deliveryyear='.$deliveryyear; - if ($sref) $param.='&sref='.$sref; - if ($snom) $param.='&snom='.$snom; - if ($sref_client) $param.='&sref_client='.$sref_client; - if ($search_user > 0) $param.='&search_user='.$search_user; - if ($search_sale > 0) $param.='&search_sale='.$search_sale; + if ($ordermonth) $param.='&ordermonth='.$ordermonth; + if ($orderyear) $param.='&orderyear='.$orderyear; + if ($deliverymonth) $param.='&deliverymonth='.$deliverymonth; + if ($deliveryyear) $param.='&deliveryyear='.$deliveryyear; + if ($search_ref) $param.='&search_ref='.$search_ref; + if ($search_company) $param.='&search_company='.$search_company; + if ($search_ref_customer) $param.='&search_ref_customer='.$search_ref_customer; + if ($search_user > 0) $param.='&search_user='.$search_user; + if ($search_sale > 0) $param.='&search_sale='.$search_sale; $num = $db->num_rows($resql); print_barre_liste($title, $page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); @@ -291,54 +290,111 @@ if ($resql) print_liste_field_titre($langs->trans('Ref'),$_SERVER["PHP_SELF"],'c.ref','',$param,'width="25%"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('RefCustomerOrder'),$_SERVER["PHP_SELF"],'c.ref_client','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Company'),$_SERVER["PHP_SELF"],'s.nom','',$param,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('OrderDate'),$_SERVER["PHP_SELF"],'c.date_commande','',$param, 'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('DeliveryDate'),$_SERVER["PHP_SELF"],'c.date_livraison','',$param, 'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('OrderDate'),$_SERVER["PHP_SELF"],'c.date_commande','',$param, 'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('DeliveryDate'),$_SERVER["PHP_SELF"],'c.date_livraison','',$param, 'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('AmountHT'),$_SERVER["PHP_SELF"],'c.total_ht','',$param, 'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Status'),$_SERVER["PHP_SELF"],'c.fk_statut','',$param,'align="right"',$sortfield,$sortorder); print ''; + print ''; print ''; print ''; print ''; - print ''; + print ''; + print ''; + print '\n"; $var=true; $total=0; $subtotal=0; - $generic_commande = new Commande($db); - while ($i < min($num,$limit)) - { - $objp = $db->fetch_object($resql); - $var=!$var; - print ''; - print ''; + print ''; diff --git a/htdocs/compta/paiement/cheque/fiche.php b/htdocs/compta/paiement/cheque/card.php similarity index 98% rename from htdocs/compta/paiement/cheque/fiche.php rename to htdocs/compta/paiement/cheque/card.php index fe396976f10..0c5eeca3689 100644 --- a/htdocs/compta/paiement/cheque/fiche.php +++ b/htdocs/compta/paiement/cheque/card.php @@ -20,7 +20,7 @@ */ /** - * \file htdocs/compta/paiement/cheque/fiche.php + * \file htdocs/compta/paiement/cheque/card.php * \ingroup bank, invoice * \brief Page for cheque deposits */ @@ -47,8 +47,6 @@ $fieldname = (! empty($ref)?'number':'rowid'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'cheque', $id, 'bordereau_cheque','','',$fieldname); -$mesg=''; - $sortfield=GETPOST('sortfield', 'alpha'); $sortorder=GETPOST('sortorder', 'alpha'); $page=GETPOST('page', 'int'); @@ -122,12 +120,12 @@ if ($action == 'setref' && $user->rights->banque->cheque) $result=$object->set_number($user,$number); if ($result < 0) { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } @@ -337,9 +335,6 @@ else } } - -dol_htmloutput_errors($mesg); - $accounts = array(); if ($action == 'new') @@ -609,7 +604,6 @@ else $sql.= " AND b.fk_bordereau = ".$object->id; $sql.= " ORDER BY $sortfield $sortorder"; - dol_syslog("sql=".$sql); $resql = $db->query($sql); if ($resql) { diff --git a/htdocs/compta/paiement/cheque/class/index.html b/htdocs/compta/paiement/cheque/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 917c88e0743..922ab54ac7c 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -73,7 +73,7 @@ class RemiseCheque extends CommonObject if ($id) $sql.= " AND bc.rowid = ".$id; if ($ref) $sql.= " AND bc.number = '".$this->db->escape($ref)."'"; - dol_syslog("RemiseCheque::fetch sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -155,7 +155,7 @@ class RemiseCheque extends CommonObject $sql.= ", ''"; $sql.= ")"; - dol_syslog("RemiseCheque::Create sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::Create", LOG_DEBUG); $resql = $this->db->query($sql); if ( $resql ) { @@ -172,7 +172,7 @@ class RemiseCheque extends CommonObject $sql.= " SET number='(PROV".$this->id.")'"; $sql.= " WHERE rowid='".$this->id."';"; - dol_syslog("RemiseCheque::Create sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::Create", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { @@ -192,7 +192,7 @@ class RemiseCheque extends CommonObject $sql.= " AND b.fk_account='".$account_id."'"; if ($limit) $sql.= $this->db->plimit($limit); - dol_syslog("RemiseCheque::Create sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::Create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -225,7 +225,7 @@ class RemiseCheque extends CommonObject $sql.= " SET fk_bordereau = ".$this->id; $sql.= " WHERE rowid = ".$lineid; - dol_syslog("RemiseCheque::Create sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::Create", LOG_DEBUG); $resql = $this->db->query($sql); if (!$resql) { @@ -250,7 +250,6 @@ class RemiseCheque extends CommonObject $this->errno = -1; $this->error=$this->db->lasterror(); $this->errno=$this->db->lasterrno(); - dol_syslog("RemiseCheque::Create Error ".$this->error, LOG_ERR); } if (! $this->errno && ! empty($conf->global->MAIN_DISABLEDRAFTSTATUS)) @@ -351,7 +350,7 @@ class RemiseCheque extends CommonObject $sql.= " AND entity = ".$conf->entity; $sql.= " AND statut = 0"; - dol_syslog("RemiseCheque::Validate sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::Validate", LOG_DEBUG); $resql = $this->db->query($sql); if ( $resql ) { @@ -410,7 +409,7 @@ class RemiseCheque extends CommonObject $sql.= " WHERE entity = ".$conf->entity; $sql.= " AND number not like '(%'"; - dol_syslog("Remisecheque::getNextNumber sql=".$sql); + dol_syslog("Remisecheque::getNextNumber", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -510,7 +509,7 @@ class RemiseCheque extends CommonObject $sql.= " AND bc.entity = ".$conf->entity; $sql.= " ORDER BY b.dateo ASC, b.rowid ASC"; - dol_syslog("RemiseCheque::generatePdf sql=".$sql, LOG_DEBUG); + dol_syslog("RemiseCheque::generatePdf", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -705,7 +704,7 @@ class RemiseCheque extends CommonObject $sql.= " SET date_bordereau = ".($date ? $this->db->idate($date) : 'null'); $sql.= " WHERE rowid = ".$this->id; - dol_syslog("RemiseCheque::set_date sql=$sql",LOG_DEBUG); + dol_syslog("RemiseCheque::set_date", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -715,7 +714,6 @@ class RemiseCheque extends CommonObject else { $this->error=$this->db->error(); - dol_syslog("RemiseCheque::set_date ".$this->error,LOG_ERR); return -1; } } @@ -740,7 +738,7 @@ class RemiseCheque extends CommonObject $sql.= " SET number = '".$number."'" ; $sql.= " WHERE rowid = ".$this->id; - dol_syslog("RemiseCheque::set_number sql=$sql",LOG_DEBUG); + dol_syslog("RemiseCheque::set_number", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -750,7 +748,6 @@ class RemiseCheque extends CommonObject else { $this->error=$this->db->error(); - dol_syslog("RemiseCheque::set_number ".$this->error,LOG_ERR); return -1; } } @@ -773,7 +770,7 @@ class RemiseCheque extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; if ($withpicto) $result.=($lien.img_object($langs->trans("ShowCheckReceipt"),'payment').$lienfin); diff --git a/htdocs/compta/paiement/cheque/index.php b/htdocs/compta/paiement/cheque/index.php index 4e1d6190a4f..362493b7f19 100644 --- a/htdocs/compta/paiement/cheque/index.php +++ b/htdocs/compta/paiement/cheque/index.php @@ -29,6 +29,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("banks"); $langs->load("categories"); +$langs->load("compta"); +$langs->load("bills"); // Security check if ($user->societe_id) $socid=$user->societe_id; @@ -77,7 +79,7 @@ if ($resql) print ""; print ''; print ''; print "
'.$langs->trans("OnProcessOrders").' ('.$num.')
'.$langs->trans("OnProcessOrders").' ('.$num.')
'.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.$commandestatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; + print ''; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; print ''; $formother->select_year($orderyear?$orderyear:-1,'orderyear',1, 20, 5); - print ''; + print ''; if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; print ''; $formother->select_year($deliveryyear?$deliveryyear:-1,'deliveryyear',1, 20, 5); - print ' '; - print ''; - print ''; - print '
 '; + print ''; + print "
'; + $generic_commande = new Commande($db); + $generic_product = new Product($db); + while ($i < min($num,$limit)) { + $objp = $db->fetch_object($resql); + $var=!$var; + print '
'; - $generic_commande->id=$objp->rowid; - $generic_commande->ref=$objp->ref; + $generic_commande->id=$objp->rowid; + $generic_commande->ref=$objp->ref; + $generic_commande->lines=array(); + $generic_commande->getLinesArray(); - print ''; - print ''; + print '
'; - print $generic_commande->getNomUrl(1,($viewstatut != 2?0:$objp->fk_statut)); - print '
'; + print ''; + // Shippable Icon + if (($objp->fk_statut > 0) && ($objp->fk_statut < 3) && ! empty($conf->global->SHIPPABLE_ORDER_ICON_IN_LIST)) { + $notshippable=0; + $text_info=''; + $nbprod=0; + for ($lig=0; $lig<(count($generic_commande->lines)); $lig++) { + if ($generic_commande->lines[$lig]->product_type==0) { + $nbprod++; // order contains real products + $generic_product->id = $generic_commande->lines[$lig]->fk_product; + $generic_product->load_stock(); + // stock order and stock order_supplier + $stock_order=0; + $stock_order_supplier=0; + if (! empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) { + if (! empty($conf->commande->enabled)) { + $generic_product->load_stats_commande(0,'1,2'); + $stock_order=$generic_product->stats_commande['qty']; + } + if (! empty($conf->fournisseur->enabled)) { + $generic_product->load_stats_commande_fournisseur(0,'3'); + $stock_order_supplier=$generic_product->stats_commande_fournisseur['qty']; + } + } + $text_info .= $generic_commande->lines[$lig]->qty.' X '.$generic_commande->lines[$lig]->ref.' '.dol_trunc($generic_commande->lines[$lig]->product_label, 25); + $text_stock_reel = $generic_product->stock_reel.'/'.$stock_order; + if ($generic_product->stock_reel<$generic_commande->lines[$lig]->qty) { + $notshippable++; + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } else { + $text_info.=''.$langs->trans('Available').' : '.$text_stock_reel.''; + } + if ($stock_order_supplier>0) { + $text_info.= ' '.$langs->trans('SupplierOrder').' : '.$stock_order_supplier.'
'; + } else { + $text_info.= '
'; + } + } + } + if ($notshippable==0) { + $text_icon = img_picto('', 'object_sending'); + $text_info = $langs->trans('Shippable').'
'.$text_info; + } else { + $text_icon = img_picto('', 'error'); + $text_info = $langs->trans('NonShippable').'
'.$text_info; + } + if ($nbprod>0) { + print ''; + } + } + + // warning late icon print ''; // Order date - print ''; // Delivery date - print ''; // Amount HT @@ -423,7 +479,7 @@ if ($resql) print ''."\n"; print '
'.img_help(1,'').' '.$langs->trans("ToBillSeveralOrderSelectCustomer", $langs->transnoentitiesnoconv("CreateInvoiceForThisCustomer")).'
'; - + $db->free($resql); } else diff --git a/htdocs/commande/note.php b/htdocs/commande/note.php index ae5aab0491b..6f3519e9ced 100644 --- a/htdocs/commande/note.php +++ b/htdocs/commande/note.php @@ -79,7 +79,7 @@ if ($id > 0 || ! empty($ref)) print '
'; + print $generic_commande->getNomUrl(1,($viewstatut != 2?0:$objp->fk_statut)); + print ''; + print $form->textwithtooltip('',$text_info,2,1,$text_icon,'',2); + print ''; if (($objp->fk_statut > 0) && ($objp->fk_statut < 3) && max($db->jdate($objp->date_commande),$db->jdate($objp->date_livraison)) < ($now - $conf->commande->client->warning_delay)) print img_picto($langs->trans("Late"),"warning"); @@ -365,7 +421,7 @@ if ($resql) // Company $companystatic->id=$objp->socid; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; $companystatic->client=$objp->client; print ''; print $companystatic->getNomUrl(1,'customer'); @@ -378,20 +434,20 @@ if ($resql) if (($objp->fk_statut > 0 && $objp->fk_statut < 3) || ($objp->fk_statut == 3 && $objp->facturee == 0)) { print ' '; - print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->nom, 'object_bill', 'hideonsmartphone').''; + print img_picto($langs->trans("CreateInvoiceForThisCustomer").' : '.$companystatic->name, 'object_bill', 'hideonsmartphone').''; } } } print ''; + print ''; print dol_print_date($db->jdate($objp->date_commande), 'day'); print ''; - print dol_print_date($db->jdate($objp->date_delivery), 'day'); + print ''; + print dol_print_date($db->jdate($objp->date_livraison), 'day'); print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (empty($conf->global->PRODUIT_MULTIPRICES)) print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if (empty($conf->global->PRODUIT_MULTIPRICES)) print ''; print "\n"; } - $var=True; + $var=true; while ($i < $num) { $objp = $db->fetch_object($result); @@ -290,9 +292,13 @@ if ($action == 'create') print "\n"; } - + // Vat rate print ''; + + // Qty print ''; + + // Percent if ($objp->remise_percent > 0) { print '\n"; @@ -302,9 +308,19 @@ if ($action == 'create') print ''; } + // Total HT + print '\n"; + + // Total VAT + print '\n"; + + // Total TTC + print '\n"; + + // Total Unit price print '\n"; - // Price of product + // Current price of product if (empty($conf->global->PRODUIT_MULTIPRICES)) { if ($objp->fk_product > 0) @@ -432,7 +448,7 @@ else $num = count($object->lines); $i = 0; - $var=True; + $var=true; while ($i < $num) { $var=!$var; @@ -507,9 +523,14 @@ else */ print '
'; + if ($object->statut == 0 && $user->rights->facture->creer) + { + echo ''; + } + if ($object->statut == 0 && $user->rights->facture->supprimer) { - print ''.$langs->trans('Delete').''; + print ''; } print '
'; @@ -524,7 +545,7 @@ else /* * List mode */ - $sql = "SELECT s.nom, s.rowid as socid, f.titre, f.total, f.rowid as facid"; + $sql = "SELECT s.nom as name, s.rowid as socid, f.titre, f.total, f.rowid as facid"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture_rec as f"; $sql.= " WHERE f.fk_soc = s.rowid"; $sql.= " AND f.entity = ".$conf->entity; @@ -552,7 +573,7 @@ else if ($num > 0) { - $var=True; + $var=true; while ($i < min($num,$limit)) { $objp = $db->fetch_object($resql); @@ -564,28 +585,23 @@ else print "\n"; $companystatic->id=$objp->socid; - $companystatic->name=$objp->nom; + $companystatic->name=$objp->name; print ''; print ''."\n"; - if (! $objp->paye) + echo ''; - } - else - { - print ''; - } + echo ''; + echo $langs->trans("CreateBill"),''; } else { - print ''; + echo " "; } - - print "\n"; + echo "\n"; $i++; } } diff --git a/htdocs/compta/facture/impayees.php b/htdocs/compta/facture/impayees.php index d009216bc86..a010e7d7401 100644 --- a/htdocs/compta/facture/impayees.php +++ b/htdocs/compta/facture/impayees.php @@ -121,6 +121,7 @@ if ($action == 'presend' && GETPOST('sendmail')) $subject = GETPOST('subject'); $message = GETPOST('message'); $sendtocc = GETPOST('sentocc'); + $sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); $substitutionarray=array( '__ID__' => $object->id, @@ -135,12 +136,13 @@ if ($action == 'presend' && GETPOST('sendmail')) $message=make_substitutions($message, $substitutionarray); $actiontypecode='AC_FAC'; - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } // Create form object @@ -151,7 +153,7 @@ if ($action == 'presend' && GETPOST('sendmail')) // Send mail require_once(DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'); - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); if ($mailfile->error) { $resultmasssend.='
'.$mailfile->error.'
'; @@ -366,10 +368,22 @@ $now=dol_now(); $search_ref = GETPOST("search_ref"); $search_refcustomer=GETPOST('search_refcustomer'); $search_societe = GETPOST("search_societe"); +$search_paymentmode = GETPOST("search_paymentmode"); $search_montant_ht = GETPOST("search_montant_ht"); $search_montant_ttc = GETPOST("search_montant_ttc"); $late = GETPOST("late"); +// Do we click on purge search criteria ? +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=''; + $search_refcustomer=''; + $search_societe=''; + $search_paymentmode=''; + $search_montant_ht=''; + $search_montant_ttc=''; +} + $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -382,10 +396,10 @@ if (! $sortorder) $sortorder="ASC"; $limit = $conf->liste_limit; -$sql = "SELECT s.nom, s.rowid as socid, s.email"; +$sql = "SELECT s.nom as name, s.rowid as socid, s.email"; $sql.= ", f.rowid as facid, f.facnumber, f.ref_client, f.increment, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.localtax1, f.localtax2, f.revenuestamp"; $sql.= ", f.datef as df, f.date_lim_reglement as datelimite"; -$sql.= ", f.paye as paye, f.fk_statut, f.type"; +$sql.= ", f.paye as paye, f.fk_statut, f.type, f.fk_mode_reglement"; $sql.= ", sum(pf.amount) as am"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; @@ -411,10 +425,12 @@ if (GETPOST('filtre')) if ($search_ref) $sql .= " AND f.facnumber LIKE '%".$db->escape($search_ref)."%'"; if ($search_refcustomer) $sql .= " AND f.ref_client LIKE '%".$db->escape($search_refcustomer)."%'"; if ($search_societe) $sql .= " AND s.nom LIKE '%".$db->escape($search_societe)."%'"; +if ($search_paymentmode) $sql .= " AND f.fk_mode_reglement = ".$search_paymentmode.""; if ($search_montant_ht) $sql .= " AND f.total = '".$db->escape($search_montant_ht)."'"; if ($search_montant_ttc) $sql .= " AND f.total_ttc = '".$db->escape($search_montant_ttc)."'"; if (GETPOST('sf_ref')) $sql .= " AND f.facnumber LIKE '%".$db->escape(GETPOST('sf_ref'))."%'"; -$sql.= " GROUP BY s.nom, s.rowid, s.email, f.rowid, f.facnumber, f.increment, f.total, f.tva, f.total_ttc, f.localtax1, f.localtax2, f.revenuestamp, f.datef, f.date_lim_reglement, f.paye, f.fk_statut, f.type "; +$sql.= " GROUP BY s.nom, s.rowid, s.email, f.rowid, f.facnumber, f.ref_client, f.increment, f.total, f.tva, f.total_ttc, f.localtax1, f.localtax2, f.revenuestamp,"; +$sql.= " f.datef, f.date_lim_reglement, f.paye, f.fk_statut, f.type, fk_mode_reglement"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.= " ORDER BY "; $listfield=explode(',',$sortfield); @@ -440,6 +456,7 @@ if ($resql) if ($search_ref) $param.='&search_ref='.urlencode($search_ref); if ($search_refcustomer) $param.='&search_ref='.urlencode($search_refcustomer); if ($search_societe) $param.='&search_societe='.urlencode($search_societe); + if ($search_societe) $param.='&search_paymentmode='.urlencode($search_paymentmode); if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); if ($search_montant_ttc) $param.='&search_montant_ttc='.urlencode($search_montant_ttc); if ($late) $param.='&late='.urlencode($late); @@ -447,7 +464,7 @@ if ($resql) $urlsource=$_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; $urlsource.=str_replace('&','&',$param); - $titre=(! empty($socid)?$langs->trans("BillsCustomersUnpaidForCompany",$soc->nom):$langs->trans("BillsCustomersUnpaid")); + $titre=(! empty($socid)?$langs->trans("BillsCustomersUnpaidForCompany",$soc->name):$langs->trans("BillsCustomersUnpaid")); if ($option == 'late') $titre.=' ('.$langs->trans("Late").')'; else $titre.=' ('.$langs->trans("All").')'; @@ -457,8 +474,6 @@ if ($resql) print_fiche_titre($titre,$link); //print_barre_liste($titre,$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',0); // We don't want pagination on this page - dol_htmloutput_mesg($mesg); - print ''; if (! empty($mode) && $action == 'presend') @@ -527,10 +542,11 @@ if ($resql) print '
'.$langs->trans("Ref").''; diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php index bea20200882..1009b030210 100644 --- a/htdocs/commande/orderstoinvoice.php +++ b/htdocs/commande/orderstoinvoice.php @@ -58,6 +58,8 @@ $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $viewstatut = GETPOST('viewstatut'); +$error = 0; + if (! $sortfield) $sortfield='c.rowid'; if (! $sortorder) $sortorder='DESC'; @@ -71,7 +73,8 @@ if ($action == 'create') { if (is_array($selected) == false) { - $mesgs = array('
'.$langs->trans('Error_OrderNotChecked').'
'); + $error++; + setEventMessage($langs->trans('Error_OrderNotChecked'), 'errors'); } else { @@ -90,7 +93,7 @@ $hookmanager->initHooks(array('orderstoinvoice')); * Actions */ -if (($action == 'create' || $action == 'add') && empty($mesgs)) +if (($action == 'create' || $action == 'add') && !$error) { require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; @@ -248,7 +251,7 @@ if (($action == 'create' || $action == 'add') && empty($mesgs)) } else { - $mesgs[]=$discount->error; + setEventMessage($discount->error, 'errors'); $error++; break; } @@ -317,7 +320,7 @@ if (($action == 'create' || $action == 'add') && empty($mesgs)) } else { - $mesgs[]=$objectsrc->error; + setEventMessage($objectsrc->error, 'errors'); $error++; } $ii++; @@ -325,7 +328,7 @@ if (($action == 'create' || $action == 'add') && empty($mesgs)) } else { - $mesgs[]=$object->error; + setEventMessage($object->error, 'errors'); $error++; } } @@ -345,7 +348,8 @@ if (($action == 'create' || $action == 'add') && empty($mesgs)) $action='create'; $_GET["origin"]=$_POST["origin"]; $_GET["originid"]=$_POST["originid"]; - $mesgs[]='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); + $error++; } } } @@ -361,7 +365,7 @@ $formfile = new FormFile($db); $companystatic = new Societe($db); // Mode creation -if ($action == 'create' && empty($mesgs)) +if ($action == 'create' && !$error) { $facturestatic=new Facture($db); @@ -501,7 +505,7 @@ if ($action == 'create' && empty($mesgs)) //Mode liste -if (($action != 'create' && $action != 'add') || ! empty($mesgs)) +if (($action != 'create' && $action != 'add') || !$error) { llxHeader(); ?> @@ -569,16 +573,16 @@ if (($action != 'create' && $action != 'add') || ! empty($mesgs)) { // Company $companystatic->id=$socid; - $companystatic->nom=$soc->nom; + $companystatic->name=$soc->name; print '

'.$companystatic->getNomUrl(1,'customer').'

'; } print ''; print ''; - print_liste_field_titre($langs->trans('Ref'),'orderstoinvoice.php','c.ref','','&socid='.$socid,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('RefCustomerOrder'),'orderstoinvoice.php','c.ref_client','','&socid='.$socid,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('OrderDate'),'orderstoinvoice.php','c.date_commande','','&socid='.$socid, 'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('DeliveryDate'),'orderstoinvoice.php','c.date_livraison','','&socid='.$socid, 'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Ref'),$_SERVER["PHP_SELF"],'c.ref','','&socid='.$socid,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('RefCustomerOrder'),$_SERVER["PHP_SELF"],'c.ref_client','','&socid='.$socid,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('OrderDate'),$_SERVER["PHP_SELF"],'c.date_commande','','&socid='.$socid, 'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('DeliveryDate'),$_SERVER["PHP_SELF"],'c.date_livraison','','&socid='.$socid, 'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans('Status'),'','','','','align="right"'); print_liste_field_titre($langs->trans('GenerateBill'),'','','','','align="center"'); print ''; @@ -618,7 +622,7 @@ if (($action != 'create' && $action != 'add') || ! empty($mesgs)) print ''; print ''; - $var=True; + $var=true; $generic_commande = new Commande($db); while ($i < $num) @@ -697,7 +701,5 @@ if (($action != 'create' && $action != 'add') || ! empty($mesgs)) } -dol_htmloutput_mesg($mesg,$mesgs); - llxFooter(); $db->close(); diff --git a/htdocs/commande/tpl/index.html b/htdocs/commande/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/commande/tpl/linkedobjectblock.tpl.php b/htdocs/commande/tpl/linkedobjectblock.tpl.php index d2fe19c5b6f..c47aefe0958 100644 --- a/htdocs/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/commande/tpl/linkedobjectblock.tpl.php @@ -48,7 +48,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > + trans("ShowOrder"),"order").' '.$object->ref; ?>'; - print ''; + print ''; print ''; print ''; @@ -306,8 +305,6 @@ if ($_GET["id"] && $action == 'edit' && $user->rights->banque->configurer) print_fiche_titre($langs->trans("EditFinancialAccount")); print "
"; - dol_htmloutput_mesg($message); - print ''; print ''; print ''; @@ -425,7 +422,7 @@ if ($_GET["id"] && $action == 'edit' && $user->rights->banque->configurer) // IBAN print ''; - print ''; + print ''; print ''; print ''; diff --git a/htdocs/compta/bank/fiche.php b/htdocs/compta/bank/card.php similarity index 88% rename from htdocs/compta/bank/fiche.php rename to htdocs/compta/bank/card.php index bdb30e46528..b1852785466 100644 --- a/htdocs/compta/bank/fiche.php +++ b/htdocs/compta/bank/card.php @@ -1,8 +1,9 @@ - * Copyright (C) 2003 Jean-Louis Bergamo - * Copyright (C) 2004-2012 Laurent Destailleur - * Copytight (C) 2005-2009 Regis Houssin +/* Copyright (C) 2002-2003 Rodolphe Quiedeville + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2012 Laurent Destailleur + * Copytight (C) 2005-2009 Regis Houssin + * Copytight (C) 2014 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,7 +20,7 @@ */ /** - * \file htdocs/compta/bank/fiche.php + * \file htdocs/compta/bank/card.php * \ingroup banque * \brief Page to create/view a bank account */ @@ -34,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("banks"); $langs->load("categories"); $langs->load("companies"); +$langs->load("compta"); $action=GETPOST("action"); @@ -55,7 +57,7 @@ if ($_POST["action"] == 'add') $error=0; // Create account - $account = new Account($db,0); + $account = new Account($db); $account->ref = dol_sanitizeFileName(trim($_POST["ref"])); $account->label = trim($_POST["label"]); @@ -65,6 +67,7 @@ if ($_POST["action"] == 'add') $account->url = $_POST["url"]; $account->account_number = trim($_POST["account_number"]); + $account->accountancy_journal = trim($_POST["accountancy_journal"]); $account->solde = $_POST["solde"]; $account->date_solde = dol_mktime(12,0,0,$_POST["remonth"],$_POST["reday"],$_POST["reyear"]); @@ -99,7 +102,7 @@ if ($_POST["action"] == 'add') if (! $error) { - $id = $account->create($user->id); + $id = $account->create($user); if ($id > 0) { $_GET["id"]=$id; // Force chargement page en mode visu @@ -116,7 +119,7 @@ if ($_POST["action"] == 'update' && ! $_POST["cancel"]) $error=0; // Update account - $account = new Account($db, $_POST["id"]); + $account = new Account($db); $account->fetch($_POST["id"]); $account->ref = dol_string_nospecial(trim($_POST["ref"])); @@ -132,13 +135,14 @@ if ($_POST["action"] == 'update' && ! $_POST["cancel"]) $account->number = trim($_POST["number"]); $account->cle_rib = trim($_POST["cle_rib"]); $account->bic = trim($_POST["bic"]); - $account->iban_prefix = trim($_POST["iban_prefix"]); + $account->iban = trim($_POST["iban"]); $account->domiciliation = trim($_POST["domiciliation"]); $account->proprio = trim($_POST["proprio"]); $account->owner_address = trim($_POST["owner_address"]); $account->account_number = trim($_POST["account_number"]); + $account->accountancy_journal = trim($_POST["accountancy_journal"]); $account->currency_code = trim($_POST["account_currency_code"]); @@ -177,7 +181,7 @@ if ($_POST["action"] == 'update' && ! $_POST["cancel"]) } else { - $message='
'.$account->error.'
'; + setEventMessage($account->error, 'errors'); $action='edit'; // Force chargement page edition } } @@ -216,8 +220,6 @@ if ($action == 'create') print_fiche_titre($langs->trans("NewFinancialAccount")); - dol_htmloutput_mesg($message); - if ($conf->use_javascript_ajax) { print "\n".' '; - print '
- trans("ShowOrder"),"order").' '.$object->ref; ?> date,'day'); ?> rights->commande->lire) { diff --git a/htdocs/compta/ajaxpayment.php b/htdocs/compta/ajaxpayment.php index 66a1c997be3..27a167bc576 100644 --- a/htdocs/compta/ajaxpayment.php +++ b/htdocs/compta/ajaxpayment.php @@ -32,7 +32,6 @@ if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't nee //if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session) require '../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; $langs->load('compta'); @@ -115,4 +114,4 @@ $toJsonArray['result'] = price($result); // Return value to user format $toJsonArray['resultnum'] = price2num($result); // Return value to numeric format // Encode to JSON to return -echo dol_json_encode($toJsonArray); // Printing the call's result +echo json_encode($toJsonArray); // Printing the call's result diff --git a/htdocs/compta/bank/account.php b/htdocs/compta/bank/account.php index bd1928f3da4..87b7d3e62c5 100644 --- a/htdocs/compta/bank/account.php +++ b/htdocs/compta/bank/account.php @@ -72,8 +72,6 @@ if ($negpage) if ($page > GETPOST("nbpage")) $page = GETPOST("nbpage"); } -$mesg=''; - $object = new Account($db); /* @@ -83,6 +81,8 @@ $dateop=-1; if ($action == 'add' && $id && ! isset($_POST["cancel"]) && $user->rights->banque->modifier) { + $error = 0; + if (price2num($_POST["credit"]) > 0) { $amount = price2num($_POST["credit"]); @@ -98,11 +98,20 @@ if ($action == 'add' && $id && ! isset($_POST["cancel"]) && $user->rights->banqu $label=$_POST["label"]; $cat1=$_POST["cat1"]; - if (! $dateop) $mesg=$langs->trans("ErrorFieldRequired",$langs->trans("Date")); - if (! $operation) $mesg=$langs->trans("ErrorFieldRequired",$langs->trans("Type")); - if (! $amount) $mesg=$langs->trans("ErrorFieldRequired",$langs->trans("Amount")); + if (! $dateop) { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("Date")), 'errors'); + } + if (! $operation) { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("Type")), 'errors'); + } + if (! $amount) { + $error++; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->trans("Amount")), 'errors'); + } - if (! $mesg) + if (! $error) { $object->fetch($id); $insertid = $object->addline($dateop, $operation, $label, $amount, $num_chq, $cat1, $user); @@ -114,7 +123,7 @@ if ($action == 'add' && $id && ! isset($_POST["cancel"]) && $user->rights->banqu } else { - $mesg=$object->error; + setEventMessage($object->error, 'errors'); } } else @@ -241,7 +250,7 @@ if ($id > 0 || ! empty($ref)) $sql.= " AND ba.entity = ".$conf->entity; $sql.= $sql_rech; - dol_syslog("account.php count transactions - sql=".$sql, LOG_DEBUG); + dol_syslog("account.php count transactions -", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -300,8 +309,6 @@ if ($id > 0 || ! empty($ref)) print '
'; - dol_htmloutput_errors($mesg); - /** * Search form */ @@ -490,7 +497,7 @@ if ($id > 0 || ! empty($ref)) $sql.= $db->order("b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day $sql.= $db->plimit($limitsql, 0); - dol_syslog("account.php get transactions - sql=".$sql, LOG_DEBUG); + dol_syslog("account.php get transactions -", LOG_DEBUG); $result = $db->query($sql); if ($result) { @@ -582,7 +589,7 @@ if ($id > 0 || ! empty($ref)) } elseif ($links[$key]['type']=='payment_sc') { - print ''; + print ''; print ' '.img_object($langs->trans('ShowPayment'),'payment').' '; //print $langs->trans("SocialContributionPayment"); print ''; @@ -673,7 +680,7 @@ if ($id > 0 || ! empty($ref)) if ($links[$key]['type']=='company') { $societestatic->id=$links[$key]['url_id']; - $societestatic->nom=$links[$key]['label']; + $societestatic->name=$links[$key]['label']; print $societestatic->getNomUrl(1,'',16); } else if ($links[$key]['type']=='user') diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index e54c501fdab..30cf5b9c5ac 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -289,7 +289,7 @@ if ($result < 0) { $langs->load("errors"); $error++; - $mesg='
'.$langs->trans("ErrorFailedToCreateDir").'
'; + setEventMessage($langs->trans("ErrorFailedToCreateDir"), 'errors'); } else { diff --git a/htdocs/compta/bank/bankid_fr.php b/htdocs/compta/bank/bankid_fr.php index 43666cba5a5..03f0babe75d 100644 --- a/htdocs/compta/bank/bankid_fr.php +++ b/htdocs/compta/bank/bankid_fr.php @@ -63,8 +63,7 @@ if ($action == 'update' && ! $_POST["cancel"]) $account->number = trim($_POST["number"]); $account->cle_rib = trim($_POST["cle_rib"]); $account->bic = trim($_POST["bic"]); - $account->iban = trim($_POST["iban_prefix"]); - $account->iban_prefix = trim($_POST["iban_prefix"]); // deprecated + $account->iban = trim($_POST["iban"]); $account->domiciliation = trim($_POST["domiciliation"]); $account->proprio = trim($_POST["proprio"]); $account->owner_address = trim($_POST["owner_address"]); @@ -80,7 +79,7 @@ if ($action == 'update' && ! $_POST["cancel"]) } else { - $message='
'.$account->error.'
'; + setEventMessage($account->error, 'errors'); $action='edit'; // Force chargement page edition } } @@ -246,7 +245,7 @@ if (($_GET["id"] || $_GET["ref"]) && $action != 'edit') if ($account->getCountryCode() == 'IN') $bickey="SWIFT"; print '
'.$langs->trans($ibankey).''.$account->iban_prefix.'
'.$account->iban.'
'.$langs->trans($bickey).''.$account->bic.'
'.$langs->trans($ibankey).'
'.$langs->trans($bickey).'
'; print ''; print ''; @@ -3573,7 +3460,8 @@ if ($action == 'create') print ''; print ''; print ''; - while ($i < $num) { + while ($i < $num) + { $objp = $db->fetch_object($resqlorderlist); if ($objp->socid == $soc->id) { $var = ! $var; @@ -3591,7 +3479,7 @@ if ($action == 'create') $i ++; } print '
' . $langs->trans("AmountHTShort") . '' . $langs->trans("Company") . '
'; - print '
'; + print '
 
'; print ''; $db->free($resqlorderlist); } else { @@ -3601,6 +3489,9 @@ if ($action == 'create') print ''; } + // Show link to elements + if ($linktoelem) print '
'.$linktoelem; + // Link for paypal payment if (! empty($conf->paypal->enabled) && $object->statut != 0) { include_once DOL_DOCUMENT_ROOT . '/paypal/lib/paypal.lib.php'; @@ -3615,11 +3506,15 @@ if ($action == 'create') $somethingshown = $formactions->showactions($object, 'invoice', $socid); print ''; - } else { + } + else + { /* - * Affiche formulaire mail + * Action presend (or prerelance) */ + $object->fetch_projet(); + // By default if $action=='presend' $titreform = 'SendBillByMail'; $topicmail = 'SendBillRef'; @@ -3639,21 +3534,24 @@ if ($action == 'create') $fileparams = dol_most_recent_file($conf->facture->dir_output . '/' . $ref, preg_quote($ref, '/')); $file = $fileparams ['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->thirdparty->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('bills'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) - $newlang = $_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - $newlang = $object->client->default_lang; - if (! empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - - $result = facture_pdf_create($db, $object, GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db, $result); exit(); @@ -3668,6 +3566,7 @@ if ($action == 'create') // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -3681,10 +3580,11 @@ if ($action == 'create') $formmail->withtocc = $liste; // List suggested for CC $formmail->withtoccc = $conf->global->MAIN_EMAIL_USECCC; if (empty($object->ref_client)) { - $formmail->withtopic = $langs->transnoentities($topicmail, '__FACREF__'); + $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__FACREF__'); } else if (! empty($object->ref_client)) { - $formmail->withtopic = $langs->transnoentities($topicmail, '__FACREF__(__REFCLIENT__)'); + $formmail->withtopic = $outputlangs->transnoentities($topicmail, '__FACREF__ (__REFCLIENT__)'); } + $formmail->withfile = 2; $formmail->withbody = 1; $formmail->withdeliveryreceipt = 1; @@ -3693,6 +3593,8 @@ if ($action == 'create') $formmail->substit ['__FACREF__'] = $object->ref; $formmail->substit ['__SIGNATURE__'] = $user->signature; $formmail->substit ['__REFCLIENT__'] = $object->ref_client; + $formmail->substit ['__THIRPARTY_NAME__'] = $object->thirdparty->name; + $formmail->substit ['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:''); $formmail->substit ['__PERSONALIZED__'] = ''; $formmail->substit ['__CONTACTCIVNAME__'] = ''; @@ -3703,7 +3605,7 @@ if ($action == 'create') if (is_array($contactarr) && count($contactarr) > 0) { foreach ($contactarr as $contact) { - if ($contact ['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { + if ($contact ['libelle'] == $langs->trans('TypeContact_facture_external_BILLING')) { // TODO Use code and not label require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php'; @@ -3736,7 +3638,5 @@ if ($action == 'create') } } -dol_htmloutput_mesg('', $mesgs); - llxFooter(); $db->close(); diff --git a/htdocs/compta/facture/admin/facture_cust_extrafields.php b/htdocs/compta/facture/admin/facture_cust_extrafields.php index 6da617b740c..6d60180593a 100644 --- a/htdocs/compta/facture/admin/facture_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facture_cust_extrafields.php @@ -37,7 +37,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -70,7 +70,7 @@ $linkback=''.$langs->trans("BackToM print_fiche_titre($langs->trans("BillsSetup"),$linkback,'setup'); print '
'; -$head = invoice_admin_prepare_head(null); +$head = invoice_admin_prepare_head(); dol_fiche_head($head, 'attributes', $langs->trans("Invoices"), 0, 'invoice'); diff --git a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php index ccd208c7c6f..fd4284a01dd 100644 --- a/htdocs/compta/facture/admin/facturedet_cust_extrafields.php +++ b/htdocs/compta/facture/admin/facturedet_cust_extrafields.php @@ -38,7 +38,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -71,7 +71,7 @@ $linkback='
'.$langs->trans("BackToM print_fiche_titre($langs->trans("BillsSetup"),$linkback,'setup'); print '
'; -$head = invoice_admin_prepare_head(null); +$head = invoice_admin_prepare_head(); dol_fiche_head($head, 'attributeslines', $langs->trans("Invoices"), 0, 'invoice'); diff --git a/htdocs/compta/facture/admin/index.html b/htdocs/compta/facture/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/facture/apercu.php b/htdocs/compta/facture/apercu.php index 856640e306e..211d9241a8f 100644 --- a/htdocs/compta/facture/apercu.php +++ b/htdocs/compta/facture/apercu.php @@ -375,7 +375,7 @@ if ($id > 0 || ! empty($ref)) { $project = New Project($db); $project->fetch($object->fk_project); - print '
'.$project->title.''; + print ''.$project->title.''; } else { @@ -398,7 +398,7 @@ if ($id > 0 || ! empty($ref)) // Si fichier png PDF d'1 page trouve if (file_exists($fileimage)) { - print ''; + print ''; } // Si fichier png PDF de plus d'1 page trouve elseif (file_exists($fileimagebis)) @@ -411,12 +411,12 @@ elseif (file_exists($fileimagebis)) if (file_exists($dir_output.$preview)) { - print '

'; + print '

'; } } } -$db->close(); - llxFooter(); + +$db->close(); diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 7147f51c613..f6c0ab1a481 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -216,7 +216,7 @@ class FactureRec extends Facture $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql.= ' WHERE f.rowid='.$rowid; - dol_syslog("FactureRec::Fetch rowid=".$rowid." sql=".$sql, LOG_DEBUG); + dol_syslog("FactureRec::Fetch rowid=".$rowid."", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -269,7 +269,6 @@ class FactureRec extends Facture if ($result < 0) { $this->error=$this->db->error(); - dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR); return -3; } return 1; @@ -284,7 +283,6 @@ class FactureRec extends Facture else { $this->error=$this->db->error(); - dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR); return -1; } } @@ -359,7 +357,6 @@ class FactureRec extends Facture else { $this->error=$this->db->error(); - dol_syslog('Facture::fetch_lines: Error '.$this->error, LOG_ERR); return -3; } } @@ -497,7 +494,7 @@ class FactureRec extends Facture $sql.= ", ".$rang; $sql.= ", ".$special_code.")"; - dol_syslog(get_class($this)."::addline sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::addline", LOG_DEBUG); if ($this->db->query($sql)) { $this->id=$facid; @@ -507,7 +504,6 @@ class FactureRec extends Facture else { $this->error=$this->db->lasterror(); - dol_syslog("FactureRec::addline sql=".$this->error, LOG_ERR); return -1; } } diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 1df0696486c..cd8ba3b06a1 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -7,9 +7,9 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2012-2014 Christophe Battarel - * Copyright (C) 2012 Marcos García + * Copyright (C) 2012-2014 Marcos García * Copyright (C) 2013 Cedric Gross * Copyright (C) 2013 Florian Henry * @@ -34,9 +34,9 @@ */ include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php'; -require_once DOL_DOCUMENT_ROOT .'/product/class/product.class.php'; -require_once DOL_DOCUMENT_ROOT .'/societe/class/client.class.php'; -require_once DOL_DOCUMENT_ROOT .'/margin/lib/margins.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; +require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; /** @@ -103,6 +103,7 @@ class Facture extends CommonInvoice var $cond_reglement_code; // Code in llx_c_paiement var $mode_reglement_id; // Id in llx_c_paiement var $mode_reglement_code; // Code in llx_c_paiement + var $fk_account; // Id of bank account var $fk_bank; // Field to store bank id to use when payment mode is withdraw var $modelpdf; var $products=array(); // deprecated @@ -239,6 +240,7 @@ class Facture extends CommonInvoice $sql.= ", note_private"; $sql.= ", note_public"; $sql.= ", ref_client, ref_int"; + $sql.= ", fk_account"; $sql.= ", fk_facture_source, fk_user_author, fk_projet"; $sql.= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf"; $sql.= ")"; @@ -256,6 +258,7 @@ class Facture extends CommonInvoice $sql.= ",".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ",".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null"); $sql.= ",".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null"); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ",".($this->fk_facture_source?"'".$this->db->escape($this->fk_facture_source)."'":"null"); $sql.= ",".($user->id > 0 ? "'".$user->id."'":"null"); $sql.= ",".($this->fk_project?$this->fk_project:"null"); @@ -263,7 +266,7 @@ class Facture extends CommonInvoice $sql.= ",".$this->mode_reglement_id; $sql.= ", '".$this->db->idate($datelim)."', '".$this->modelpdf."')"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -273,7 +276,7 @@ class Facture extends CommonInvoice $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET facnumber='".$this->ref."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; @@ -461,6 +464,8 @@ class Facture extends CommonInvoice $result=$this->update_price(1); if ($result > 0) { + $action='create'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('invoicedao')); @@ -479,14 +484,10 @@ class Facture extends CommonInvoice } else if ($reshook < 0) $error++; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_CREATE',$user); + if ($result < 0) $error++; + // End call triggers if (! $error) { @@ -516,7 +517,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create error ".$this->error." sql=".$sql, LOG_ERR); $this->db->rollback(); return -1; } @@ -600,6 +600,8 @@ class Facture extends CommonInvoice // Load source object $objFrom = dol_clone($this); + + // Change socid if needed if (! empty($socid) && $socid != $this->socid) { @@ -645,6 +647,18 @@ class Facture extends CommonInvoice // Create clone $result=$this->create($user); if ($result < 0) $error++; + else { + // copy internal contacts + if ($this->copy_linked_contact($objFrom, 'internal') < 0) + $error++; + + // copy external contacts if same company + elseif ($objFrom->socid == $this->socid) + { + if ($this->copy_linked_contact($objFrom, 'external') < 0) + $error++; + } + } if (! $error) { @@ -657,14 +671,10 @@ class Facture extends CommonInvoice if ($reshook < 0) $error++; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_CLONE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_CLONE',$user); + if ($result < 0) $error++; + // End call triggers } // End @@ -849,6 +859,7 @@ class Facture extends CommonInvoice $sql.= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf'; $sql.= ', f.fk_facture_source'; $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet, f.extraparams'; + $sql.= ', f.fk_account'; $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f'; @@ -860,7 +871,7 @@ class Facture extends CommonInvoice 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)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -899,6 +910,7 @@ class Facture extends CommonInvoice $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc; + $this->fk_account = ($obj->fk_account>0)?$obj->fk_account:null; $this->fk_project = $obj->fk_projet; $this->fk_facture_source = $obj->fk_facture_source; $this->note = $obj->note_private; // deprecated @@ -929,7 +941,6 @@ class Facture extends CommonInvoice if ($result < 0) { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return -3; } return 1; @@ -944,7 +955,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR); return -1; } } @@ -970,7 +980,7 @@ class Facture extends CommonInvoice $sql.= ' WHERE l.fk_facture = '.$this->id; $sql.= ' ORDER BY l.rang'; - dol_syslog(get_class($this).'::fetch_lines sql='.$sql, LOG_DEBUG); + dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -1030,7 +1040,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this).'::fetch_lines '.$this->error,LOG_ERR); return -3; } } @@ -1043,7 +1052,7 @@ class Facture extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -1103,7 +1112,7 @@ class Facture extends CommonInvoice $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -1113,14 +1122,10 @@ class Facture extends CommonInvoice { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End call triggers + // Call trigger + $result=$this->call_trigger('BILL_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers } } @@ -1275,14 +1280,10 @@ class Facture extends CommonInvoice if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_DELETE',$user); + if ($result < 0) $error++; + // End call triggers } // Removed extrafields @@ -1325,11 +1326,10 @@ class Facture extends CommonInvoice $sql.= ' SET fk_facture = NULL, fk_facture_line = NULL'; $sql.= ' WHERE fk_facture_line IN ('.join(',',$list_rowid_det).')'; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if (! $this->db->query($sql)) { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -5; } @@ -1358,9 +1358,15 @@ class Facture extends CommonInvoice // Delete invoice line $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.$rowid; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + if ($this->db->query($sql) && $this->delete_linked_contact()) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.$rowid; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $resql=$this->db->query($sql); if ($resql) { @@ -1398,7 +1404,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->lasterror()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -6; } @@ -1406,15 +1411,12 @@ class Facture extends CommonInvoice else { $this->error=$this->db->lasterror()." sql=".$sql; - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -4; } } else { - $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -1446,18 +1448,14 @@ class Facture extends CommonInvoice if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'"; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_PAYED',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_PAYED',$user); + if ($result < 0) $error++; + // End call triggers } else { @@ -1502,18 +1500,14 @@ class Facture extends CommonInvoice $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::set_unpaid sql=".$sql); + dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_UNPAYED',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_UNPAYED',$user); + if ($result < 0) $error++; + // End call triggers } else { @@ -1573,18 +1567,14 @@ class Facture extends CommonInvoice $resql=$this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_CANCEL',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; - $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('BILL_CANCEL',$user); + if ($result < 0) + { $this->db->rollback(); return -1; - } - // Fin appel triggers + // End call triggers $this->db->commit(); return 1; @@ -1610,10 +1600,11 @@ class Facture extends CommonInvoice * * @param User $user Object user that validate * @param string $force_number Reference to force on invoice - * @param int $idwarehouse Id of warehouse to use for stock decrease - * @return int <0 if KO, >0 if OK + * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease) + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @return int <0 if KO, >0 if OK */ - function validate($user, $force_number='', $idwarehouse=0) + function validate($user, $force_number='', $idwarehouse=0, $notrigger=0) { global $conf,$langs; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -1701,6 +1692,7 @@ class Facture extends CommonInvoice { $num = $this->ref; } + $this->newref = $num; if ($num) { @@ -1716,11 +1708,10 @@ class Facture extends CommonInvoice } $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::validate sql=".$sql); + dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::validate Echec update - 10 - sql=".$sql, LOG_ERR); dol_print_error($this->db); $error++; } @@ -1737,7 +1728,7 @@ class Facture extends CommonInvoice $result=$this->client->set_as_client(); // Si active on decremente le produit principal et ses composants a la validation de facture - if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL)) + if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); @@ -1761,30 +1752,45 @@ class Facture extends CommonInvoice } } + // Trigger calls + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('BILL_VALIDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + if (! $error) { - $this->oldref = ''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Rename of object directory ($this->ref = old ref, $num = new ref) // to not lose the linked files - $facref = dol_sanitizeFileName($this->ref); - $snumfa = dol_sanitizeFileName($num); - $dirsource = $conf->facture->dir_output.'/'.$facref; - $dirdest = $conf->facture->dir_output.'/'.$snumfa; + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->facture->dir_output.'/'.$oldref; + $dirdest = $conf->facture->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { - $this->oldref = $facref; - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($conf->facture->dir_output.'/'.$snumfa.'/'.$facref.'*.*'); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -1799,19 +1805,6 @@ class Facture extends CommonInvoice $this->brouillon=0; $this->date_validation=$now; } - - // Trigger calls - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } } else { @@ -1855,7 +1848,7 @@ class Facture extends CommonInvoice $sql.= " SET fk_statut = 0"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_draft sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_draft", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -1884,17 +1877,15 @@ class Facture extends CommonInvoice $old_statut=$this->statut; $this->brouillon = 1; $this->statut = 0; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_UNVALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { + // Call trigger + $result=$this->call_trigger('BILL_UNVALIDATE',$user); + if ($result < 0) + { $error++; - $this->errors=$interface->errors; $this->statut=$old_statut; $this->brouillon=0; } - // Fin appel triggers + // End call triggers } else { $this->db->rollback(); return -1; @@ -2002,7 +1993,7 @@ class Facture extends CommonInvoice // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type); @@ -2090,7 +2081,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR); $this->db->rollback(); return -1; } @@ -2161,7 +2151,7 @@ class Facture extends CommonInvoice // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type,'',$localtaxes_type); $total_ht = $tabprice[0]; @@ -2278,12 +2268,11 @@ class Facture extends CommonInvoice $sql.= ' SET fk_facture_line = NULL'; $sql.= ' WHERE fk_facture_line = '.$rowid; - dol_syslog(get_class($this)."::deleteline sql=".$sql); + dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $result = $this->db->query($sql); if (! $result) { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2373,7 +2362,7 @@ class Facture extends CommonInvoice $sql.= ' WHERE rowid = '.$this->id; $sql.= ' AND fk_statut = 0'; - dol_syslog(get_class($this)."::set_remise_absolue sql=$sql"); + dol_syslog(get_class($this)."::set_remise_absolue", LOG_DEBUG); if ($this->db->query($sql)) { @@ -2418,7 +2407,7 @@ class Facture extends CommonInvoice $sql.= ' AND p.fk_paiement = t.id'; if ($filtertype) $sql.=" AND t.code='PRE'"; - dol_syslog(get_class($this)."::getListOfPayments sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2764,7 +2753,7 @@ class Facture extends CommonInvoice if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid; $sql.= " ORDER BY f.facnumber"; - dol_syslog(get_class($this)."::list_replacable_invoices sql=$sql"); + dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2780,7 +2769,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::list_replacable_invoices ".$this->error, LOG_ERR); return -1; } } @@ -2814,7 +2802,7 @@ class Facture extends CommonInvoice if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid; $sql.= " ORDER BY f.facnumber"; - dol_syslog(get_class($this)."::list_qualified_avoir_invoices sql=".$sql); + dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2836,7 +2824,6 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::list_avoir_invoices ".$this->error, LOG_ERR); return -1; } } @@ -2850,6 +2837,8 @@ class Facture extends CommonInvoice */ function demande_prelevement($user) { + $error=0; + dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); if ($this->statut > 0 && $this->paye == 0) @@ -2863,7 +2852,7 @@ class Facture extends CommonInvoice $sql.= ' WHERE fk_facture = '.$this->id; $sql.= ' AND traite = 0'; - dol_syslog(get_class($this)."::demande_prelevement sql=".$sql); + dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2894,22 +2883,33 @@ class Facture extends CommonInvoice $sql .= ",'".$bac->number."'"; $sql .= ",'".$bac->cle_rib."')"; - dol_syslog(get_class($this)."::demande_prelevement sql=".$sql); - if ($this->db->query($sql)) + dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); + $resql=$this->db->query($sql); + if (! $resql) { - return 1; - } - else - { $this->error=$this->db->lasterror(); dol_syslog(get_class($this).'::demandeprelevement Erreur'); - return -1; + $error++; } + + if (! $error) + { + // Force payment mode of invoice to withdraw + $payment_mode_id = dol_getIdFromCode($this->db, 'PRE', 'c_paiement'); + if ($payment_mode_id > 0) + { + $result=$this->setPaymentMethods($payment_mode_id); + } + } + + if ($error) return -1; + return 1; } else { $this->error="A request already exists"; dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours'); + return 0; } } else @@ -3208,11 +3208,11 @@ class Facture extends CommonInvoice $sql.= ' p.ref as product_ref, p.fk_product_type, p.label as product_label,'; $sql.= ' p.description as product_desc'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l'; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product p ON l.fk_product=p.rowid'; + $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product=p.rowid'; $sql.= ' WHERE l.fk_facture = '.$this->id; $sql.= ' ORDER BY l.rang ASC, l.rowid'; - dol_syslog(get_class($this).'::getLinesArray sql='.$sql,LOG_DEBUG); + dol_syslog(get_class($this).'::getLinesArray',LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -3262,21 +3262,55 @@ class Facture extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog("Error sql=".$sql.", error=".$this->error,LOG_ERR); return -1; } } + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs objet lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int <0 if KO, >0 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$user,$langs; + + $langs->load("bills"); + + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->FACTURE_ADDON_PDF)) + { + $modele = $conf->global->FACTURE_ADDON_PDF; + } + else + { + $modele = 'crabe'; + } + } + + $modelpath = "core/modules/facture/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + + + } /** - * \class FactureLigne - * \brief Classe permettant la gestion des lignes de factures - * Gere des lignes de la table llx_facturedet + * Class to manage invoice lines. + * Saved into database table llx_facturedet */ -class FactureLigne extends CommonInvoiceLine +class FactureLigne extends CommonInvoiceLine { var $db; var $error; @@ -3534,7 +3568,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= " ".price2num($this->total_localtax2); $sql.= ')'; - dol_syslog(get_class($this)."::insert sql=".$sql); + dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3600,18 +3634,14 @@ class FactureLigne extends CommonInvoiceLine if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEBILL_INSERT',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; - $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEBILL_INSERT',$user); + if ($result < 0) + { $this->db->rollback(); return -2; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -3621,7 +3651,6 @@ class FactureLigne extends CommonInvoiceLine else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -3701,7 +3730,7 @@ class FactureLigne extends CommonInvoiceLine if (! empty($this->rang)) $sql.= ", rang=".$this->rang; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -3717,18 +3746,14 @@ class FactureLigne extends CommonInvoiceLine if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEBILL_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; - $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEBILL_UPDATE',$user); + if ($result < 0) + { $this->db->rollback(); return -2; } - // Fin appel triggers + // End call triggers } $this->db->commit(); return 1; @@ -3736,7 +3761,6 @@ class FactureLigne extends CommonInvoiceLine else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -3755,31 +3779,26 @@ class FactureLigne extends CommonInvoiceLine $this->db->begin(); + // Call trigger + $result=$this->call_trigger('LINEBILL_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if ($this->db->query($sql) ) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEBILL_DELETE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; - $this->errors=$interface->errors; - $this->db->rollback(); - return -1; - } - // Fin appel triggers - $this->db->commit(); - return 1; } else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::delete Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -3808,7 +3827,7 @@ class FactureLigne extends CommonInvoiceLine $sql.= ",total_ttc=".price2num($this->total_ttc).""; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update_total sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -3819,7 +3838,6 @@ class FactureLigne extends CommonInvoiceLine else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } diff --git a/htdocs/compta/facture/class/index.html b/htdocs/compta/facture/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 62ebcbacdbd..b75bb056e03 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -119,7 +119,7 @@ class PaymentTerm // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -185,7 +185,7 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -213,7 +213,6 @@ class PaymentTerm // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -235,7 +234,7 @@ class PaymentTerm // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; $sql.= " WHERE t.code = 'RECEP'"; - dol_syslog(get_class($this)."::getDefaultId sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -250,7 +249,6 @@ class PaymentTerm // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::getDefaultId ".$this->error, LOG_ERR); return -1; } } @@ -263,7 +261,7 @@ class PaymentTerm // extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -301,7 +299,7 @@ class PaymentTerm // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -357,7 +355,7 @@ class PaymentTerm // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index c3c629bc68d..8fe20cd66f6 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -127,7 +127,6 @@ $userstatic=new User($db); /* Mode vue et edition */ /* */ /* *************************************************************************** */ -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { diff --git a/htdocs/compta/facture/fiche-rec.php b/htdocs/compta/facture/fiche-rec.php index 1929a8a3721..1fd4d2c80fc 100644 --- a/htdocs/compta/facture/fiche-rec.php +++ b/htdocs/compta/facture/fiche-rec.php @@ -32,7 +32,6 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $langs->load('bills'); $langs->load('compta'); -$langs->load('products'); // Security check $id=(GETPOST('facid','int')?GETPOST('facid','int'):GETPOST('id','int')); @@ -219,15 +218,18 @@ if ($action == 'create') if ($num) { print '

'.$langs->trans("Description").''.$langs->trans("VAT").''.$langs->trans("Qty").''.$langs->trans("ReductionShort").''.$langs->trans("PriceU").''.$langs->trans("CurrentProductPrice").''.$langs->trans("Description").''.$langs->trans("VAT").''.$langs->trans("Qty").''.$langs->trans("ReductionShort").''.$langs->trans("TotalHT").''.$langs->trans("TotalVAT").''.$langs->trans("TotalTTC").''.$langs->trans("PriceUHT").''.$langs->trans("CurrentProductPrice").'
'.vatrate($objp->tva_tx).'%'.$objp->qty.''.$objp->remise_percent." % '.price($objp->total_ht)."'.price($objp->total_vat)."'.price($objp->total_ttc)."'.price($objp->subprice)."'.$companystatic->getNomUrl(1,'customer').''.price($objp->total).''; + + if ($user->rights->facture->creer) { - if ($objp->fk_statut == 0) - { - print ''.$langs->trans("Draft").''.$langs->trans("Validated").' 
'; print ''; print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"f.facnumber","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans('RefCustomer'),$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('RefCustomer'),$_SERVER["PHP_SELF"],'f.ref_client','',$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"f.datef","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateDue"),$_SERVER["PHP_SELF"],"f.date_lim_reglement","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("PaymentMode"),$_SERVER["PHP_SELF"],"f.fk_reglement_mode","",$param,"",$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountHT"),$_SERVER["PHP_SELF"],"f.total","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Taxes"),$_SERVER["PHP_SELF"],"f.tva","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"f.total_ttc","",$param,'align="right"',$sortfield,$sortorder); @@ -552,12 +568,15 @@ if ($resql) // Ref print ''; - print ''; + print ''; print ''; print ''; print ''; + print ''; print ''; print ''; print ''; @@ -565,6 +584,7 @@ if ($resql) print ''; print ''; if (empty($mode)) { @@ -582,7 +602,7 @@ if ($resql) if ($num > 0) { - $var=True; + $var=true; $total_ht=0; $total_tva=0; $total_ttc=0; @@ -629,15 +649,28 @@ if ($resql) print "\n"; - // Customer ref - print ''; + // Customer ref + print ''; print ''."\n"; print ''."\n"; - print ''; + print ''; + + // Payment mode + print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; diff --git a/htdocs/compta/facture/index.html b/htdocs/compta/facture/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/facture/index.php b/htdocs/compta/facture/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/compta/facture/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 3532125ed8e..56bd57c725a 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -108,9 +108,10 @@ $now=dol_now(); $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); // Do we click on purge search criteria ? -if (GETPOST("button_removefilter_x")) +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $search_categ=''; $search_user=''; @@ -143,7 +144,7 @@ else $sql = 'SELECT DISTINCT'; $sql.= ' f.rowid as facid, f.facnumber, f.ref_client, f.type, f.note_private, f.increment, f.total as total_ht, f.tva as total_tva, f.total_ttc,'; $sql.= ' f.datef as df, f.date_lim_reglement as datelimite,'; $sql.= ' f.paye as paye, f.fk_statut,'; -$sql.= ' s.nom, s.rowid as socid, s.code_client, s.client '; +$sql.= ' s.nom as name, s.rowid as socid, s.code_client, s.client '; if (! $sall) $sql.= ', SUM(pf.amount) as am'; // To be able to sort on status $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql.= ', '.MAIN_DB_PREFIX.'facture as f'; @@ -264,7 +265,7 @@ if ($resql) if ($search_user > 0) $param.='&search_user=' .$search_user; if ($search_montant_ht) $param.='&search_montant_ht='.$search_montant_ht; if ($search_montant_ttc) $param.='&search_montant_ttc='.$search_montant_ttc; - print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->nom:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); + print_barre_liste($langs->trans('BillsCustomers').' '.($socid?' '.$soc->name:''),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); $i = 0; print ''."\n"; @@ -327,11 +328,12 @@ if ($resql) print ''; print ''; print '\n"; if ($num > 0) { - $var=True; + $var=true; $total_ht=0; $total_tva=0; $total_ttc=0; @@ -398,7 +400,7 @@ if ($resql) print ''; print ''; + // Conditions de reglement + print ''; + // Date payment term print ''; - print ''; - print ''; - print ''; - - print '
'; print ''; - print ''; - print ''; + print ''; + print '  '; + $form->select_types_paiements($search_paymentmode, 'search_paymentmode'); + print '  '; print ''; + print ''; print ''; - print $objp->ref_client; - print ''; + print $objp->ref_client; + print ''.dol_print_date($db->jdate($objp->df),'day').''.dol_print_date($db->jdate($objp->datelimite),'day').''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($objp->nom,28).''; + $thirdparty=new Societe($db); + $thirdparty->id=$objp->socid; + $thirdparty->name=$objp->name; + $thirdparty->client=$objp->client; + $thirdparty->code_client=$objp->code_client; + print $thirdparty->getNomUrl(1,'customer'); + print ''; + $form->form_modes_reglement($_SERVER['PHP_SELF'], $objp->fk_mode_reglement, 'none'); + print ''.price($objp->total_ht).''.price($objp->total_tva); @@ -691,7 +724,7 @@ if ($resql) } print '
'.$langs->trans("Total").''.$langs->trans("Total").''.price($total_ht).''.price($total_tva).''.price($total_ttc).' '; + print ''; print "
'; $thirdparty=new Societe($db); $thirdparty->id=$objp->socid; - $thirdparty->nom=$objp->nom; + $thirdparty->name=$objp->name; $thirdparty->client=$objp->client; $thirdparty->code_client=$objp->code_client; print $thirdparty->getNomUrl(1,'customer'); diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 81505af34ee..1b4f440b461 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -3,7 +3,7 @@ * Copyright (C) 2004 Eric Seigne * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -58,6 +58,7 @@ if ($id > 0 || ! empty($ref)) } } + /* * Actions */ @@ -69,14 +70,14 @@ if ($action == "new") $result = $object->demande_prelevement($user); if ($result > 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; + setEventMessage($langs->trans("RecordSaved")); } else { setEventMessage($object->error, 'errors'); } } + $action=''; } if ($action == "delete") @@ -307,6 +308,31 @@ if ($object->id > 0) print '
'; + print ''; + if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print ''; + print '
'; + print $langs->trans('PaymentConditionsShort'); + print 'id.'">'.img_edit($langs->trans('SetConditions'),1).'
'; + print '
'; + if ($object->type != Facture::TYPE_CREDIT_NOTE) + { + if ($action == 'editconditions') + { + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'cond_reglement_id'); + } + else + { + $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'none'); + } + } + else + { + print ' '; + } + print '
'; print ''; - // Conditions de reglement - print ''; - - // Mode de reglement + // Payment mode print ''; print ''; @@ -219,7 +219,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) { $sql = "SELECT f.ref, f.rowid, f.total_ttc, f.type,"; - $sql.= " s.nom, s.rowid as socid"; + $sql.= " s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.rowid = f.fk_soc AND f.fk_statut = 0"; @@ -254,7 +254,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- print ''; print ''; @@ -294,7 +294,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql = "SELECT f.rowid, f.facnumber, f.fk_statut, f.type, f.total, f.total_ttc, f.paye, f.tms,"; $sql.= " f.date_lim_reglement as datelimite,"; - $sql.= " s.nom, s.rowid as socid,"; + $sql.= " s.nom as name, s.rowid as socid,"; $sql.= " sum(pf.amount) as am"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; @@ -351,7 +351,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; @@ -392,7 +392,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $facstatic=new FactureFournisseur($db); $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.libelle, ff.total_ht, ff.total_ttc, ff.tms, ff.paye"; - $sql.= ", s.nom, s.rowid as socid"; + $sql.= ", s.nom as name, s.rowid as socid"; $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"; @@ -432,7 +432,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- print ''; print ''; @@ -494,7 +494,7 @@ if (! empty($conf->don->enabled) && $user->rights->societe->lire) print ''; if ($num) { - $var = True; + $var = true; $total_ttc = $totalam = $total = 0; $var=true; @@ -613,7 +613,7 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $langs->load("orders"); $sql = "SELECT sum(f.total) as tot_fht, sum(f.total_ttc) as tot_fttc,"; - $sql.= " s.nom, s.rowid as socid,"; + $sql.= " s.nom as name, s.rowid as socid,"; $sql.= " c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.total_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -639,7 +639,7 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us $i = 0; print '
'; @@ -333,32 +359,7 @@ if ($object->id > 0) } print '
'; - print ''; - if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && ! empty($object->brouillon) && $user->rights->facture->creer) print ''; - print '
'; - print $langs->trans('PaymentConditionsShort'); - print 'id.'">'.img_edit($langs->trans('SetConditions'),1).'
'; - print '
'; - if ($object->type != Facture::TYPE_CREDIT_NOTE) - { - if ($action == 'editconditions') - { - $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'cond_reglement_id'); - } - else - { - $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'none'); - } - } - else - { - print ' '; - } - print '
'; print ''; + // Bank Account + print '"; + print ''; + // Montants print ''; print ''; @@ -384,21 +405,19 @@ if ($object->id > 0) print ''; // Amount Local Taxes - if ($mysoc->country_code=='ES') + if ($mysoc->localtax1_assuj=="1") //Localtax1 { - if ($mysoc->localtax1_assuj=="1") //Localtax1 RE - { - print ''; - print ''; - print ''; - } - if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF - { - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; } + if ($mysoc->localtax2_assuj=="1") //Localtax2 + { + print ''; + print ''; + print ''; + } + print ''; print ''; @@ -493,7 +512,7 @@ if ($object->id > 0) print ''; print ''; print ''; - $var=True; + $var=true; if ($result_sql) { @@ -509,7 +528,7 @@ if ($object->id > 0) print ''; print ''; print ''; - print ''; + print ''; print ''; print '\n"; - print ''; + print ''; print ''; print ''; diff --git a/htdocs/compta/facture/tpl/index.html b/htdocs/compta/facture/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/hrm.php b/htdocs/compta/hrm.php index a8ce6a45714..6252f0f6ef7 100644 --- a/htdocs/compta/hrm.php +++ b/htdocs/compta/hrm.php @@ -1,7 +1,7 @@ - * Copyright (C) 2013-2014 Laurent Destailleur - * Copyright (C) 2012 Regis Houssin +/* Copyright (C) 2011 Dimitri Mouillard + * Copyright (C) 2013-2014 Laurent Destailleur + * Copyright (C) 2012-2014 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 @@ -38,6 +38,8 @@ $langs->load('users'); $langs->load('holidays'); $langs->load('trips'); +$socid=GETPOST("socid"); + // Protection if external user if ($user->societe_id > 0) accessforbidden(); @@ -58,6 +60,8 @@ if ($user->societe_id > 0) accessforbidden(); $holiday = new Holiday($db); $holidaystatic=new Holiday($db); +$childids = $user->getAllChildIds(); +$childids[]=$user->id; llxHeader(array(),$langs->trans('HRMArea')); @@ -96,9 +100,9 @@ if (! empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) print '
'; print $langs->trans('PaymentMode'); @@ -376,6 +377,26 @@ if ($object->id > 0) } print '
'; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if (($action != 'editbankaccount') && $user->rights->commande->creer && ! empty($object->brouillon)) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print '
'; + if ($action == 'editbankaccount') + { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } + else + { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print "
'.$langs->trans('AmountHT').''.price($object->total_ht).''.$langs->trans('Currency'.$conf->currency).'
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($object->total_localtax1).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($object->total_localtax2).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($object->total_localtax1).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($object->total_localtax2).''.$langs->trans("Currency".$conf->currency).'
'.$langs->trans('AmountTTC').''.price($object->total_ttc).''.$langs->trans('Currency'.$conf->currency).'
'.$langs->trans("WithdrawalReceipt").''.$langs->trans("User").'  
'.$langs->trans("OrderWaiting").''.price($obj->amount).'-'.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.' '; print ''; @@ -565,7 +584,7 @@ if ($object->id > 0) print $withdrawreceipt->getNomUrl(1); print "'.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.''.img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'  
'; print ''; print ""; - print "'; + print "'; print ''; - //print "'; + //print "'; print ''; print "
'.$langs->trans("SearchATripAndExpense").'
".$langs->trans("Ref").'::
".$langs->trans("Other").':
:

"; } @@ -116,8 +120,9 @@ $sql.= " FROM ".MAIN_DB_PREFIX."deplacement as d, ".MAIN_DB_PREFIX."user as u"; if (!$user->rights->societe->client->voir && !$user->societe_id) $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->societe_id) $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; +if (!empty($socid)) $sql.= " AND d.fk_soc = ".$socid; $sql.= $db->order("d.tms","DESC"); $sql.= $db->plimit($max, 0); diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 205aba9a778..2359d70d07b 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -97,9 +97,9 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ""; print ''; - print "'; + print "'; print ''; - print "'; + print "'; print ''; print "
'.$langs->trans("SearchACustomerInvoice").'
".$langs->trans("Ref").':
:
".$langs->trans("Other").':
:

"; } @@ -114,9 +114,9 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) print ''; print ''; print ""; - print "'; + print "'; print ''; - print "'; + print "'; print ''; print "
'.$langs->trans("SearchASupplierInvoice").'
".$langs->trans("Ref").'::
".$langs->trans("RefSupplier").':
:

"; } @@ -127,14 +127,14 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire) if (! empty($conf->don->enabled) && $user->rights->don->lire) { $langs->load("donations"); - print '
'; + print ''; print ''; print ''; print ''; print ""; - print "'; + print "'; print ''; - //print "'; + //print "'; print ''; print "
'.$langs->trans("SearchADonation").'
".$langs->trans("Ref").'::
".$langs->trans("Other").':
:

"; } @@ -145,7 +145,7 @@ if (! empty($conf->don->enabled) && $user->rights->don->lire) if (! empty($conf->facture->enabled) && $user->rights->facture->lire) { $sql = "SELECT f.facnumber, f.rowid, f.total_ttc, f.type,"; - $sql.= " s.nom, s.rowid as socid"; + $sql.= " s.nom as name, s.rowid as socid"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", sc.fk_soc, sc.fk_user "; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -185,7 +185,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print '
'; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'',16); print ''; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'',16); print ''; $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; + $thirdpartystatic->name=$obj->name; $thirdpartystatic->client=1; print $thirdpartystatic->getNomUrl(1,'customer',44); print ''; $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; + $thirdpartystatic->name=$obj->name; $thirdpartystatic->fournisseur=1; print $thirdpartystatic->getNomUrl(1,'supplier',44); print '
'; print ""; - print ''; + print ''; if (! empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; @@ -675,10 +675,10 @@ if (! empty($conf->facture->enabled) && ! empty($conf->commande->enabled) && $us print ''; + print ''; if (! empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; @@ -717,7 +717,7 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) $sql = "SELECT f.rowid, f.facnumber, f.fk_statut, f.datef, f.type, f.total, f.total_ttc, f.paye, f.tms,"; $sql.= " f.date_lim_reglement as datelimite,"; - $sql.= " s.nom, s.rowid as socid,"; + $sql.= " s.nom as name, s.rowid as socid,"; $sql.= " sum(pf.amount) as am"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; @@ -774,10 +774,10 @@ if (! empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; + print ''; if (! empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; print ''; print ''; @@ -821,7 +821,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- $facstatic=new FactureFournisseur($db); $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut, ff.libelle, ff.total_ht, ff.total_ttc, ff.paye,"; - $sql.= " s.nom, s.rowid as socid,"; + $sql.= " s.nom as name, s.rowid as socid,"; $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"; @@ -863,7 +863,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- print $facstatic->getNomUrl(1,''); print ''; $societestatic->id=$obj->socid; - $societestatic->nom=$obj->nom; + $societestatic->name=$obj->name; $societestatic->client=0; print ''; if (! empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; @@ -908,7 +908,7 @@ if ($resql) print '
'.$langs->trans("OrdersToBill").' ('.$num.')'.$langs->trans("OrdersToBill").' ('.$num.')'.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("ToBill").''; $societestatic->id=$obj->socid; - $societestatic->nom=$obj->nom; + $societestatic->name=$obj->name; $societestatic->client=1; print $societestatic->getNomUrl(1,'customer',44); - print ''.price($obj->total_ht).''.price($obj->total_ttc).''.price($obj->total_ttc-$obj->tot_fttc).'' ; $societestatic->id=$obj->socid; - $societestatic->nom=$obj->nom; + $societestatic->name=$obj->name; $societestatic->client=1; print $societestatic->getNomUrl(1,'customer',44); - print ''.price($obj->total).''.price($obj->total_ttc).''.price($obj->am).''.$societestatic->getNomUrl(1, 'supplier', 44).''.price($obj->total_ht).'
'; print ''; print "\n"; - $var = True; + $var = true; $i = 0; while ($i < $db->num_rows($resql)) { @@ -916,7 +916,7 @@ if ($resql) $var=!$var; print ""; - print ""; + print ""; $i++; } $db->free($resql); diff --git a/htdocs/compta/journal/index.html b/htdocs/compta/journal/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index 52562ed0244..34cf525104a 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -1,7 +1,7 @@ * Copyright (C) 2007-2010 Jean Heimburger - * Copyright (C) 2011-2013 Juanjo Menent + * Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2012 Regis Houssin * Copyright (C) 2011-2012 Alexandre spangaro * Copyright (C) 2013 Marcos García @@ -104,11 +104,11 @@ $sql.= " fd.total_ttc, fd.tva_tx, fd.total_ht, fd.tva as total_tva, fd.product_t $sql.= " s.rowid as socid, s.nom as name, s.code_compta_fournisseur,"; $sql.= " p.rowid as pid, p.ref as ref, p.accountancy_code_buy,"; $sql.= " ct.accountancy_code_buy as account_tva, ct.recuperableonly"; -$sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn_det fd"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = fd.fk_product"; -$sql.= " JOIN ".MAIN_DB_PREFIX."facture_fourn f ON f.rowid = fd.fk_facture_fourn"; -$sql.= " JOIN ".MAIN_DB_PREFIX."societe s ON s.rowid = f.fk_soc" ; +$sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as fd"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva as ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product"; +$sql.= " JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = fd.fk_facture_fourn"; +$sql.= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc" ; $sql.= " WHERE f.fk_statut > 0 AND f.entity = ".$conf->entity; if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql.= " AND f.type IN (0,1,2)"; else $sql.= " AND f.type IN (0,1,2,3)"; @@ -117,14 +117,13 @@ if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start // TODO Find a better trick to avoid problem with some mysql installations if (in_array($db->type, array('mysql', 'mysqli'))) $db->query('SET SQL_BIG_SELECTS=1'); -dol_syslog("sql=".$sql); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); // les variables - $cptfour = (! empty($conf->global->COMPTA_ACCOUNT_SUPPLIER)?$conf->global->COMPTA_ACCOUNT_SUPPLIER:$langs->trans("CodeNotDef")); - $cpttva = (! empty($conf->global->COMPTA_VAT_BUY_ACCOUNT)?$conf->global->COMPTA_VAT_BUY_ACCOUNT:$langs->trans("CodeNotDef")); + $cptfour = (! empty($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER)?$conf->global->ACCOUNTING_ACCOUNT_SUPPLIER:$langs->trans("CodeNotDef")); + $cpttva = (! empty($conf->global->ACCOUNTING_VAT_BUY_ACCOUNT)?$conf->global->ACCOUNTING_VAT_BUY_ACCOUNT:$langs->trans("CodeNotDef")); $tabfac = array(); $tabht = array(); @@ -143,16 +142,16 @@ if ($result) $compta_prod = $obj->accountancy_code_buy; if (empty($compta_prod)) { - if($obj->product_type == 0) $compta_prod = (! empty($conf->global->COMPTA_PRODUCT_BUY_ACCOUNT)?$conf->global->COMPTA_PRODUCT_BUY_ACCOUNT:$langs->trans("CodeNotDef")); - else $compta_prod = (! empty($conf->global->COMPTA_SERVICE_BUY_ACCOUNT)?$conf->global->COMPTA_SERVICE_BUY_ACCOUNT:$langs->trans("CodeNotDef")); + if($obj->product_type == 0) $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT)?$conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT:$langs->trans("CodeNotDef")); + else $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT)?$conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT:$langs->trans("CodeNotDef")); } $compta_tva = (! empty($obj->account_tva)?$obj->account_tva:$cpttva); $compta_localtax1 = (! empty($obj->account_localtax1)?$obj->account_localtax1:$langs->trans("CodeNotDef")); $compta_localtax2 = (! empty($obj->account_localtax2)?$obj->account_localtax2:$langs->trans("CodeNotDef")); - $account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $mysoc); + $account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $mysoc, $obj->thirdparty); $compta_localtax1= (! empty($account_localtax1[2])?$account_localtax1[2]:$langs->trans("CodeNotDef")); - $account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $mysoc); + $account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $mysoc, $obj->thirdparty); $compta_localtax2= (! empty($account_localtax2[2])?$account_localtax2[2]:$langs->trans("CodeNotDef")); $tabfac[$obj->rowid]["date"] = $obj->datef; @@ -231,7 +230,6 @@ foreach ($tabfac as $key => $val) if (isset($line['nomtcheck']) || $mt) { print ""; - //print ""; print ""; print ""; print ""; diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index 931b8757470..e249d3fe554 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -1,7 +1,7 @@ * Copyright (C) 2007-2010 Jean Heimburger - * Copyright (C) 2011-2013 Juanjo Menent + * Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2012 Regis Houssin * Copyright (C) 2011-2012 Alexandre Spangaro * Copyright (C) 2013 Marcos García @@ -105,10 +105,10 @@ $sql.= " fd.product_type, fd.total_ht, fd.total_tva, fd.tva_tx, fd.total_ttc, fd $sql.= " s.rowid as socid, s.nom as name, s.code_compta, s.client,"; $sql.= " p.rowid as pid, p.ref as pref, p.accountancy_code_sell,"; $sql.= " ct.accountancy_code_sell as account_tva, ct.recuperableonly"; -$sql.= " FROM ".MAIN_DB_PREFIX."facturedet fd"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = fd.fk_product"; -$sql.= " JOIN ".MAIN_DB_PREFIX."facture f ON f.rowid = fd.fk_facture"; -$sql.= " JOIN ".MAIN_DB_PREFIX."societe s ON s.rowid = f.fk_soc"; +$sql.= " FROM ".MAIN_DB_PREFIX."facturedet as fd"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product"; +$sql.= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture"; +$sql.= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_tva ct ON fd.tva_tx = ct.taux AND fd.info_bits = ct.recuperableonly AND ct.fk_pays = '".$idpays."'"; $sql.= " WHERE f.entity = ".$conf->entity; $sql.= " AND f.fk_statut > 0"; @@ -121,7 +121,6 @@ $sql.= " ORDER BY f.rowid"; // TODO Find a better trick to avoid problem with some mysql installations if (in_array($db->type, array('mysql', 'mysqli'))) $db->query('SET SQL_BIG_SELECTS=1'); -dol_syslog("sql=".$sql); $result = $db->query($sql); if ($result) { @@ -142,20 +141,20 @@ if ($result) { $obj = $db->fetch_object($result); // les variables - $cptcli = (! empty($conf->global->COMPTA_ACCOUNT_CUSTOMER)?$conf->global->COMPTA_ACCOUNT_CUSTOMER:$langs->trans("CodeNotDef")); + $cptcli = (! empty($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER)?$conf->global->ACCOUNTING_ACCOUNT_CUSTOMER:$langs->trans("CodeNotDef")); $compta_soc = (! empty($obj->code_compta)?$obj->code_compta:$cptcli); $compta_prod = $obj->accountancy_code_sell; if (empty($compta_prod)) { - if($obj->product_type == 0) $compta_prod = (! empty($conf->global->COMPTA_PRODUCT_SOLD_ACCOUNT)?$conf->global->COMPTA_PRODUCT_SOLD_ACCOUNT:$langs->trans("CodeNotDef")); - else $compta_prod = (! empty($conf->global->COMPTA_SERVICE_SOLD_ACCOUNT)?$conf->global->COMPTA_SERVICE_SOLD_ACCOUNT:$langs->trans("CodeNotDef")); + if($obj->product_type == 0) $compta_prod = (! empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT)?$conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT:$langs->trans("CodeNotDef")); + else $compta_prod = (! empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT)?$conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT:$langs->trans("CodeNotDef")); } - $cpttva = (! empty($conf->global->COMPTA_VAT_ACCOUNT)?$conf->global->COMPTA_VAT_ACCOUNT:$langs->trans("CodeNotDef")); + $cpttva = (! empty($conf->global->ACCOUNTING_VAT_ACCOUNT)?$conf->global->ACCOUNTING_VAT_ACCOUNT:$langs->trans("CodeNotDef")); $compta_tva = (! empty($obj->account_tva)?$obj->account_tva:$cpttva); - $account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $mysoc); + $account_localtax1=getLocalTaxesFromRate($obj->tva_tx, 1, $obj->thirdparty, $mysoc); $compta_localtax1= (! empty($account_localtax1[3])?$account_localtax1[3]:$langs->trans("CodeNotDef")); - $account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $mysoc); + $account_localtax2=getLocalTaxesFromRate($obj->tva_tx, 2, $obj->thirdparty, $mysoc); $compta_localtax2= (! empty($account_localtax2[3])?$account_localtax2[3]:$langs->trans("CodeNotDef")); //la ligne facture @@ -241,7 +240,6 @@ foreach ($tabfac as $key => $val) if (isset($line['nomtcheck']) || $mt) { print ""; - //print ""; print ""; print ""; print ""; diff --git a/htdocs/compta/localtax/fiche.php b/htdocs/compta/localtax/card.php similarity index 87% rename from htdocs/compta/localtax/fiche.php rename to htdocs/compta/localtax/card.php index c8849ba07f9..1b16064ed9e 100644 --- a/htdocs/compta/localtax/fiche.php +++ b/htdocs/compta/localtax/card.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2011-2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,7 +16,7 @@ */ /** - * \file htdocs/compta/localtax/fiche.php + * \file htdocs/compta/localtax/card.php * \ingroup tax * \brief Page of IRPF payments */ @@ -30,7 +30,7 @@ $langs->load("banks"); $langs->load("bills"); $id=$_REQUEST["id"]; - +$lttype=GETPOST('localTaxType', 'int'); $mesg = ''; // Security check @@ -44,6 +44,11 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); */ //add payment of localtax +if($_POST["cancel"] == $langs->trans("Cancel")){ + header("Location: reglement.php?localTaxType=".$lttype); + exit; +} + if ($_POST["action"] == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) { $localtax = new Localtax($db); @@ -59,12 +64,13 @@ if ($_POST["action"] == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $localtax->datep=$datep; $localtax->amount=$_POST["amount"]; $localtax->label=$_POST["label"]; + $localtax->ltt=$lttype; $ret=$localtax->addPayment($user); if ($ret > 0) { $db->commit(); - header("Location: reglement.php"); + header("Location: reglement.php?localTaxType=".$lttype); exit; } else @@ -143,12 +149,13 @@ if ($id) if ($_GET["action"] == 'create') { - print "
\n"; + print "\n"; print ''; + print ''; print ''; - print_fiche_titre($langs->transcountry("newLT2Payment",$mysoc->country_code)); - + print_fiche_titre($langs->transcountry($lttype==2?"newLT2Payment":"newLT1Payment",$mysoc->country_code)); + if ($mesg) print $mesg; print '
'.$langs->trans("TasksToDo").'
".dol_print_date($obj->da,"day")."$obj->libelle $obj->label
$obj->libelle $obj->label
".$conf->global->COMPTA_JOURNAL_BUY."".dol_print_date($val["date"])."".$invoicestatic->getNomUrl(1)."".$k."".$line['label']."
".$conf->global->COMPTA_JOURNAL_SELL."".dol_print_date($val["date"])."".$invoicestatic->getNomUrl(1)."".$k."".$line['label']."
'; @@ -163,7 +170,7 @@ if ($_GET["action"] == 'create') print ''; // Label - print ''; + print ''; // Amount print ''; @@ -201,7 +208,7 @@ if ($id) if ($mesg) print $mesg; $h = 0; - $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/fiche.php?id='.$vatpayment->id; + $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$vatpayment->id; $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; @@ -252,7 +259,7 @@ if ($id) */ print "
\n"; if ($vatpayment->rappro == 0) - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; else print ''.$langs->trans("Delete").''; print "
"; diff --git a/htdocs/compta/localtax/class/index.html b/htdocs/compta/localtax/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php index b500a701254..e2c9c94595a 100644 --- a/htdocs/compta/localtax/class/localtax.class.php +++ b/htdocs/compta/localtax/class/localtax.class.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2011-2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -31,6 +31,7 @@ class Localtax extends CommonObject { var $id; var $ref; + var $ltt; var $tms; var $datep; var $datev; @@ -74,6 +75,7 @@ class Localtax extends CommonObject // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."localtax("; + $sql.= "localtaxtype,"; $sql.= "tms,"; $sql.= "datep,"; $sql.= "datev,"; @@ -84,6 +86,7 @@ class Localtax extends CommonObject $sql.= "fk_user_creat,"; $sql.= "fk_user_modif"; $sql.= ") VALUES ("; + $sql.= " ".$this->ltt.","; $sql.= " '".$this->db->idate($this->tms)."',"; $sql.= " '".$this->db->idate($this->datep)."',"; $sql.= " '".$this->db->idate($this->datev)."',"; @@ -95,25 +98,24 @@ class Localtax extends CommonObject $sql.= " '".$this->fk_user_modif."'"; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."localtax"); - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LOCALTAX_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LOCALTAX_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + + //FIXME: Add rollback if trigger fail return $this->id; } else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } } @@ -125,7 +127,7 @@ class Localtax extends CommonObject * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -141,6 +143,7 @@ class Localtax extends CommonObject // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."localtax SET"; + $sql.= " localtaxtype=".$this->ltt.","; $sql.= " tms=".$this->db->idate($this->tms).","; $sql.= " datep=".$this->db->idate($this->datep).","; $sql.= " datev=".$this->db->idate($this->datev).","; @@ -152,23 +155,22 @@ class Localtax extends CommonObject $sql.= " fk_user_modif='".$this->fk_user_modif."'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LOCALTAX_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LOCALTAX_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + + //FIXME: Add rollback if trigger fail } return 1; @@ -186,6 +188,7 @@ class Localtax extends CommonObject global $langs; $sql = "SELECT"; $sql.= " t.rowid,"; + $sql.= " t.localtaxtype,"; $sql.= " t.tms,"; $sql.= " t.datep,"; $sql.= " t.datev,"; @@ -202,7 +205,7 @@ class Localtax extends CommonObject $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -212,6 +215,7 @@ class Localtax extends CommonObject $this->id = $obj->rowid; $this->ref = $obj->rowid; + $this->ltt = $obj->localtaxtype; $this->tms = $this->db->jdate($obj->tms); $this->datep = $this->db->jdate($obj->datep); $this->datev = $this->db->jdate($obj->datev); @@ -232,7 +236,6 @@ class Localtax extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -250,24 +253,23 @@ class Localtax extends CommonObject $error=0; + // Call trigger + $result=$this->call_trigger('LOCALTAX_DELETE',$user); + if ($result < 0) return -1; + // End call triggers + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."localtax"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -1; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LOCALTAX_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers return 1; } @@ -285,6 +287,7 @@ class Localtax extends CommonObject $this->id=0; $this->tms=''; + $this->ltt=0; $this->datep=''; $this->datev=''; $this->amount=''; @@ -323,35 +326,32 @@ class Localtax extends CommonObject */ function localtax_sum_collectee($year = 0) { - $sql = "SELECT sum(f.localtax) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) { $sql .= " AND f.datef >= '$year-01-01' AND f.datef <= '$year-12-31' "; } $result = $this->db->query($sql); - if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->amount; + $ret = $obj->amount; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free($result); - } else - { - print $this->db->error(); + { + print $this->db->lasterror(); return -1; } } @@ -367,31 +367,30 @@ class Localtax extends CommonObject $sql = "SELECT sum(f.total_localtax) as total_localtax"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) { $sql .= " WHERE f.datef >= '$year-01-01' AND f.datef <= '$year-12-31' "; } - $result = $this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->total_localtax; + $ret = $obj->total_localtax; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free(); - } else { - print $this->db->error(); + print $this->db->lasterror(); return -1; } } @@ -409,32 +408,30 @@ class Localtax extends CommonObject $sql = "SELECT sum(f.amount) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."localtax as f"; - if ($year) { $sql .= " WHERE f.datev >= '$year-01-01' AND f.datev <= '$year-12-31' "; } $result = $this->db->query($sql); - if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->amount; + $ret = $obj->amount; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free(); - } else { - print $this->db->error(); + print $this->db->lasterror(); return -1; } } @@ -476,19 +473,19 @@ class Localtax extends CommonObject } // Insertion dans table des paiement localtax - $sql = "INSERT INTO ".MAIN_DB_PREFIX."localtax (datep, datev, amount"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."localtax (localtaxtype, datep, datev, amount"; if ($this->note) $sql.=", note"; if ($this->label) $sql.=", label"; $sql.= ", fk_user_creat, fk_bank"; $sql.= ") "; - $sql.= " VALUES ('".$this->db->idate($this->datep)."',"; + $sql.= " VALUES (".$this->ltt.", '".$this->db->idate($this->datep)."',"; $sql.= "'".$this->db->idate($this->datev)."'," . $this->amount; if ($this->note) $sql.=", '".$this->db->escape($this->note)."'"; if ($this->label) $sql.=", '".$this->db->escape($this->label)."'"; $sql.=", '".$user->id."', NULL"; $sql.= ")"; - dol_syslog(get_class($this)."::addPayment sql=".$sql); + dol_syslog(get_class($this)."::addPayment", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -519,7 +516,7 @@ class Localtax extends CommonObject } // Mise a jour liens - $result=$acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/localtax/fiche.php?id=', "(VATPayment)", "payment_vat"); + $result=$acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/localtax/card.php?id=', "(VATPayment)", "payment_vat"); if ($result < 0) { $this->error=$acc->error; @@ -540,14 +537,14 @@ class Localtax extends CommonObject } else { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -2; } } else { - $this->error=$this->db->error(); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } @@ -589,7 +586,7 @@ class Localtax extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='payment'; diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index cc71b402060..7c34cec1ed4 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -1,6 +1,6 @@ - * Copyright (C) 2014 Ferran Marcet +/* Copyright (C) 2011-2014 Juanjo Menent + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,6 +33,8 @@ $langs->load("compta"); $langs->load("companies"); $langs->load("products"); +$local=GETPOST('localTaxType', 'int'); + // Date range $year=GETPOST("year"); if (empty($year)) @@ -102,15 +104,17 @@ $fsearch.=' '; $fsearch.=' '.$langs->trans("SalesTurnoverMinimum").': '; $fsearch.=' '; +$calc=MAIN_INFO_LOCALTAX_CALC.$local; // Affiche en-tete du rapport -if ($modetax==1) // Calculate on invoice for goods and services +if ($conf->global->$calc==0 || $conf->global->$calc==1) // Calculate on invoice for goods and services { - $nom=$langs->transcountry("LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); + $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); + $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT'.$local.'Rec"); + $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); - $description=$langs->trans("RulesVATDue"); if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; - $description.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; + $description.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $builddate=time(); $elementcust=$langs->trans("CustomersInvoices"); @@ -120,14 +124,15 @@ if ($modetax==1) // Calculate on invoice for goods and services $productsup=$langs->trans("Description"); $amountsup=$langs->trans("AmountHT"); } -if ($modetax==0) // Invoice for goods, payment for services +if ($conf->global->$calc==2) // Invoice for goods, payment for services { - $nom=$langs->transcountry("LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); + $nom=$langs->transcountry($local==1?"LT1ReportByCustomersInInputOutputMode":"LT2ReportByCustomersInInputOutputMode",$mysoc->country_code); + $calcmode=$langs->trans("CalcModeLT2Debt"); + $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); - $description=$langs->trans("RulesVATIn"); if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); $description.=$fsearch; - $description.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; + $description.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; $builddate=time(); $elementcust=$langs->trans("CustomersInvoices"); @@ -137,173 +142,180 @@ if ($modetax==0) // Invoice for goods, payment for services $productsup=$langs->trans("Description"); $amountsup=$langs->trans("AmountHT"); } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink); +report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); -$vatcust=$langs->transcountry("LT2",$mysoc->country_code); -$vatsup=$langs->transcountry("LT2",$mysoc->country_code); + +$vatcust=$langs->transcountry($local==1?"LT1":"LT2",$mysoc->country_code); +$vatsup=$langs->transcountry($local==1?"LT1":"LT2",$mysoc->country_code); // IRPF that the customer has retained me - -print "
'.$langs->trans("Label").'transcountry("LT2Payment",$mysoc->country_code)).'">
'.$langs->trans("Label").'transcountry(($lttype==2?"LT2Payment":"LT1Payment"),$mysoc->country_code)).'">
'.$langs->trans("Amount").'
"; -print ""; -print '"; -print '"; -print ""; -print ""; -print ""; -print "\n"; - -$coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'sell'); - -$action = "tvaclient"; -$object = &$coll_list; -$parameters["mode"] = $modetax; -$parameters["start"] = $date_start; -$parameters["end"] = $date_end; -$parameters["direction"] = 'sell'; -// Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('externalbalance')); -$reshook=$hookmanager->executeHooks('addStatisticLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks - -if (is_array($coll_list)) +if($conf->global->$calc ==0 || $conf->global->$calc == 2) { - $var=true; - $total = 0; $totalamount = 0; - $i = 1; - foreach($coll_list as $coll) + print "
'.$langs->trans("Num")."'.$langs->trans("Customer")."".$langs->transcountry("ProfId1",$mysoc->country_code)."".$langs->trans("TotalHT")."".$vatcust."
"; + print ""; + print '"; + print '"; + print ""; + print ""; + print ""; + print "\n"; + + $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'sell'); + + $action = "tvaclient"; + $object = &$coll_list; + $parameters["mode"] = $modetax; + $parameters["start"] = $date_start; + $parameters["end"] = $date_end; + $parameters["direction"] = 'sell'; + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array + $hookmanager->initHooks(array('externalbalance')); + $reshook=$hookmanager->executeHooks('addStatisticLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + + if (is_array($coll_list)) { - if(($min == 0 or ($min > 0 && $coll->amount > $min)) && $coll->localtax2!=0) + $var=true; + $total = 0; $totalamount = 0; + $i = 1; + foreach($coll_list as $coll) { - $var=!$var; - $intra = str_replace($find,$replace,$coll->tva_intra); - if(empty($intra)) + if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) !=0) { - if($coll->assuj == '1') + $var=!$var; + $intra = str_replace($find,$replace,$coll->tva_intra); + if(empty($intra)) { - $intra = $langs->trans('Unknown'); - } - else - { - $intra = ''; + if($coll->assuj == '1') + { + $intra = $langs->trans('Unknown'); + } + else + { + $intra = ''; + } } + print ""; + print '"; + $company_static->id=$coll->socid; + $company_static->name=$coll->name; + print ''; + $find = array(' ','.'); + $replace = array('',''); + print '"; + print ""; + print ""; + $totalamount = $totalamount + $coll->amount; + $total = $total + ($local==1?$coll->localtax1:$coll->localtax2); + print "\n"; + $i++; } - print ""; - print '"; - $company_static->id=$coll->socid; - $company_static->nom=$coll->nom; - print ''; - $find = array(' ','.'); - $replace = array('',''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->localtax2; - print "\n"; - $i++; } - } - $x_coll_sum = $total; + $x_coll_sum = $total; - print ''; - print ''; - print ''; - print ''; -} -else -{ - $langs->load("errors"); - if ($coll_list == -1) - print ''; - else if ($coll_list == -2) - print ''; + print ''; + print ''; + print ''; + print ''; + } else - print ''; + { + $langs->load("errors"); + if ($coll_list == -1) + print ''; + else if ($coll_list == -2) + print ''; + else + print ''; + } } // IRPF I retained my supplier +if($conf->global->$calc ==0 || $conf->global->$calc == 1){ + print "
'.$langs->trans("Num")."'.$langs->trans("Customer")."".$langs->transcountry("ProfId1",$mysoc->country_code)."".$langs->trans("TotalHT")."".$vatcust."
'.$i."'.$company_static->getNomUrl(1).''.$intra."".price($coll->amount)."".price($local==1?$coll->localtax1:$coll->localtax2)."
'.$i."'.$company_static->getNomUrl(1).''.$intra."".price($coll->amount)."".price($coll->localtax2)."
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
'.$langs->trans("Error").'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
"; + print ""; + print '"; + print '"; + print ""; + print ""; + print ""; + print "\n"; -print ""; -print '"; -print '"; -print ""; -print ""; -print ""; -print "\n"; + $company_static=new Societe($db); -$company_static=new Societe($db); - -$coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy'); -$parameters["direction"] = 'buy'; -$reshook=$hookmanager->executeHooks('addStatisticLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -if (is_array($coll_list)) -{ - $var=true; - $total = 0; $totalamount = 0; - $i = 1; - foreach($coll_list as $coll) + $coll_list = vat_by_thirdparty($db,0,$date_start,$date_end,$modetax,'buy'); + $parameters["direction"] = 'buy'; + $reshook=$hookmanager->executeHooks('addStatisticLine',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + if (is_array($coll_list)) { - if(($min == 0 or ($min > 0 && $coll->amount > $min)) && $coll->localtax2!=0) + $var=true; + $total = 0; $totalamount = 0; + $i = 1; + foreach($coll_list as $coll) { - $var=!$var; - $intra = str_replace($find,$replace,$coll->tva_intra); - if(empty($intra)) + if(($min == 0 or ($min > 0 && $coll->amount > $min)) && ($local==1?$coll->localtax1:$coll->localtax2) != 0) { - if($coll->assuj == '1') + $var=!$var; + $intra = str_replace($find,$replace,$coll->tva_intra); + if(empty($intra)) { - $intra = $langs->trans('Unknown'); - } - else - { - $intra = ''; + if($coll->assuj == '1') + { + $intra = $langs->trans('Unknown'); + } + else + { + $intra = ''; + } } + print ""; + print '"; + $company_static->id=$coll->socid; + $company_static->name=$coll->name; + print ''; + $find = array(' ','.'); + $replace = array('',''); + print '"; + print ""; + print ""; + $totalamount = $totalamount + $coll->amount; + $total = $total + ($local==1?$coll->localtax1:$coll->localtax2); + print "\n"; + $i++; } - print ""; - print '"; - $company_static->id=$coll->socid; - $company_static->nom=$coll->nom; - print ''; - $find = array(' ','.'); - $replace = array('',''); - print '"; - print ""; - print ""; - $totalamount = $totalamount + $coll->amount; - $total = $total + $coll->localtax2; - print "\n"; - $i++; } + $x_paye_sum = $total; + + print ''; + print ''; + print ''; + print ''; + + print '
'.$langs->trans("Num")."'.$langs->trans("Supplier")."".$langs->transcountry("ProfId1",$mysoc->country_code)."".$langs->trans("TotalHT")."".$vatsup."
'.$langs->trans("Num")."'.$langs->trans("Supplier")."".$langs->transcountry("ProfId1",$mysoc->country_code)."".$langs->trans("TotalHT")."".$vatsup."
'.$i."'.$company_static->getNomUrl(1).''.$intra."".price($coll->amount)."".price($local==1?$coll->localtax1:$coll->localtax2)."
'.$i."'.$company_static->getNomUrl(1).''.$intra."".price($coll->amount)."".price($coll->localtax2)."
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
'; + } - $x_paye_sum = $total; - - print '
'.$langs->trans("Total").':'.price($totalamount).''.price($total).'
'; - - // Total to pay - print '

'; - print ''; - $diff = $x_paye_sum; - print ''; - print ''; - print '\n"; - print "\n"; - -} -else -{ - $langs->load("errors"); - if ($coll_list == -1) - print ''; - else if ($coll_list == -2) - print ''; else - print ''; + { + $langs->load("errors"); + if ($coll_list == -1) + print ''; + else if ($coll_list == -2) + print ''; + else + print ''; + } } +if($conf->global->$calc ==0){ + // Total to pay + print '

'; + print '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'; + $diff = $x_coll_sum - $x_paye_sum ; + print ''; + print ''; + print '\n"; + print "\n"; + +} print '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index 5a832b7631b..1ee31f5ebbd 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -27,6 +27,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->load("other"); +$localTaxType=GETPOST('localTaxType', 'int'); $year=$_GET["year"]; if ($year == 0 ) @@ -95,24 +96,41 @@ function pt ($db, $sql, $date) llxHeader(); -$tva = new Tva($db); +if($localTaxType==1) +{ + $LT='LT1'; + $LTSummary='LT1Summary'; + $LTPaid='LT1Paid'; + $LTCustomer='LT1Customer'; + $LTSupplier='LT1Supplier'; + $CalcLT= $conf->global->MAIN_INFO_LOCALTAX_CALC1; +} +else +{ + $LT='LT2'; + $LTSummary='LT2Summary'; + $LTPaid='LT2Paid'; + $LTCustomer='LT2Customer'; + $LTSupplier='LT2Supplier'; + $CalcLT= $conf->global->MAIN_INFO_LOCALTAX_CALC2; +} -$textprevyear="".img_previous().""; -$textnextyear=" ".img_next().""; +$textprevyear="".img_previous().""; +$textnextyear=" ".img_next().""; -print_fiche_titre($langs->transcountry("LT2",$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear"); +print_fiche_titre($langs->transcountry($LT,$mysoc->country_code),"$textprevyear ".$langs->trans("Year")." $year_start $textnextyear"); -print $langs->trans("VATReportBuildWithOptionDefinedInModule").'
'; -print '('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')
'; +print $langs->trans("LTReportBuildWithOptionDefinedInModule").'
'; +print '('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')
'; print '
'; print ''; print ''; print ''; $rowspan=5; - if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT)) $rowspan++; // Payment mode print '\n"; - // Payment amount - if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT)) - { - print ''; - print ''; - print ''; - } - // Cheque number print ''; print "\n"; - $var=True; + $var=true; $total=0; $totalrecu=0; $totalrecucreditnote=0; @@ -578,10 +559,8 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie if ($action != 'add_paiement') { - if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT)) - { - print img_picto($langs->trans('AddRemind'),'rightarrow.png','id="'.$objp->facid.'"'); - } + if(!empty($conf->global->FAC_AUTO_FILLJS)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'"); print ''; print ''; } @@ -708,15 +687,15 @@ if (! GETPOST('action')) { $num = $db->num_rows($resql); $i = 0; - $var=True; + $var=true; - print_barre_liste($langs->trans('Payments'), $page, 'paiement.php','',$sortfield,$sortorder,'',$num); + print_barre_liste($langs->trans('Payments'), $page, $_SERVER["PHP_SELF"],'',$sortfield,$sortorder,'',$num); print '
'; -print_titre($langs->transcountry("LT2Summary",$mysoc->country_code)); +print_titre($langs->transcountry($LTSummary,$mysoc->country_code)); print ' '; -print_titre($langs->transcountry("LT2Paid",$mysoc->country_code)); +print_titre($langs->transcountry($LTPaid,$mysoc->country_code)); print '
'; @@ -120,8 +138,20 @@ print '
'; print ""; print ""; print ""; -print ""; -print ""; +if($CalcLT==0) +{ + print ""; + print ""; +} +if($CalcLT==1) +{ + print ""; +} +if($CalcLT==2) +{ + print ""; +} + print ""; print "\n"; print "\n"; @@ -160,24 +190,59 @@ for ($m = 1 ; $m < 13 ; $m++ ) $var=!$var; print ""; print ''; - - $x_coll = 0; - foreach($coll_listsell as $vatrate=>$val) + if($CalcLT==0) { - $x_coll+=$val['localtax2']; - } - $subtotalcoll = $subtotalcoll + $x_coll; - print ""; + $x_coll = 0; + foreach($coll_listsell as $vatrate=>$val) + { + $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2']; + } + $subtotalcoll = $subtotalcoll + $x_coll; + print ""; - $x_paye = 0; - foreach($coll_listbuy as $vatrate=>$val) + $x_paye = 0; + foreach($coll_listbuy as $vatrate=>$val) + { + $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2']; + } + $subtotalpaye = $subtotalpaye + $x_paye; + print ""; + } + elseif($CalcLT==1) { - $x_paye+=$val['localtax2']; + $x_paye = 0; + foreach($coll_listbuy as $vatrate=>$val) + { + $x_paye+=$val[$localTaxType==1?'localtax1':'localtax2']; + } + $subtotalpaye = $subtotalpaye + $x_paye; + print ""; } - $subtotalpaye = $subtotalpaye + $x_paye; - print ""; - - $diff = $x_coll - $x_paye; + elseif($CalcLT==2) + { + $x_coll = 0; + foreach($coll_listsell as $vatrate=>$val) + { + $x_coll+=$val[$localTaxType==1?'localtax1':'localtax2']; + } + $subtotalcoll = $subtotalcoll + $x_coll; + print ""; + + } + + if($CalcLT==0) + { + $diff= $x_coll - $x_paye; + } + elseif($CalcLT==1) + { + $diff= $x_paye; + } + elseif($CalcLT==2) + { + $diff= $x_coll; + } + $total = $total + $diff; $subtotal = $subtotal + $diff; @@ -186,12 +251,26 @@ for ($m = 1 ; $m < 13 ; $m++ ) print "\n"; $i++; - if ($i > 2) { + if ($i > 2) + { print ''; print ''; - print ''; - print ''; - print ''; + if($CalcLT==0) + { + print ''; + print ''; + print ''; + } + elseif($CalcLT==1) + { + print ''; + print ''; + } + elseif($CalcLT==2) + { + print ''; + print ''; + } print ''; $i = 0; $subtotalcoll=0; $subtotalpaye=0; $subtotal=0; @@ -214,6 +293,7 @@ $sql.= " FROM ".MAIN_DB_PREFIX."localtax as f"; $sql.= " WHERE f.entity = ".$conf->entity; $sql.= " AND f.datev >= '".$db->idate(dol_get_first_day($y,1,false))."'"; $sql.= " AND f.datev <= '".$db->idate(dol_get_last_day($y,12,false))."'"; +$sql.= " AND localtaxtype=".$localTaxType; $sql.= " GROUP BY dm ASC"; pt($db, $sql,$langs->trans("Year")." $y"); diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php new file mode 100644 index 00000000000..b1b4aad7722 --- /dev/null +++ b/htdocs/compta/localtax/quadri_detail.php @@ -0,0 +1,668 @@ + + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2006-2007 Yannick Warnier + * Copyright (C) 2014 Rosana Romero + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/compta/tva/quadri_detail.php + * \ingroup tax + * \brief Trimestrial page - detailed version + * TODO Deal with recurrent invoices as well + */ +global $mysoc; + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; + +$langs->load("bills"); +$langs->load("compta"); +$langs->load("companies"); +$langs->load("products"); + +$local=GETPOST('localTaxType', 'int'); +// Date range +$year=GETPOST("year"); +if (empty($year)) +{ + $year_current = strftime("%Y",dol_now()); + $year_start = $year_current; +} else { + $year_current = $year; + $year_start = $year; +} +$date_start=dol_mktime(0,0,0,$_REQUEST["date_startmonth"],$_REQUEST["date_startday"],$_REQUEST["date_startyear"]); +$date_end=dol_mktime(23,59,59,$_REQUEST["date_endmonth"],$_REQUEST["date_endday"],$_REQUEST["date_endyear"]); +// Quarter +if (empty($date_start) || empty($date_end)) // We define date_start and date_end +{ + $q=GETPOST("q"); + if (empty($q)) + { + if (isset($_REQUEST["month"])) { $date_start=dol_get_first_day($year_start,$_REQUEST["month"],false); $date_end=dol_get_last_day($year_start,$_REQUEST["month"],false); } + else + { + $month_current = strftime("%m",dol_now()); + if ($month_current >= 10) $q=4; + elseif ($month_current >= 7) $q=3; + elseif ($month_current >= 4) $q=2; + else $q=1; + } + } + if ($q==1) { $date_start=dol_get_first_day($year_start,1,false); $date_end=dol_get_last_day($year_start,3,false); } + if ($q==2) { $date_start=dol_get_first_day($year_start,4,false); $date_end=dol_get_last_day($year_start,6,false); } + if ($q==3) { $date_start=dol_get_first_day($year_start,7,false); $date_end=dol_get_last_day($year_start,9,false); } + if ($q==4) { $date_start=dol_get_first_day($year_start,10,false); $date_end=dol_get_last_day($year_start,12,false); } +} + +$min = GETPOST("min"); +if (empty($min)) $min = 0; + +// Define modetax (0 or 1) +// 0=normal, 1=option vat for services is on debit +$modetax = $conf->global->TAX_MODE; +if (isset($_REQUEST["modetax"])) $modetax=$_REQUEST["modetax"]; +if (empty($modetax)) $modetax=0; + +// Security check +$socid = GETPOST('socid','int'); +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'tax', '', '', 'charges'); + + + +/* + * View + */ + +$morequerystring=''; +$listofparams=array('date_startmonth','date_startyear','date_startday','date_endmonth','date_endyear','date_endday'); +foreach($listofparams as $param) +{ + if (GETPOST($param)!='') $morequerystring.=($morequerystring?'&':'').$param.'='.GETPOST($param); +} + +llxHeader('','','','',0,0,'','',$morequerystring); + +$form=new Form($db); + +$company_static=new Societe($db); +$invoice_customer=new Facture($db); +$invoice_supplier=new FactureFournisseur($db); +$product_static=new Product($db); +$payment_static=new Paiement($db); +$paymentfourn_static=new PaiementFourn($db); + +//print_fiche_titre($langs->trans("VAT"),""); + +//$fsearch.='
'; +$fsearch.=' '; +$fsearch.=' '; +//$fsearch.=' '.$langs->trans("SalesTurnoverMinimum").': '; +//$fsearch.=' '; + +$calc=MAIN_INFO_LOCALTAX_CALC.$local; +// Affiche en-tete du rapport +if ($conf->global->$calc==0 || $conf->global->$calc==1) // Calculate on invoice for goods and services +{ + $nom=$langs->trans($local==1?"LT1ReportByQuartersInDueDebtMode":"LT2ReportByQuartersInDueDebtMode"); + $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT'.$local.'Rec"); + $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $prevyear=$year_start; $prevquarter=$q; + if ($prevquarter > 1) $prevquarter--; + else { $prevquarter=4; $prevyear--; } + $nextyear=$year_start; $nextquarter=$q; + if ($nextquarter < 4) $nextquarter++; + else { $nextquarter=1; $nextyear++; } + //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); + //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); + //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.='
'.$langs->trans("DepositsAreNotIncluded"); + else $description.='
'.$langs->trans("DepositsAreIncluded"); + $description.=$fsearch; + $builddate=time(); + //$exportlink=$langs->trans("NotYetAvailable"); + + $elementcust=$langs->trans("CustomersInvoices"); + $productcust=$langs->trans("ProductOrService"); + $amountcust=$langs->trans("AmountHT"); + $vatcust=$langs->trans("VATReceived"); + if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; + $elementsup=$langs->trans("SuppliersInvoices"); + $productsup=$langs->trans("ProductOrService"); + $amountsup=$langs->trans("AmountHT"); + $vatsup=$langs->trans("VATPaid"); + if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; +} +if ($conf->global->$calc==2) // Invoice for goods, payment for services +{ + $nom=$langs->trans($local==1?"LT1ReportByQuartersInInputOutputMode":"LT2ReportByQuartersInInputOutputMode"); + $calcmode=$calc==0?$langs->trans("CalcModeLT".$local):$langs->trans("CalcModeLT'.$local.'Rec"); + $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRulesLT",DOL_URL_ROOT.'/admin/company.php').')'; + $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); + $prevyear=$year_start; $prevquarter=$q; + if ($prevquarter > 1) $prevquarter--; + else { $prevquarter=4; $prevyear--; } + $nextyear=$year_start; $nextquarter=$q; + if ($nextquarter < 4) $nextquarter++; + else { $nextquarter=1; $nextyear++; } + //$periodlink=($prevyear?"".img_previous()." ".img_next()."":""); + if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description.=' '.$langs->trans("DepositsAreNotIncluded"); + else $description.=' '.$langs->trans("DepositsAreIncluded"); + //if ($conf->global->MAIN_MODULE_COMPTABILITE || $conf->global->MAIN_MODULE_ACCOUNTING) $description.='
'.img_warning().' '.$langs->trans('OptionVatInfoModuleComptabilite'); + //if (! empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description.='
'.$langs->trans("WarningDepositsNotIncluded"); + $description.=$fsearch; + $builddate=time(); + //$exportlink=$langs->trans("NotYetAvailable"); + + $elementcust=$langs->trans("CustomersInvoices"); + $productcust=$langs->trans("ProductOrService"); + $amountcust=$langs->trans("AmountHT"); + $vatcust=$langs->trans("VATReceived"); + if ($mysoc->tva_assuj) $vatcust.=' ('.$langs->trans("ToPay").')'; + $elementsup=$langs->trans("SuppliersInvoices"); + $productsup=$langs->trans("ProductOrService"); + $amountsup=$langs->trans("AmountHT"); + $vatsup=$langs->trans("VATPaid"); + if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; +} +report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); + + +if($local==1){ + $vatcust=$langs->transcountry("LocalTax1", $mysoc->country_code); + $vatsup=$langs->transcountry("LocalTax1", $mysoc->country_code); +}else{ + $vatcust=$langs->transcountry("LocalTax2", $mysoc->country_code); + $vatsup=$langs->transcountry("LocalTax2", $mysoc->country_code); +} + +// VAT Received and paid + + + +$y = $year_current; +$total = 0; +$i=0; + +// Load arrays of datas +$x_coll= local_by_date($db, 0, 0, $date_start, $date_end, $modetax, 'sell', $local); +//$x_coll = vat_by_date($db, 0, 0, $date_start, $date_end, $modetax, 'sell'); +$x_paye = local_by_date($db, 0, 0, $date_start, $date_end, $modetax, 'buy', $local); + + +echo '
".$langs->trans("Year")." $y".$langs->transcountry("LT2Customer",$mysoc->country_code)."".$langs->transcountry("LT2Supplier",$mysoc->country_code)."".$langs->transcountry($LTCustomer,$mysoc->country_code)."".$langs->transcountry($LTSupplier,$mysoc->country_code)."".$langs->transcountry($LTSupplier,$mysoc->country_code)."".$langs->transcountry($LTCustomer,$mysoc->country_code)."".$langs->trans("TotalToPay")." 
'.dol_print_date(dol_mktime(0,0,0,$m,1,$y),"%b %Y").'".price($x_coll)."".price($x_coll)."".price($x_paye)."".price($x_paye)."".price($x_paye)."".price($x_coll)."
'.$langs->trans("SubTotal").':'.price($subtotalcoll).''.price($subtotalpaye).''.price($subtotal).''.price($subtotalcoll).''.price($subtotalpaye).''.price($subtotal).''.price($subtotalpaye).''.price($subtotal).''.price($subtotalcoll).''.price($subtotal).' 
'; + +if (! is_array($x_coll) || ! is_array($x_paye)) +{ + $langs->load("errors"); + if ($x_coll == -1) + print ''; + else if ($x_coll == -2) + print ''; + else + print ''; +} +else +{ + $x_both = array(); + //now, from these two arrays, get another array with one rate per line + foreach(array_keys($x_coll) as $my_coll_rate) + { + //foreach($x_coll[$my_coll_rate][localtax1_list]){ + $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; + $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; + $x_both[$my_coll_rate]['paye']['totalht'] = 0; + $x_both[$my_coll_rate]['paye']['vat'] = 0; + $x_both[$my_coll_rate]['coll']['links'] = ''; + $x_both[$my_coll_rate]['coll']['detail'] = array(); + foreach($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) + { + $invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; + $invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; + $invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; + $x_both[$my_coll_rate]['coll']['detail'][] = array( + 'id' =>$x_coll[$my_coll_rate]['facid'][$id], + 'descr' =>$x_coll[$my_coll_rate]['descr'][$id], + 'pid' =>$x_coll[$my_coll_rate]['pid'][$id], + 'pref' =>$x_coll[$my_coll_rate]['pref'][$id], + 'ptype' =>$x_coll[$my_coll_rate]['ptype'][$id], + 'payment_id'=>$x_coll[$my_coll_rate]['payment_id'][$id], + 'payment_amount'=>$x_coll[$my_coll_rate]['payment_amount'][$id], + 'ftotal_ttc'=>$x_coll[$my_coll_rate]['ftotal_ttc'][$id], + 'dtotal_ttc'=>$x_coll[$my_coll_rate]['dtotal_ttc'][$id], + 'dtype' =>$x_coll[$my_coll_rate]['dtype'][$id], + 'ddate_start'=>$x_coll[$my_coll_rate]['ddate_start'][$id], + 'ddate_end' =>$x_coll[$my_coll_rate]['ddate_end'][$id], + 'totalht' =>$x_coll[$my_coll_rate]['totalht_list'][$id], + 'localtax1'=> $x_coll[$my_coll_rate]['localtax1_list'][$id], + 'localtax2'=> $x_coll[$my_coll_rate]['localtax2_list'][$id], + 'vat' =>$x_coll[$my_coll_rate]['vat_list'][$id], + 'link' =>$invoice_customer->getNomUrl(1,'',12)); + } + } + // tva paid + foreach(array_keys($x_paye) as $my_paye_rate){ + $x_both[$my_paye_rate]['paye']['totalht'] = $x_paye[$my_paye_rate]['totalht']; + $x_both[$my_paye_rate]['paye']['vat'] = $x_paye[$my_paye_rate]['vat']; + if(!isset($x_both[$my_paye_rate]['coll']['totalht'])){ + $x_both[$my_paye_rate]['coll']['totalht'] = 0; + $x_both[$my_paye_rate]['coll']['vat'] = 0; + } + $x_both[$my_paye_rate]['paye']['links'] = ''; + $x_both[$my_paye_rate]['paye']['detail'] = array(); + + foreach($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) + { + $invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; + $invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; + $invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; + $x_both[$my_paye_rate]['paye']['detail'][] = array( + 'id' =>$x_paye[$my_paye_rate]['facid'][$id], + 'descr' =>$x_paye[$my_paye_rate]['descr'][$id], + 'pid' =>$x_paye[$my_paye_rate]['pid'][$id], + 'pref' =>$x_paye[$my_paye_rate]['pref'][$id], + 'ptype' =>$x_paye[$my_paye_rate]['ptype'][$id], + 'payment_id'=>$x_paye[$my_paye_rate]['payment_id'][$id], + 'payment_amount'=>$x_paye[$my_paye_rate]['payment_amount'][$id], + 'ftotal_ttc'=>price2num($x_paye[$my_paye_rate]['ftotal_ttc'][$id]), + 'dtotal_ttc'=>price2num($x_paye[$my_paye_rate]['dtotal_ttc'][$id]), + 'dtype' =>$x_paye[$my_paye_rate]['dtype'][$id], + 'ddate_start'=>$x_paye[$my_paye_rate]['ddate_start'][$id], + 'ddate_end' =>$x_paye[$my_paye_rate]['ddate_end'][$id], + 'totalht' =>price2num($x_paye[$my_paye_rate]['totalht_list'][$id]), + 'localtax1'=> $x_paye[$my_paye_rate]['localtax1_list'][$id], + 'localtax2'=> $x_paye[$my_paye_rate]['localtax2_list'][$id], + 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], + 'link' =>$invoice_supplier->getNomUrl(1,'',12)); + } + } + //now we have an array (x_both) indexed by rates for coll and paye + + + //print table headers for this quadri - incomes first + + $x_coll_sum = 0; + $x_coll_ht = 0; + $x_paye_sum = 0; + $x_paye_ht = 0; + + $span=3; + if ($modetax == 0) $span+=2; + + //print ''; + + if($conf->global->$calc ==0 || $conf->global->$calc == 2){ + // Customers invoices + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; + + + $LT=0; + $sameLT=false; + foreach(array_keys($x_coll) as $rate) + { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; + + if (is_array($x_both[$rate]['coll']['detail'])) + { + // VAT Rate + $var=true; + + if($rate!=0){ + print ""; + //print ''; + /**/ + print ''; + print ''."\n"; + } + foreach($x_both[$rate]['coll']['detail'] as $index => $fields) + { + if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){ + // Define type + $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (! empty($fields['ddate_start'])) $type=1; + if (! empty($fields['ddate_end'])) $type=1; + + $var=!$var; + print ''; + + // Ref + print ''; + + // Description + print ''; + + // Total HT + if ($modetax == 0) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax == 0) + { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + print ''; + } + + // Total collected + print ''; + + // Localtax + print ''; + print ''; + + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; + } + } + } + if($rate!=0){ + // Total customers for this vat rate + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + } + + if (count($x_coll) == 0) // Show a total ine if nothing shown + { + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + + // Blank line + print ''; + print '
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'..')
'.$elementcust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("BI").''.$vatcust.'
'.$langs->trans("Rate").': '.vatrate($rate).'%'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].''; + if ($fields['pid']) + { + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['ptype']; + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + } + else + { + if ($type) $text = img_object($langs->trans('Service'),'service'); + else $text = img_object($langs->trans('Product'),'product'); + if (preg_match('/^\((.*)\)$/',$fields['descr'],$reg)) + { + if ($reg[1]=='DEPOSIT') $fields['descr']=$langs->transnoentitiesnoconv('Deposit'); + elseif ($reg[1]=='CREDIT_NOTE') $fields['descr']=$langs->transnoentitiesnoconv('CreditNote'); + else $fields['descr']=$langs->transnoentitiesnoconv($reg[1]); + } + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); + } + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $payment_static->id=$fields['payment_id']; + print $payment_static->getNomUrl(2); + } + if ($type == 0) + { + print $langs->trans("NotUsedForGoods"); + } + else { + print $fields['payment_amount']; + if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + print ''; + $temp_ht=$fields['totalht']; + if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT')); + print ''; + $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2']; + print price(price2num($temp_vat,'MT')); + //print price($fields['vat']); + print '
'.$langs->trans("Total").':  '.price(price2num($subtot_coll_total_ht,'MT')).''.price(price2num($subtot_coll_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
 
'; + $diff=$x_coll_sum; + } + + if($conf->global->$calc ==0 || $conf->global->$calc == 1){ + echo ''; + //print table headers for this quadri - expenses now + //imprime les en-tete de tables pour ce quadri - maintenant les d�penses + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''."\n"; + + foreach(array_keys($x_paye) as $rate) + { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; + + if(is_array($x_both[$rate]['paye']['detail'])) + { + $var=true; + if($rate!=0){ + print ""; + print ''; + print ''."\n"; + } + foreach($x_both[$rate]['paye']['detail'] as $index=>$fields) + { + if(($local==1 && $fields['localtax1']!=0) || ($local==2 && $fields['localtax2']!=0)){ + // Define type + $type=($fields['dtype']?$fields['dtype']:$fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (! empty($fields['ddate_start'])) $type=1; + if (! empty($fields['ddate_end'])) $type=1; + + $var=!$var; + print ''; + + // Ref + print ''; + + // Description + print ''; + + // Total HT + if ($modetax == 0) + { + print ''; + } + + // Payment + $ratiopaymentinvoice=1; + if ($modetax == 0) + { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice=($fields['payment_amount']/$fields['ftotal_ttc']); + print ''; + } + + // VAT paid + print ''; + + // Localtax + print ''; + print ''; + + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + } + if($rate!=0){ + // Total suppliers for this vat rate + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + } + + if (count($x_paye) == 0) // Show a total ine if nothing shown + { + print ''; + print ''; + print ''; + if ($modetax == 0) + { + print ''; + print ''; + } + print ''; + print ''; + print ''; + } + + print '
'.$elementsup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("BI").''.$vatsup.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'.$fields['link'].''; + if ($fields['pid']) + { + $product_static->id=$fields['pid']; + $product_static->ref=$fields['pref']; + $product_static->type=$fields['ptype']; + print $product_static->getNomUrl(1); + if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + } + else + { + if ($type) $text = img_object($langs->trans('Service'),'service'); + else $text = img_object($langs->trans('Product'),'product'); + print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']),16); + + // Show range + print_date_range($fields['ddate_start'],$fields['ddate_end']); + } + print ''; + print price($fields['totalht']); + if (price2num($fields['ftotal_ttc'])) + { + //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; + $ratiolineinvoice=($fields['dtotal_ttc']/$fields['ftotal_ttc']); + //print ' ('.round($ratiolineinvoice*100,2).'%)'; + } + print ''; + if ($fields['payment_amount'] && $fields['ftotal_ttc']) + { + $paymentfourn_static->id=$fields['payment_id']; + print $paymentfourn_static->getNomUrl(2); + } + if ($type == 0) + { + print $langs->trans("NotUsedForGoods"); + } + else + { + print $fields['payment_amount']; + if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice*100,2).'%)'; + } + print ''; + $temp_ht=$fields['totalht']; + if ($type == 1) $temp_ht=$fields['totalht']*$ratiopaymentinvoice; + print price(price2num($temp_ht,'MT')); + print ''; + $temp_vat= $local==1?$fields['localtax1']:$fields['localtax2']; + print price(price2num($temp_vat,'MT')); + //print price($fields['vat']); + print '
 '.$langs->trans("Total").':  '.price(price2num($subtot_paye_total_ht,'MT')).''.price(price2num($subtot_paye_vat,'MT')).'
 '.$langs->trans("Total").':  '.price(price2num(0,'MT')).''.price(price2num(0,'MT')).'
'; + $diff=$x_paye_sum; + } + + if($conf->global->$calc ==0){$diff=$x_coll_sum - $x_paye_sum;} + echo ''; + // Total to pay + print '

'; + print '
'; + //$diff = $local==1?$x_coll_sum:$x_paye_sum; + print ''; + print ''; + print '\n"; + print "\n"; + + echo '
'.$langs->trans("TotalToPay").($q?', '.$langs->trans("Quadri").' '.$q:'').''.price(price2num($diff,'MT'))."
'; + + $i++; +} + +$db->close(); + +llxFooter(); diff --git a/htdocs/compta/localtax/reglement.php b/htdocs/compta/localtax/reglement.php index 00199dba36f..6d8c1bc7a9c 100644 --- a/htdocs/compta/localtax/reglement.php +++ b/htdocs/compta/localtax/reglement.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2011-2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -31,6 +31,7 @@ $langs->load("compta"); $socid = isset($_GET["socid"])?$_GET["socid"]:''; if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); +$ltt=$_REQUEST["localTaxType"]; /* * View @@ -40,11 +41,11 @@ llxHeader(); $localtax_static = new Localtax($db); -print_fiche_titre($langs->transcountry("LT2Payments",$mysoc->country_code)); +print_fiche_titre($langs->transcountry($ltt==2?"LT2Payments":"LT1Payments",$mysoc->country_code)); $sql = "SELECT rowid, amount, label, f.datev as dm"; $sql.= " FROM ".MAIN_DB_PREFIX."localtax as f "; -$sql.= " WHERE f.entity = ".$conf->entity; +$sql.= " WHERE f.entity = ".$conf->entity." AND localtaxtype=".$ltt; $sql.= " ORDER BY dm DESC"; $result = $db->query($sql); diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 3aafa1c165b..56278f15c5d 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -4,6 +4,7 @@ * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> * * 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 @@ -66,14 +67,17 @@ if ($facid > 0) } // Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('paiementcard')); +$hookmanager->initHooks(array('paiementcard','globalcard')); $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + /* * Actions */ + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes')) { $error = 0; @@ -236,7 +240,7 @@ if ($action == 'confirm_paiement' && $confirm == 'yes') } } if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/compta/paiement/fiche.php?id='.$paiement_id; + else $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id; header('Location: '.$loc); exit; } @@ -374,19 +378,15 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie }); '; - // Add user helper to input amount on invoices - if (! empty($conf->global->MAIN_JS_ON_PAYMENT) && $facture->type != 2) - { - print ' $("#payment_form").find("img").click(function() { - callForResult(jQuery(this).attr("id")); - }); - - $("#amountpayment").change(function() { - callForResult(); - });'; - } - print ' });'."\n"; + if(!empty($conf->global->FAC_AUTO_FILLJS)){ + //Add js for AutoFill + print ' $(document).ready(function () {'; + print ' $(".AutoFillAmout").on(\'click touchstart\', function(){ + $("input[name="+$(this).data(\'rowname\')+"]").val($(this).data("value")).trigger("change"); + });'; + print ' });'."\n"; + } print ' '."\n"; } @@ -412,7 +412,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '
'.$langs->trans('Comments').'
'.$langs->trans('PaymentMode').''; @@ -438,24 +437,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } print "
'.$langs->trans('AmountPayment').''; - if ($action == 'add_paiement') - { - print ''; - print ''; - } - else - { - print ''; - } - print '
'.$langs->trans('Numero'); print ' ('.$langs->trans("ChequeOrTransferNumber").')'; @@ -528,7 +509,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ' 
'; print ''; - print_liste_field_titre($langs->trans('Invoice'),'paiement.php','facnumber','','','',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Date'),'paiement.php','dp','','','',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Type'),'paiement.php','libelle','','','',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Amount'),'paiement.php','fa_amount','','','align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Invoice'),$_SERVER["PHP_SELF"],'facnumber','','','',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Date'),$_SERVER["PHP_SELF"],'dp','','','',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Type'),$_SERVER["PHP_SELF"],'libelle','','','',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Amount'),$_SERVER["PHP_SELF"],'fa_amount','','','align="right"',$sortfield,$sortorder); print ''; print "\n"; diff --git a/htdocs/compta/paiement/avalider.php b/htdocs/compta/paiement/avalider.php index 70e7507b96e..1afdf0e2c80 100644 --- a/htdocs/compta/paiement/avalider.php +++ b/htdocs/compta/paiement/avalider.php @@ -80,14 +80,14 @@ if ($resql) $i = 0; $var=True; - print_barre_liste($langs->trans("ReceivedCustomersPaymentsToValid"), $page, "avalider.php","",$sortfield,$sortorder,'',$num); + print_barre_liste($langs->trans("ReceivedCustomersPaymentsToValid"), $page, $_SERVER["PHP_SELF"],"",$sortfield,$sortorder,'',$num); print '
 
'; print ''; - print_liste_field_titre($langs->trans("Ref"),"avalider.php","p.rowid","","",'width="60"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Date"),"avalider.php","dp","","",'width="80" align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Type"),"avalider.php","c.libelle","","","",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("AmountTTC"),"avalider.php","c.libelle","","",'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"p.rowid","","",'width="60"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"dp","","",'width="80" align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"c.libelle","","","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"c.libelle","","",'align="right"',$sortfield,$sortorder); print ""; print "\n"; @@ -96,7 +96,7 @@ if ($resql) $objp = $db->fetch_object($resql); $var=!$var; print ""; - print ''; + print ''; print '\n"; print "\n"; print ''; @@ -104,7 +104,7 @@ if ($resql) if ($objp->statut == 0) { - print ''.$langs->trans("PaymentStatusToValidShort").''; + print ''.$langs->trans("PaymentStatusToValidShort").''; } else { diff --git a/htdocs/compta/paiement/fiche.php b/htdocs/compta/paiement/card.php similarity index 91% rename from htdocs/compta/paiement/fiche.php rename to htdocs/compta/paiement/card.php index 97f3fb9d47c..d0e15307be5 100644 --- a/htdocs/compta/paiement/fiche.php +++ b/htdocs/compta/paiement/card.php @@ -20,10 +20,10 @@ */ /** - * \file htdocs/compta/paiement/fiche.php + * \file htdocs/compta/paiement/card.php * \ingroup facture * \brief Page of a customer payment - * \remarks Nearly same file than fournisseur/paiement/fiche.php + * \remarks Nearly same file than fournisseur/paiement/card.php */ require '../../main.inc.php'; @@ -45,8 +45,6 @@ if ($user->societe_id) $socid=$user->societe_id; // TODO ajouter regle pour restreindre acces paiement //$result = restrictedArea($user, 'facture', $id,''); -$mesg=''; - $object = new Paiement($db); @@ -67,7 +65,7 @@ if ($action == 'setnote' && $user->rights->facture->paiement) } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); $db->rollback(); } } @@ -81,13 +79,13 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->facture-> if ($result > 0) { $db->commit(); - header("Location: liste.php"); + header("Location: list.php"); exit; } else { $langs->load("errors"); - $mesg='
'.$langs->trans($object->error).'
'; + setEventMessage($langs->trans($object->error), 'errors'); $db->rollback(); } } @@ -114,7 +112,9 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->facture-> $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($_REQUEST['lang_id']); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) facture_pdf_create($db, $fac, $fac->modelpdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $fac->generateDocument($fac->modelpdf, $outputlangs); + } } header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); @@ -123,7 +123,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->facture-> else { $langs->load("errors"); - $mesg='
'.$langs->trans($object->error).'
'; + setEventMessage($langs->trans($object->error), 'errors'); $db->rollback(); } } @@ -134,11 +134,11 @@ if ($action == 'setnum_paiement' && ! empty($_POST['num_paiement'])) $res = $object->update_num($_POST['num_paiement']); if ($res === 0) { - $mesg = '
'.$langs->trans('PaymentNumberUpdateSucceeded').'
'; + setEventMessage($langs->trans('PaymentNumberUpdateSucceeded')); } else { - $mesg = '
'.$langs->trans('PaymentNumberUpdateFailed').'
'; + setEventMessage($langs->trans('PaymentNumberUpdateFailed'), 'errors'); } } @@ -149,11 +149,11 @@ if ($action == 'setdatep' && ! empty($_POST['datepday'])) $res = $object->update_date($datepaye); if ($res === 0) { - $mesg = '
'.$langs->trans('PaymentDateUpdateSucceeded').'
'; + setEventMessage($langs->trans('PaymentDateUpdateSucceeded')); } else { - $mesg = '
'.$langs->trans('PaymentDateUpdateFailed').'
'; + setEventMessage($langs->trans('PaymentDateUpdateFailed'), 'errors'); } } @@ -198,10 +198,6 @@ if ($action == 'valide') } - -dol_htmloutput_mesg($mesg); - - print '
 
'.img_object($langs->trans("ShowPayment"),"payment").' '.$objp->rowid.''.img_object($langs->trans("ShowPayment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."$objp->paiement_type $objp->num_paiement'.price($objp->amount).'
'; // Ref @@ -277,7 +273,7 @@ print '
'; */ $disable_delete = 0; -$sql = 'SELECT f.rowid as facid, f.facnumber, f.type, f.total_ttc, f.paye, f.fk_statut, pf.amount, s.nom, s.rowid as socid'; +$sql = 'SELECT f.rowid as facid, f.facnumber, f.type, f.total_ttc, f.paye, f.fk_statut, pf.amount, s.nom as name, s.rowid as socid'; $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf,'.MAIN_DB_PREFIX.'facture as f,'.MAIN_DB_PREFIX.'societe as s'; $sql.= ' WHERE pf.fk_facture = f.rowid'; $sql.= ' AND f.fk_soc = s.rowid'; @@ -326,7 +322,7 @@ if ($resql) // Third party print '
'; $thirdpartystatic->id=$objp->socid; - $thirdpartystatic->nom=$objp->nom; + $thirdpartystatic->name=$objp->name; print $thirdpartystatic->getNomUrl(1); print '
'.$langs->trans("BankChecksToReceipt").''; - print ''.$num.''; + print ''.$num.''; print '
\n"; } @@ -90,6 +92,7 @@ else //print '
'; print '
'; +$max=10; $sql = "SELECT bc.rowid, bc.date_bordereau as db, bc.amount, bc.number as ref"; $sql.= ", bc.statut, bc.nbcheque"; @@ -98,8 +101,8 @@ $sql.= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc"; $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql.= " WHERE ba.rowid = bc.fk_bank_account"; $sql.= " AND bc.entity = ".$conf->entity; -$sql.= " ORDER BY bc.rowid"; -$sql.= " DESC LIMIT 10"; +$sql.= " ORDER BY bc.date_bordereau DESC, rowid DESC"; +$sql.= $db->plimit($max); $resql = $db->query($sql); @@ -107,7 +110,7 @@ if ($resql) { print ''; print ''; - print ''; + print ''; print '"; print ''; print ''; diff --git a/htdocs/compta/paiement/cheque/list.php b/htdocs/compta/paiement/cheque/list.php new file mode 100644 index 00000000000..fdfe86ec178 --- /dev/null +++ b/htdocs/compta/paiement/cheque/list.php @@ -0,0 +1,197 @@ + + * Copyright (C) 2007-2009 Laurent Destailleur + * Copyright (C) 2009-2012 Regis Houssin + * Copyright (C) 2014 Alexandre Spangaro + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/compta/paiement/cheque/list.php + * \ingroup compta + * \brief Page list of cheque deposits + */ + +require('../../../main.inc.php'); +require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + +$langs->load("banks"); +$langs->load("categories"); +$langs->load("bills"); + +// Security check +if ($user->societe_id) $socid=$user->societe_id; +$result = restrictedArea($user, 'banque', '',''); + +$search_ref = GETPOST('search_ref','int'); +$search_account = GETPOST('search_account','int'); +$search_amount = GETPOST('search_amount','alpha'); +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +$limit = $conf->liste_limit; +if (! $sortorder) $sortorder="DESC"; +if (! $sortfield) $sortfield="dp"; + +$year=GETPOST("year"); +$month=GETPOST("month"); + +$form=new Form($db); +$formother = new FormOther($db); +$checkdepositstatic=new RemiseCheque($db); +$accountstatic=new Account($db); + +// If click on purge search criteria ? +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=''; + $search_amount=''; + $search_account=''; + $year=''; + $month=''; +} + +/* + * View + */ + +llxHeader('',$langs->trans("ChequesReceipts")); + +$sql = "SELECT bc.rowid, bc.number as ref, bc.date_bordereau as dp,"; +$sql.= " bc.nbcheque, bc.amount, bc.statut,"; +$sql.= " ba.rowid as bid, ba.label"; +$sql.= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc,"; +$sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; +$sql.= " WHERE bc.fk_bank_account = ba.rowid"; +$sql.= " AND bc.entity = ".$conf->entity; + +// Search criteria +if ($search_ref) $sql.=" AND bc.number=".$search_ref; +if ($search_account > 0) $sql.=" AND bc.fk_bank_account=".$search_account; +if ($search_amount) $sql.=" AND bc.amount='".$db->escape(price2num(trim($search_amount)))."'"; +if ($month > 0) +{ + if ($year > 0 && empty($day)) + $sql.= " AND bc.date_bordereau BETWEEN '".$db->idate(dol_get_first_day($year,$month,false))."' AND '".$db->idate(dol_get_last_day($year,$month,false))."'"; + else if ($year > 0 && ! empty($day)) + $sql.= " AND bc.date_bordereau BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year))."' AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year))."'"; + else + $sql.= " AND date_format(bc.date_bordereau, '%m') = '".$month."'"; +} +else if ($year > 0) +{ + $sql.= " AND bc.date_bordereau BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; +} + +$sql.= " ORDER BY $sortfield $sortorder"; +$sql.= $db->plimit($limit+1, $offset); +//print "$sql"; + +$resql = $db->query($sql); + +if ($resql) +{ + $num = $db->num_rows($resql); + $i = 0; + $params=''; + + print_barre_liste($langs->trans("MenuChequeDeposits"), $page, $_SERVER["PHP_SELF"], $params, $sortfield, $sortorder, '', $num); + + print ''; + print '
'.$langs->trans("CheckReceiptShort").''.$langs->trans("LastCheckReceiptShort",$max).''.$langs->trans("Date")."'.$langs->trans("Account").''.$langs->trans("NbOfCheques").'
'; + print ''; + print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"bc.number","",$params,"",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"dp","",$params,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Account"),$_SERVER["PHP_SELF"],"ba.label","",$params,"",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("NbOfCheques"),$_SERVER["PHP_SELF"],"bc.nbcheque","",$params,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Amount"),$_SERVER["PHP_SELF"],"bc.amount","",$params,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"bc.statut","",$params,'align="right"',$sortfield,$sortorder); + print "\n"; + + // Lignes des champs de filtre + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '\n"; + + $var=true; + while ($i < min($num,$limit)) + { + $objp = $db->fetch_object($resql); + $var=!$var; + print ""; + + // Num ref cheque + print ''; + + // Date + print ''; + + // Bank + print ''; + + // Number of cheques + print ''; + + // Amount + print ''; + + // Statut + print '\n"; + $i++; + } + print "
'; + print ''; + print ''; + if (! empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($year?$year:-1,'year',1, 20, 5); + print ''; + $form->select_comptes($search_account,'search_account',0,'',1); + print ' '; + print ''; + print ''; + print ''; + print "
'; + $checkdepositstatic->id=$objp->rowid; + $checkdepositstatic->ref=($objp->ref?$objp->ref:$objp->rowid); + $checkdepositstatic->statut=$objp->statut; + print $checkdepositstatic->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->dp),'day').''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; + else print ' '; + print ''.$objp->nbcheque.''.price($objp->amount).''; + print $checkdepositstatic->LibStatut($objp->statut,5); + print "
"; + print "\n"; +} +else +{ + dol_print_error($db); +} + +$db->close(); + +llxFooter(); diff --git a/htdocs/compta/paiement/cheque/liste.php b/htdocs/compta/paiement/cheque/liste.php deleted file mode 100644 index 474b4531295..00000000000 --- a/htdocs/compta/paiement/cheque/liste.php +++ /dev/null @@ -1,155 +0,0 @@ - - * Copyright (C) 2007-2009 Laurent Destailleur - * Copyright (C) 2009-2012 Regis Houssin - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/compta/paiement/cheque/liste.php - * \ingroup compta - * \brief Page liste des bordereau de remise de cheque - */ - -require('../../../main.inc.php'); -require_once DOL_DOCUMENT_ROOT.'/compta/paiement/cheque/class/remisecheque.class.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - -$langs->load("banks"); -$langs->load("categories"); -$langs->load("bills"); - -// Security check -if ($user->societe_id) $socid=$user->societe_id; -$result = restrictedArea($user, 'banque', '',''); - -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); -$page = GETPOST("page",'int'); -if ($page == -1) { $page = 0; } -$offset = $conf->liste_limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; -$limit = $conf->liste_limit; -if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) $sortfield="bc.number"; - -$checkdepositstatic=new RemiseCheque($db); -$accountstatic=new Account($db); - - -/* - * View - */ - -llxHeader('',$langs->trans("ChequesReceipts")); - -$sql = "SELECT bc.rowid, bc.number as ref, bc.date_bordereau as dp,"; -$sql.= " bc.nbcheque, bc.amount, bc.statut,"; -$sql.= " ba.rowid as bid, ba.label"; -$sql.= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc,"; -$sql.= " ".MAIN_DB_PREFIX."bank_account as ba"; -$sql.= " WHERE bc.fk_bank_account = ba.rowid"; -$sql.= " AND bc.entity = ".$conf->entity; -if (GETPOST('search_montant')) -{ - $sql.=" AND bc.amount=".price2num(GETPOST('search_montant')); -} -$sql.= " ORDER BY $sortfield $sortorder"; -$sql.= $db->plimit($limit+1, $offset); -//print "$sql"; - -$resql = $db->query($sql); - -if ($resql) -{ - $num = $db->num_rows($resql); - $i = 0; - $params=''; - - print_barre_liste($langs->trans("MenuChequeDeposits"), $page, 'liste.php', $params, $sortfield, $sortorder, '', $num); - - print '
'; - print ''; - print ''; - print_liste_field_titre($langs->trans("Ref"),"liste.php","bc.number","",$params,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Date"),"liste.php","dp","",$params,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Account"),"liste.php","ba.label","",$params,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("NbOfCheques"),"liste.php","bc.nbcheque","",$params,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Amount"),"liste.php","bc.amount","",$params,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Status"),"liste.php","bc.statut","",$params,'align="right"',$sortfield,$sortorder); - print "\n"; - - // Lignes des champs de filtre - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - $var=true; - while ($i < min($num,$limit)) - { - $objp = $db->fetch_object($resql); - $var=!$var; - print ""; - - // Num ref cheque - print ''; - - // Date - print ''; - - // Banque - print ''; - - // Nb of cheques - print ''; - - // Montant - print ''; - - // Statut - print '\n"; - $i++; - } - print "
    '; - print ''; - print ''; - print ''; - print '
'; - $checkdepositstatic->id=$objp->rowid; - $checkdepositstatic->ref=($objp->ref?$objp->ref:$objp->rowid); - $checkdepositstatic->statut=$objp->statut; - print $checkdepositstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp),'day').''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"),'account').' '.$objp->label.''; - else print ' '; - print ''.$objp->nbcheque.''.price($objp->amount).''; - print $checkdepositstatic->LibStatut($objp->statut,5); - print "
"; - print "
\n"; -} -else -{ - dol_print_error($db); -} - -$db->close(); - -llxFooter(); diff --git a/htdocs/compta/paiement/class/index.html b/htdocs/compta/paiement/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index 0eea10bf510..95503db6ff9 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -81,7 +81,7 @@ class Paiement extends CommonObject $sql.= ' WHERE p.fk_paiement = c.id'; $sql.= ' AND p.rowid = '.$id; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) @@ -161,7 +161,7 @@ class Paiement extends CommonObject $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement (entity, datec, datep, amount, fk_paiement, num_paiement, note, fk_user_creat)"; $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', '".$this->db->idate($this->datepaye)."', '".$totalamount."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.")"; - dol_syslog(get_class($this)."::Create insert paiement sql=".$sql); + dol_syslog(get_class($this)."::Create insert paiement", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -177,7 +177,7 @@ class Paiement extends CommonObject $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiement_facture (fk_facture, fk_paiement, amount)'; $sql .= ' VALUES ('.$facid.', '. $this->id.', \''.$amount.'\')'; - dol_syslog(get_class($this).'::Create Amount line '.$key.' insert paiement_facture sql='.$sql); + dol_syslog(get_class($this).'::Create Amount line '.$key.' insert paiement_facture', LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -221,7 +221,7 @@ class Paiement extends CommonObject if (!in_array($invoice->type, $affected_types)) dol_syslog("Invoice ".$facid." is not a standard, nor replacement invoice, nor credit note, nor deposit invoice. We do nothing more."); else if ($remaintopay) dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing more."); else if ($mustwait) dol_syslog("There is ".$mustwait." differed payment to process, we do nothing more."); - else + else { $result=$invoice->set_paid($user,'',''); if ($result<0) @@ -235,7 +235,6 @@ class Paiement extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this).'::Create insert paiement_facture error='.$this->error, LOG_ERR); $error++; } } @@ -248,17 +247,14 @@ class Paiement extends CommonObject if (! $error) { // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_CUSTOMER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } + $result=$this->call_trigger('PAYMENT_CUSTOMER_CREATE', $user); + if ($result < 0) { $error++; } // Fin appel triggers } } else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this).'::Create insert paiement error='.$this->error, LOG_ERR); $error++; } @@ -363,11 +359,13 @@ class Paiement extends CommonObject if (! $notrigger) { // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + $result=$this->call_trigger('PAYMENT_DELETE', $user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // Fin appel triggers } $this->db->commit(); @@ -455,8 +453,8 @@ class Paiement extends CommonObject if ( ! $error) { $url=''; - if ($mode == 'payment') $url=DOL_URL_ROOT.'/compta/paiement/fiche.php?id='; - if ($mode == 'payment_supplier') $url=DOL_URL_ROOT.'/fourn/paiement/fiche.php?id='; + 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); @@ -484,8 +482,8 @@ class Paiement extends CommonObject $result=$acc->add_url_line( $bank_line_id, $fac->thirdparty->id, - DOL_URL_ROOT.'/comm/fiche.php?socid=', - $fac->thirdparty->nom, + DOL_URL_ROOT.'/comm/card.php?socid=', + $fac->thirdparty->name, 'company' ); if ($result <= 0) dol_print_error($this->db); @@ -502,8 +500,8 @@ class Paiement extends CommonObject $result=$acc->add_url_line( $bank_line_id, $fac->thirdparty->id, - DOL_URL_ROOT.'/fourn/fiche.php?socid=', - $fac->thirdparty->nom, + DOL_URL_ROOT.'/fourn/card.php?socid=', + $fac->thirdparty->name, 'company' ); if ($result <= 0) dol_print_error($this->db); @@ -516,11 +514,9 @@ class Paiement extends CommonObject if (! $error && ! $notrigger) { // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_ADD_TO_BANK',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + $result=$this->call_trigger('PAYMENT_ADD_TO_BANK', $user); + if ($result < 0) { $error++; } + // Fin appel triggers } } else @@ -561,7 +557,7 @@ class Paiement extends CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' set fk_bank = '.$id_bank; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this).'::update_fk_bank sql='.$sql); + dol_syslog(get_class($this).'::update_fk_bank', LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -589,7 +585,7 @@ class Paiement extends CommonObject $sql.= " SET datep = '".$this->db->idate($date)."'"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_date sql=".$sql); + dol_syslog(get_class($this)."::update_date", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -600,7 +596,6 @@ class Paiement extends CommonObject else { $this->error='Error -1 '.$this->db->error(); - dol_syslog(get_class($this)."::update_date ".$this->error, LOG_ERR); return -2; } } @@ -621,7 +616,7 @@ class Paiement extends CommonObject $sql.= " SET num_paiement = '".$this->db->escape($num)."'"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_num sql=".$sql); + dol_syslog(get_class($this)."::update_num", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -631,7 +626,6 @@ class Paiement extends CommonObject else { $this->error='Error -1 '.$this->db->error(); - dol_syslog(get_class($this)."::update_num ".$this->error, LOG_ERR); return -2; } } @@ -647,7 +641,7 @@ class Paiement extends CommonObject { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET statut = 1 WHERE rowid = '.$this->id; - dol_syslog(get_class($this).'::valide sql='.$sql); + dol_syslog(get_class($this).'::valide', LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -671,7 +665,7 @@ class Paiement extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.'paiement as p'; $sql.= ' WHERE p.rowid = '.$id; - dol_syslog(get_class($this).'::info sql='.$sql); + dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); if ($result) @@ -734,7 +728,7 @@ class Paiement extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' - sql='.$sql); + dol_syslog(get_class($this).'::getBillsArray Error '.$this->error.' -', LOG_DEBUG); return -1; } } @@ -753,7 +747,7 @@ class Paiement extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; if ($withpicto) $result.=($lien.img_object($langs->trans("ShowPayment"),'payment').$lienfin); diff --git a/htdocs/compta/paiement/info.php b/htdocs/compta/paiement/info.php index 8cc06397e62..84ef52c3a80 100644 --- a/htdocs/compta/paiement/info.php +++ b/htdocs/compta/paiement/info.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; $langs->load("bills"); $langs->load("companies"); +$id=GETPOST('id'); + /* * View @@ -39,8 +41,8 @@ $langs->load("companies"); llxHeader(); $paiement = new Paiement($db); -$paiement->fetch($_GET["id"], $user); -$paiement->info($_GET["id"]); +$paiement->fetch($id); +$paiement->info($id); $head = payment_prepare_head($paiement); diff --git a/htdocs/compta/paiement/liste.php b/htdocs/compta/paiement/list.php similarity index 78% rename from htdocs/compta/paiement/liste.php rename to htdocs/compta/paiement/list.php index 6e3e1bc54ff..c7fd426babf 100644 --- a/htdocs/compta/paiement/liste.php +++ b/htdocs/compta/paiement/list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/compta/paiement/liste.php + * \file htdocs/compta/paiement/list.php * \ingroup compta * \brief Page liste des paiements des factures clients */ @@ -42,6 +42,11 @@ $paymentstatic=new Paiement($db); $accountstatic=new Account($db); $companystatic=new Societe($db); +$search_ref=GETPOST("search_ref","int"); +$search_account=GETPOST("search_account","int"); +$search_paymenttype=GETPOST("search_paymenttype"); +$search_amount=GETPOST("search_amount"); +$search_company=GETPOST("search_company"); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -53,8 +58,14 @@ $limit = $conf->liste_limit; if (! $sortorder) $sortorder="DESC"; if (! $sortfield) $sortfield="p.rowid"; - - +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_account=""; + $search_amount=""; + $search_paymenttype=""; + $search_company=""; +} /* * View @@ -85,7 +96,7 @@ else //$sql.= " c.libelle as paiement_type,"; $sql.= " c.code as paiement_code,"; $sql.= " ba.rowid as bid, ba.label,"; - $sql.= " s.rowid as socid, s.nom"; + $sql.= " s.rowid as socid, s.nom as name"; //$sql.= " f.facnumber"; $sql.= " FROM (".MAIN_DB_PREFIX."c_paiement as c, ".MAIN_DB_PREFIX."paiement as p)"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON p.fk_bank = b.rowid"; @@ -110,11 +121,11 @@ else else $sql.= " AND f.fk_user_author = ".$userid; } // Search criteria - if (GETPOST("search_ref")) $sql .=" AND p.rowid=".GETPOST("search_ref",'int'); - if (GETPOST("search_account") > 0) $sql .=" AND b.fk_account=".GETPOST("search_account",'int'); - if (GETPOST("search_paymenttype") != "") $sql .=" AND c.code='".GETPOST("search_paymenttype")."'"; - if (GETPOST("search_amount")) $sql .=" AND p.amount=".price2num(GETPOST("search_amount")); - if (GETPOST("search_company")) $sql .= natural_search('s.nom', GETPOST('search_company')); + if ($search_ref) $sql .=" AND p.rowid=".$search_ref; + if ($search_account > 0) $sql .=" AND b.fk_account=".$search_account; + if ($search_paymenttype != "") $sql .=" AND c.code='".$search_paymenttype."'"; + if ($search_amount) $sql .=" AND p.amount='".price2num($search_amount)."'"; + if ($search_company) $sql .= natural_search('s.nom', $search_company); } $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit+1, $offset); @@ -129,9 +140,9 @@ if ($resql) $paramlist=''; $paramlist.=(GETPOST("orphelins")?"&orphelins=1":""); - $paramlist.=($_REQUEST["search_ref"]?"&search_ref=".$_REQUEST["search_ref"]:""); - $paramlist.=($_REQUEST["search_company"]?"&search_company=".$_REQUEST["search_company"]:""); - $paramlist.=($_REQUEST["search_amount"]?"&search_amount=".$_REQUEST["search_amount"]:""); + $paramlist.=($search_ref?"&search_ref=".$search_ref:""); + $paramlist.=($search_company?"&search_company=".$search_company:""); + $paramlist.=($search_amount?"&search_amount=".$search_amount:""); print_barre_liste($langs->trans("ReceivedCustomersPayments"), $page, $_SERVER["PHP_SELF"],$paramlist,$sortfield,$sortorder,'',$num); @@ -149,26 +160,29 @@ if ($resql) { print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"p.statut","",$paramlist,'align="right"',$sortfield,$sortorder); } - print "
 
'; - print ''; + print ''; print ' '; - print ''; + print ''; print ''; - $form->select_types_paiements($_REQUEST["search_paymenttype"],'search_paymenttype','',2,1,1); + $form->select_types_paiements($search_paymenttype,'search_paymenttype','',2,1,1); print ''; - $form->select_comptes($_REQUEST["search_account"],'search_account',0,'',1); + $form->select_comptes($search_account,'search_account',0,'',1); print ''; - print ''; + print ''; + print ''; print ''; + print ''; print ''; - if ($objp->statut == 0) print ''; + if ($objp->statut == 0) print ''; print $paymentstatic->LibStatut($objp->statut,5); if ($objp->statut == 0) print ''; print ' 
'.$langs->trans("Amount").'
'; - - print ''; - print ''; - print ''; - print '
'.$langs->trans("Ref").''.$object->ref.'
'.$langs->trans("Amount").''.price($object->amount).'
'.$langs->trans("File").''; - - $relativepath = 'bon/'.$object->ref; - - print ''.$object->ref.''; - - print '

'; - - $fileimage = $conf->prelevement->dir_output.'/receipts/'.$object->ref.'.ps.png.0'; - $fileps = $conf->prelevement->dir_output.'/receipts/'.$object->ref.'.ps'; - - // Conversion du PDF en image png si fichier png non existant - if (!file_exists($fileimage)) - { - if (class_exists("Imagick")) - { - $ret = dol_convert_file($file,'png',$fileimage); - if ($ret < 0) $error++; - } - else - { - $langs->load("errors"); - print ''.$langs->trans("ErrorNoImagickReadimage").''; - } - } - - if (file_exists($fileimage)) - { - print ''; - - } - - dol_fiche_end(); - } - else - { - dol_print_error($db); - } -} - -llxFooter(); diff --git a/htdocs/compta/prelevement/bons.php b/htdocs/compta/prelevement/bons.php index 97e4401ec27..c2d67b4551b 100644 --- a/htdocs/compta/prelevement/bons.php +++ b/htdocs/compta/prelevement/bons.php @@ -73,14 +73,14 @@ if ($result) $urladd= "&statut=".$statut; - print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, "bons.php", $urladd, $sortfield, $sortorder, '', $num); + print_barre_liste($langs->trans("WithdrawalsReceipts"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num); print"\n\n"; print ''; print ''; - print_liste_field_titre($langs->trans("WithdrawalsReceipts"),"bons.php","p.ref",'','','class="liste_titre"'); - print_liste_field_titre($langs->trans("Date"),"bons.php","p.datec","","",'class="liste_titre" align="center"'); + print_liste_field_titre($langs->trans("WithdrawalsReceipts"),$_SERVER["PHP_SELF"],"p.ref",'','','class="liste_titre"'); + print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"p.datec","","",'class="liste_titre" align="center"'); print ''; print ''; @@ -104,7 +104,7 @@ if ($result) print $bon->LibStatut($obj->statut,2); print " "; - print ''.$obj->ref."\n"; + print ''.$obj->ref."\n"; print '\n"; diff --git a/htdocs/compta/prelevement/fiche.php b/htdocs/compta/prelevement/card.php similarity index 88% rename from htdocs/compta/prelevement/fiche.php rename to htdocs/compta/prelevement/card.php index e594beae1d6..e2a5e846b0a 100644 --- a/htdocs/compta/prelevement/fiche.php +++ b/htdocs/compta/prelevement/card.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/compta/prelevement/fiche.php + * \file htdocs/compta/prelevement/card.php * \ingroup prelevement * \brief Fiche prelevement */ @@ -69,7 +69,7 @@ if ( $action == 'confirm_credite' && GETPOST('confirm','alpha') == 'yes') $bon->set_credite(); - header("Location: fiche.php?id=".$id); + header("Location: card.php?id=".$id); exit; } @@ -92,7 +92,7 @@ if ($action == 'infotrans' && $user->rights->prelevement->bons->send) $bon->set_infotrans($user, $dt, GETPOST('methode','alpha')); } - header("Location: fiche.php?id=".$id); + header("Location: card.php?id=".$id); exit; } else @@ -105,7 +105,7 @@ if ($action == 'infotrans' && $user->rights->prelevement->bons->send) if ($error) { - header("Location: fiche.php?id=".$id."&error=$error"); + header("Location: card.php?id=".$id."&error=$error"); exit; } } @@ -120,7 +120,7 @@ if ($action == 'infocredit' && $user->rights->prelevement->bons->credit) if ($error) { - header("Location: fiche.php?id=".$id."&error=$error"); + header("Location: card.php?id=".$id."&error=$error"); exit; } } @@ -150,7 +150,7 @@ if ($id > 0) /*if ($action == 'credite') { - print $form->formconfirm("fiche.php?id=".$bon->id,$langs->trans("ClassCredited"),$langs->trans("ClassCreditedConfirm"),"confirm_credite",'',1,1); + print $form->formconfirm("card.php?id=".$bon->id,$langs->trans("ClassCredited"),$langs->trans("ClassCreditedConfirm"),"confirm_credite",'',1,1); }*/ @@ -201,7 +201,7 @@ if ($id > 0) if (empty($bon->date_trans) && $user->rights->prelevement->bons->send && $action=='settransmitted') { - print ''; + print ''; print ''; print ''; print '
'.$langs->trans("Amount").'
'.dol_print_date($db->jdate($obj->datec),'day')."
'; @@ -224,7 +224,7 @@ if ($id > 0) if (! empty($bon->date_trans) && $bon->date_credit == 0 && $user->rights->prelevement->bons->credit && $action=='setcredited') { - print ''; + print ''; print ''; print ''; print '
'; @@ -247,15 +247,15 @@ if ($id > 0) if (empty($bon->date_trans) && $user->rights->prelevement->bons->send) { - print "id."\">".$langs->trans("SetToStatusSent").""; + print "id."\">".$langs->trans("SetToStatusSent").""; } if (! empty($bon->date_trans) && $bon->date_credit == 0) { - print "id."\">".$langs->trans("ClassCredited").""; + print "id."\">".$langs->trans("ClassCredited").""; } - print "id."\">".$langs->trans("Delete").""; + print "id."\">".$langs->trans("Delete").""; print ""; } diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 3a83d9c3dba..5da94a28b76 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -56,7 +56,9 @@ class BonPrelevement extends CommonObject var $statut; // 0-Wait, 1-Trans, 2-Done var $labelstatut=array(); + var $invoice_in_error=array(); + /** * Constructor * @@ -280,7 +282,7 @@ class BonPrelevement extends CommonObject $sql.= " WHERE p.rowid = ".$rowid; $sql.= " AND p.entity = ".$conf->entity; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -315,7 +317,6 @@ class BonPrelevement extends CommonObject } else { - dol_syslog(get_class($this)."::Fetch Erreur sql=".$sql, LOG_ERR); return -2; } } @@ -558,8 +559,6 @@ class BonPrelevement extends CommonObject } else { - dol_syslog(get_class($this)."::set_infotrans Erreur 1", LOG_ERR); - dol_syslog($this->db->error()); $error++; } @@ -706,6 +705,7 @@ class BonPrelevement extends CommonObject //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; + dol_syslog(get_class($this)."::SommeAPrelever"); $resql = $this->db->query($sql); if ( $resql ) @@ -719,7 +719,6 @@ class BonPrelevement extends CommonObject else { $this->error=get_class($this)."::SommeAPrelever Erreur -1 sql=".$this->db->error(); - dol_syslog($this->error, LOG_ERR); return -1; } } @@ -758,13 +757,15 @@ class BonPrelevement extends CommonObject $factures = array(); $factures_prev = array(); $factures_result = array(); + $factures_prev_id=array(); + $factures_errors=array(); if (! $error) { $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc"; $sql.= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib"; $sql.= ", pfd.amount"; - $sql.= ", s.nom"; + $sql.= ", s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; @@ -780,7 +781,7 @@ class BonPrelevement extends CommonObject //if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'"; //if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'"; - dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::Create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -824,7 +825,9 @@ class BonPrelevement extends CommonObject { $bac = new CompanyBankAccount($this->db); $bac->fetch(0,$soc->id); + if ($bac->verif() >= 1) + //if (true) { $factures_prev[$i] = $fac; /* second tableau necessaire pour BonPrelevement */ @@ -833,8 +836,8 @@ class BonPrelevement extends CommonObject } else { - dol_syslog("Error on default bank number RIB/IBAN for thirdparty reported by verif() ".$fact->socid." ".$soc->nom, LOG_ERR); - $facture_errors[$fac[0]]="Error on default bank number RIB/IBAN for thirdparty reported by function verif() ".$fact->socid." ".$soc->nom; + dol_syslog("Error on default bank number RIB/IBAN for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_ERR); + $this->invoice_in_error[$fac[0]]="Error on default bank number RIB/IBAN for invoice ".$fact->getNomUrl(0)." for thirdparty (reported by function verif) ".$soc->name; } } else @@ -897,7 +900,7 @@ class BonPrelevement extends CommonObject $sql.= " WHERE ref LIKE '".$ref."%'"; $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::Create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -923,7 +926,7 @@ class BonPrelevement extends CommonObject $sql.= ", '".$this->db->idate($now)."'"; $sql.= ")"; - dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::Create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -984,7 +987,7 @@ class BonPrelevement extends CommonObject $sql.= ", fk_prelevement_bons = ".$prev_id; $sql.= " WHERE rowid = ".$fac[1]; - dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::Create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -1041,7 +1044,7 @@ class BonPrelevement extends CommonObject $sql.= " WHERE rowid = ".$prev_id; $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::Create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -1122,12 +1125,12 @@ class BonPrelevement extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; if ($option == 'xxx') { - $lien = ''; + $lien = ''; $lienfin=''; } @@ -1229,92 +1232,24 @@ class BonPrelevement extends CommonObject * @return int 0 if OK, <0 if KO */ //TODO: Optimize code to read lines in a single function - function Generate() + function generate() { global $conf,$langs,$mysoc; $result = 0; - dol_syslog(get_class($this)."::Generate build file ".$this->filename); + dol_syslog(get_class($this)."::generate build file ".$this->filename); $this->file = fopen($this->filename,"w"); - // TODO Move code for es and fr into an external module file with selection into setup of prelevement module - $found=0; - // Build file for Spain - if ($mysoc->country_code=='ES') - { - if (! empty($conf->esaeb->enabled)) - { - $found++; - - dol_include_once('/esaeb/class/esaeb19.class.php'); - - //Head - $esaeb19 = new AEB19DocWritter; - $esaeb19->configuraPresentador($this->numero_national_emetteur,$conf->global->ESAEB_SUFIX_PRESENTADOR,$this->raison_sociale,$this->emetteur_code_banque,$this->emetteur_code_guichet); - $idOrdenante = $esaeb19->agregaOrdenante($this->numero_national_emetteur,$conf->global->ESAEB_SUFIX_ORDENANTE,$this->raison_sociale,$this->emetteur_code_banque,$this->emetteur_code_guichet, $this->emetteur_number_key, $this->emetteur_numero_compte); - $this->total = 0; - $sql = "SELECT pl.rowid, pl.fk_soc, pl.client_nom, pl.code_banque, pl.code_guichet, pl.cle_rib, pl.number, pl.amount,"; - $sql.= " f.facnumber, pf.fk_facture"; - $sql.= " FROM"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; - $sql.= " ".MAIN_DB_PREFIX."facture as f,"; - $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf"; - $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; - $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; - $sql.= " AND pf.fk_facture = f.rowid"; - - //Lines - $i = 0; - $resql=$this->db->query($sql); - if ($resql) - { - $num = $this->db->num_rows($resql); - - $client = new Societe($this->db); - - while ($i < $num) - { - $obj = $this->db->fetch_object($resql); - $client->fetch($obj->fk_soc); - - $esaeb19->agregaRecibo( - $idOrdenante, - $client->idprof1, - $obj->client_nom, - $obj->code_banque, - $obj->code_guichet, - $obj->cle_rib, - $obj->number, - $obj->amount, - "Fra.".$obj->facnumber." ".$obj->amount - ); - - $this->total = $this->total + $obj->amount; - - $i++; - } - } - else - { - $result = -2; - } - - fputs($this->file, $esaeb19->generaRemesa()); - } - } - // Build file for European countries - if (! $found && $mysoc->isInEEC()) + if ($mysoc->isInEEC()) { $found++; /** - * SECTION CREATION FICHIER SEPA - * SECTION CREATION FICHIER SEPA * SECTION CREATION FICHIER SEPA */ // SEPA Initialisation @@ -1331,20 +1266,20 @@ class BonPrelevement extends CommonObject /* * section Debiteur (sepa Debiteurs bloc lines) */ - $sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, soc.datec, p.code as country_code,"; - $sql.= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,"; + $sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, soc.datec, c.code as country_code,"; + $sql.= " pl.client_nom as name, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,"; $sql.= " f.facnumber as fac, pf.fk_facture as idfac, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum"; $sql.= " FROM"; $sql.= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; $sql.= " ".MAIN_DB_PREFIX."facture as f,"; $sql.= " ".MAIN_DB_PREFIX."prelevement_facture as pf,"; $sql.= " ".MAIN_DB_PREFIX."societe as soc,"; - $sql.= " ".MAIN_DB_PREFIX."c_pays as p,"; + $sql.= " ".MAIN_DB_PREFIX."c_country as c,"; $sql.= " ".MAIN_DB_PREFIX."societe_rib as rib"; $sql.= " WHERE pl.fk_prelevement_bons = ".$this->id; $sql.= " AND pl.rowid = pf.fk_prelevement_lignes"; $sql.= " AND pf.fk_facture = f.rowid"; - $sql.= " AND soc.fk_pays = p.rowid"; + $sql.= " AND soc.fk_pays = c.rowid"; $sql.= " AND soc.rowid = f.fk_soc"; $sql.= " AND rib.fk_soc = f.fk_soc"; $sql.= " AND rib.default_rib = 1"; @@ -1356,7 +1291,7 @@ class BonPrelevement extends CommonObject while ($i < $num) { $obj = $this->db->fetch_object($resql); - $fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->facnumber, $obj->idfac, $obj->iban, $obj->bic, $obj->datec, $obj->drum); + $fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->name, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->facnumber, $obj->idfac, $obj->iban, $obj->bic, $obj->datec, $obj->drum); $this->total = $this->total + $obj->somme; $i++; } @@ -1377,8 +1312,6 @@ class BonPrelevement extends CommonObject } /** - * SECTION CREATION FICHIER SEPA - * SECTION CREATION FICHIER SEPA * SECTION CREATION FICHIER SEPA */ // SEPA File Header @@ -1470,11 +1403,14 @@ class BonPrelevement extends CommonObject } } else - { + { $result = -2; } + $langs->load('withdrawals'); - fputs($this->file, $langs->trans('WithdrawalFileNotCapable')); + + // TODO Add here code to generate a generic file + fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code)); } fclose($this->file); @@ -1560,11 +1496,11 @@ class BonPrelevement extends CommonObject * Write recipient of request (customer) * * @param string $row_code_client soc.code_client as code, - * @param string $row_nom pl.client_nom AS nom, + * @param string $row_nom pl.client_nom AS name, * @param string $row_address soc.address AS adr, * @param string $row_zip soc.zip * @param string $row_town soc.town - * @param string $row_country_code p.code AS pays, + * @param string $row_country_code c.code AS country, * @param string $row_cb pl.code_banque AS cb, * @param string $row_cg pl.code_guichet AS cg, * @param string $row_cc pl.number AS cc, @@ -1720,7 +1656,7 @@ class BonPrelevement extends CommonObject $obj = $this->db->fetch_object($resql); // DONNEES BRUTES : par la suite Rows['XXX'] de la requete au dessus - $pays = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY); + $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY); $IdBon = sprintf("%05d", $obj->rowid); $RefBon = $obj->ref; $type = ($nombre == 1) ? 'FRST' : 'RCUR' ; @@ -1745,7 +1681,7 @@ class BonPrelevement extends CommonObject $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$configuration->global->PRELEVEMENT_RAISON_SOCIALE.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; - $XML_SEPA_INFO .= ' '.$pays[1].''.$CrLf; + $XML_SEPA_INFO .= ' '.$country[1].''.$CrLf; $XML_SEPA_INFO .= ' '.$configuration->global->MAIN_INFO_SOCIETE_ADDRESS.''.$CrLf; $XML_SEPA_INFO .= ' '.$configuration->global->MAIN_INFO_SOCIETE_ZIP.' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1763,7 +1699,7 @@ class BonPrelevement extends CommonObject /* $XML_SEPA_INFO .= ' '.$CrLf; $XML_SEPA_INFO .= ' '.$configuration->global->PRELEVEMENT_RAISON_SOCIALE.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; - $XML_SEPA_INFO .= ' '.$pays[1].''.$CrLf; + $XML_SEPA_INFO .= ' '.$country[1].''.$CrLf; $XML_SEPA_INFO .= ' '.$conf->global->MAIN_INFO_SOCIETE_ADDRESS.''.$CrLf; $XML_SEPA_INFO .= ' '.$conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN.''.$CrLf; $XML_SEPA_INFO .= ' '.$CrLf; @@ -1880,21 +1816,21 @@ class BonPrelevement extends CommonObject if ($mode == 1) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut0').' '.$langs->trans($this->labelstatut[$statut]); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1').' '.$langs->trans($this->labelstatut[$statut]); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3').' '.$langs->trans($this->labelstatut[$statut]); if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6').' '.$langs->trans($this->labelstatut[$statut]); } if ($mode == 2) { - if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut0'); - if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==0) return img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); if ($statut==2) return img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); } if ($mode == 3) { - if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut0'); - if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==0) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut1'); + if ($statut==1) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut3'); if ($statut==2) return $langs->trans($this->labelstatut[$statut]).' '.img_picto($langs->trans($this->labelstatut[$statut]),'statut6'); } } diff --git a/htdocs/compta/prelevement/class/index.html b/htdocs/compta/prelevement/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/prelevement/class/ligneprelevement.class.php b/htdocs/compta/prelevement/class/ligneprelevement.class.php index 9c4bf96e8b3..581fb3152af 100644 --- a/htdocs/compta/prelevement/class/ligneprelevement.class.php +++ b/htdocs/compta/prelevement/class/ligneprelevement.class.php @@ -138,20 +138,20 @@ class LignePrelevement if ($mode == 1) { - if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0').' '.$langs->trans($this->statuts[$statut]); + if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut1').' '.$langs->trans($this->statuts[$statut]); if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]); if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]); } if ($mode == 2) { - if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut0'); + if ($statut==0) return img_picto($langs->trans($this->statuts[$statut]),'statut1'); if ($statut==2) return img_picto($langs->trans($this->statuts[$statut]),'statut4'); if ($statut==3) return img_picto($langs->trans($this->statuts[$statut]),'statut8'); } if ($mode == 3) { - if ($statut==0) return $langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut0'); + if ($statut==0) return $langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut1'); if ($statut==2) return $langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut4'); if ($statut==3) return $langs->trans($this->statuts[$statut]).' '.img_picto($langs->trans($this->statuts[$statut]),'statut8'); } diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 51f9a83ed3c..d0b467f294b 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -173,7 +173,8 @@ class RejetPrelevement } //Tag invoice as unpaid dol_syslog("RejetPrelevement::Create set_unpaid fac ".$fac->ref); - $fac->set_unpaid($fac->id, $user); + + $fac->set_unpaid($user); //TODO: Must be managed by notifications module // Send email to sender of the standing order request @@ -194,7 +195,7 @@ class RejetPrelevement } /** - * Envoi mail + * Send email to all users that has asked the withdraw request * * @param Facture $fac Invoice object * @return void @@ -244,7 +245,7 @@ class RejetPrelevement $arr_mime = array(); $arr_name = array(); $facref = $fac->ref; - $socname = $soc->nom; + $socname = $soc->name; $amount = price($fac->total_ttc); $userinfo = $this->user->getFullName($langs); diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index a3f7ca2ace8..e4cb4b65c30 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -70,6 +70,10 @@ if ($action == 'create') if ($result == 0) { $mesg='
'.$langs->trans("NoInvoiceCouldBeWithdrawed").'
'; + foreach($bprev->invoice_in_error as $key => $val) + { + $mesg.=$val."
\n"; + } } } @@ -156,7 +160,7 @@ print '
'; * Invoices waiting for withdraw */ -$sql = "SELECT f.facnumber, f.rowid, f.total_ttc, s.nom, s.rowid as socid,"; +$sql = "SELECT f.facnumber, f.rowid, f.total_ttc, s.nom as name, s.rowid as socid,"; $sql.= " pfd.date_demande"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; $sql.= " ".MAIN_DB_PREFIX."societe as s,"; @@ -179,6 +183,7 @@ if ($resql) print '
'; print ''; print ''; + print ''; print ''; print ''; print ''; @@ -190,16 +195,22 @@ if ($resql) { $obj = $db->fetch_object($resql); $var=!$var; - print ''; + print ''; + // Thirdparty print ''; + // RIB + print ''; + // Amount print ''; @@ -211,7 +222,7 @@ if ($resql) $i++; } } - else print ''; + else print ''; print "
'.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("RIB").''.$langs->trans("AmountTTC").''.$langs->trans("DateRequest").'
'; + print '
'; $invoicestatic->id=$obj->rowid; $invoicestatic->ref=$obj->facnumber; print $invoicestatic->getNomUrl(1,'withdraw'); print ''; - $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; - print $thirdpartystatic->getNomUrl(1,'customer'); + $thirdpartystatic->fetch($obj->socid); + print $thirdpartystatic->getNomUrl(1,'card'); print ''; + print $thirdpartystatic->display_rib(); + print ''; print price($obj->total_ttc,0,$langs,0,0,-1,$conf->currency); print '
'.$langs->trans("None").'
'.$langs->trans("None").'
"; print "
\n"; } diff --git a/htdocs/compta/prelevement/demandes.php b/htdocs/compta/prelevement/demandes.php index 4cd3098bfc3..364e073676b 100644 --- a/htdocs/compta/prelevement/demandes.php +++ b/htdocs/compta/prelevement/demandes.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $langs->load("banks"); $langs->load("categories"); -$langs->load("widthdrawals"); +$langs->load("withdrawals"); $langs->load("companies"); // Security check @@ -67,7 +67,7 @@ if (! $sortfield) $sortfield="f.facnumber"; */ $sql= "SELECT f.facnumber, f.rowid, f.total_ttc,"; -$sql.= " s.nom, s.rowid as socid,"; +$sql.= " s.nom as name, s.rowid as socid,"; $sql.= " pfd.date_demande as date_demande,"; $sql.= " pfd.fk_user_demande"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; @@ -112,8 +112,8 @@ if ($resql) print '
'; $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; + $thirdpartystatic->name=$obj->name; print $thirdpartystatic->getNomUrl(1,'customer'); print '
'.$langs->trans("Ref").''.$bon->getNomUrl(1).'
'.$langs->trans("Date").''.dol_print_date($bon->datec,'day').'
'.$langs->trans("Amount").''.price($bon->amount).'
'.$langs->trans('Status').''.$bon->getLibStatut(1).'
'.$langs->trans("TransData").''; print dol_print_date($bon->date_trans,'day'); print ' '.$langs->trans("By").' '.$muser->getFullName($langs).'
'; - + print '
'; - + print '
'; print $langs->trans("WithdrawalFile").''; $relativepath = 'receipts/'.$bon->ref; print ''.$relativepath.''; print '
'; - + dol_fiche_end(); - + } else { @@ -114,7 +114,7 @@ $offset = $conf->liste_limit * $page ; */ $sql = "SELECT pf.rowid"; $sql.= ",f.rowid as facid, f.facnumber as ref, f.total_ttc"; -$sql.= ", s.rowid as socid, s.nom, pl.statut"; +$sql.= ", s.rowid as socid, s.nom as name, pl.statut"; $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_lignes as pl"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_facture as pf"; @@ -144,9 +144,9 @@ if ($result) print"\n\n"; print ''; print ''; - print_liste_field_titre($langs->trans("Bill"),"factures.php","p.ref",'',$urladd,'class="liste_titre"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("ThirdParty"),"factures.php","s.nom",'',$urladd,'class="liste_titre"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Amount"),"factures.php","f.total_ttc","",$urladd,'class="liste_titre" align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Bill"),$_SERVER["PHP_SELF"],"p.ref",'',$urladd,'class="liste_titre"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom",'',$urladd,'class="liste_titre"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Amount"),$_SERVER["PHP_SELF"],"f.total_ttc","",$urladd,'class="liste_titre" align="center"',$sortfield,$sortorder); print ''; $var=false; @@ -165,8 +165,8 @@ if ($result) print ''.$obj->ref."\n"; - print '\n"; + print '\n"; print '\n"; @@ -213,6 +213,7 @@ else dol_print_error($db); } -$db->close(); llxFooter(); + +$db->close(); diff --git a/htdocs/compta/prelevement/fiche-rejet.php b/htdocs/compta/prelevement/fiche-rejet.php index 905ab6f6bf1..161227aa121 100644 --- a/htdocs/compta/prelevement/fiche-rejet.php +++ b/htdocs/compta/prelevement/fiche-rejet.php @@ -62,17 +62,17 @@ if ($prev_id) print ''; print ''; print ''; - + // Status print ''; print ''; print ''; - + if($bon->date_trans <> 0) { $muser = new User($db); $muser->fetch($bon->user_trans); - + print ''; @@ -86,19 +86,19 @@ if ($prev_id) print dol_print_date($bon->date_credit,'day'); print ''; } - + print '
 
'; - print img_object($langs->trans("ShowCompany"),"company"). ' '.stripslashes($obj->nom)."'; + print img_object($langs->trans("ShowCompany"),"company"). ' '.$obj->name."'.price($obj->total_ttc)."
'.$langs->trans("Ref").''.$bon->getNomUrl(1).'
'.$langs->trans("Date").''.dol_print_date($bon->datec,'day').'
'.$langs->trans("Amount").''.price($bon->amount).'
'.$langs->trans('Status').''.$bon->getLibStatut(1).'
'.$langs->trans("TransData").''; print dol_print_date($bon->date_trans,'day'); print ' '.$langs->trans("By").' '.$muser->getFullName($langs).'
'; - + print '
'; - + print '
'; print $langs->trans("WithdrawalFile").''; $relativepath = 'receipts/'.$bon->ref; print ''.$relativepath.''; print '
'; - + dol_fiche_end(); - + } else { @@ -112,7 +112,7 @@ $rej = new RejetPrelevement($db, $user); * Liste des factures */ $sql = "SELECT pl.rowid, pl.amount, pl.statut"; -$sql.= " , s.rowid as socid, s.nom"; +$sql.= " , s.rowid as socid, s.nom as name"; $sql.= " , pr.motif, pr.afacturer, pr.fk_facture"; $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; @@ -152,7 +152,7 @@ if ($resql) print img_picto('', 'statut'.$obj->statut).' '; print substr('000000'.$obj->rowid, -6); print '
'.stripslashes($obj->nom)."'.$obj->name."'.price($obj->amount)."'.$rej->motifs[$obj->motif].'
'; print ''; diff --git a/htdocs/compta/prelevement/index.php b/htdocs/compta/prelevement/index.php index 911ffde6f99..1abc421cf46 100644 --- a/htdocs/compta/prelevement/index.php +++ b/htdocs/compta/prelevement/index.php @@ -96,7 +96,7 @@ print '

'; */ $sql = "SELECT f.facnumber, f.rowid, f.total_ttc, f.fk_statut, f.paye, f.type,"; $sql.= " pfd.date_demande,"; -$sql.= " s.nom, s.rowid as socid"; +$sql.= " s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f,"; $sql.= " ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -137,7 +137,7 @@ if ($resql) print ''; $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; + $thirdpartystatic->name=$obj->name; print $thirdpartystatic->getNomUrl(1,'customer'); print ''; diff --git a/htdocs/compta/prelevement/ligne.php b/htdocs/compta/prelevement/ligne.php index ebf5180eb0e..3e7cb5b6bd7 100644 --- a/htdocs/compta/prelevement/ligne.php +++ b/htdocs/compta/prelevement/ligne.php @@ -105,10 +105,13 @@ if ($action == 'confirm_rejet') } } + /* * View */ +$invoicestatic=new Facture($db); + llxHeader('',$langs->trans("StandingOrder")); $h = 0; @@ -131,12 +134,10 @@ if ($id) print ''; print ''; + print $bon->getNomUrl(1).''; print ''; print ''; - print ''; + print ''; if ($lipre->statut == 3) { @@ -190,7 +191,7 @@ if ($id) print ''; //Select yes/no - print ''; + print ''; print ''; @@ -215,7 +216,7 @@ if ($id) print '
'.$langs->trans("WithdrawalsReceipts").''; - print ''.$lipre->bon_ref.'
'.$langs->trans("Date").''.dol_print_date($bon->datec,'day').'
'.$langs->trans("Amount").''.price($lipre->amount).'
'.$langs->trans("Status").''; - - print $lipre->LibStatut($lipre->statut,1).'
'.$langs->trans("Status").''.$lipre->LibStatut($lipre->statut,1).'
'.$langs->trans("WithdrawalRefused").'
'.$langs->trans("WithdrawalRefusedConfirm").' '.$soc->nom.' ?
'.$langs->trans("WithdrawalRefusedConfirm").' '.$soc->name.' ?'; print $form->selectyesno("confirm",1,0); print '

'; //Confirm Button - print '
'; + print '
'; print ''; } @@ -229,13 +230,20 @@ if ($id) if ($action == '') { - if ($bon->statut == 2 && $lipre->statut == 2 && $user->rights->prelevement->bons->credit) + if ($bon->statut == 2 && $lipre->statut == 2) { - print "id\">".$langs->trans("StandingOrderReject").""; + if ($user->rights->prelevement->bons->credit) + { + print "id\">".$langs->trans("StandingOrderReject").""; + } + else + { + print "trans("NotAllowed")."\">".$langs->trans("StandingOrderReject").""; + } } else { - print "".$langs->trans("StandingOrderReject").""; + print "trans("NotPossibleForThisStatusOfWithdrawReceiptORLine")."\">".$langs->trans("StandingOrderReject").""; } } @@ -256,8 +264,8 @@ if ($id) * Liste des factures */ $sql = "SELECT pf.rowid"; - $sql.= " ,f.rowid as facid, f.facnumber as ref, f.total_ttc"; - $sql.= " , s.rowid as socid, s.nom"; + $sql.= " ,f.rowid as facid, f.facnumber as ref, f.total_ttc, f.paye, f.fk_statut"; + $sql.= " , s.rowid as socid, s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; $sql.= " , ".MAIN_DB_PREFIX."prelevement_facture as pf"; @@ -287,7 +295,7 @@ if ($id) print"\n\n"; print ''; print ''; - print ''; + print ''; print ''; $var=True; @@ -307,11 +315,16 @@ if ($id) print ''.$obj->ref."\n"; - print '\n"; + print '\n"; print '\n"; + print '\n"; + print "\n"; $i++; diff --git a/htdocs/compta/prelevement/lignes.php b/htdocs/compta/prelevement/lignes.php index d7dac30b3af..c4724824f36 100644 --- a/htdocs/compta/prelevement/lignes.php +++ b/htdocs/compta/prelevement/lignes.php @@ -106,7 +106,7 @@ if ($prev_id) print '
'.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("Amount").''.$langs->trans("Invoice").''.$langs->trans("ThirdParty").''.$langs->trans("Amount").''.$langs->trans("Status").'
'; - print img_object($langs->trans("ShowCompany"),"company"). ' '.stripslashes($obj->nom)."'; + print img_object($langs->trans("ShowCompany"),"company"). ' '.$obj->name."'.price($obj->total_ttc)."'; + $invoicestatic->fetch($obj->facid); + print $invoicestatic->getLibStatut(5); + print "
'; dol_fiche_end(); - + } else { @@ -124,11 +124,9 @@ $pagenext = $page + 1; /* * Liste des lignes de prelevement - * - * */ $sql = "SELECT pl.rowid, pl.statut, pl.amount"; -$sql.= ", s.rowid as socid, s.nom"; +$sql.= ", s.rowid as socid, s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_lignes as pl"; $sql.= ", ".MAIN_DB_PREFIX."prelevement_bons as pb"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; @@ -149,13 +147,13 @@ if ($result) $urladd = "&id=".$prev_id; - print_barre_liste("", $page, "lignes.php", $urladd, $sortfield, $sortorder, '', $num); + print_barre_liste("", $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num); print"\n\n"; print ''; print ''; - print_liste_field_titre($langs->trans("Lines"),"lignes.php","pl.rowid",'',$urladd); - print_liste_field_titre($langs->trans("ThirdParty"),"lignes.php","s.nom",'',$urladd); - print_liste_field_titre($langs->trans("Amount"),"lignes.php","pl.amount","",$urladd,'align="center"'); + print_liste_field_titre($langs->trans("Lines"),$_SERVER["PHP_SELF"],"pl.rowid",'',$urladd); + print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom",'',$urladd); + print_liste_field_titre($langs->trans("Amount"),$_SERVER["PHP_SELF"],"pl.amount","",$urladd,'align="center"'); print ''; $var=false; @@ -175,7 +173,11 @@ if ($result) print substr('000000'.$obj->rowid, -6); print ''; - print '\n"; + $thirdparty=new Societe($db); + $thirdparty->fetch($obj->socid); + print '\n"; print '\n"; diff --git a/htdocs/compta/prelevement/liste.php b/htdocs/compta/prelevement/list.php similarity index 76% rename from htdocs/compta/prelevement/liste.php rename to htdocs/compta/prelevement/list.php index a9fb6024992..921736faedf 100644 --- a/htdocs/compta/prelevement/liste.php +++ b/htdocs/compta/prelevement/list.php @@ -19,7 +19,7 @@ */ /** - * \file htdocs/compta/prelevement/liste.php + * \file htdocs/compta/prelevement/list.php * \ingroup prelevement * \brief Page liste des prelevements */ @@ -42,10 +42,10 @@ $result = restrictedArea($user, 'prelevement','','','bons'); $page = GETPOST('page','int'); $sortorder = ((GETPOST('sortorder','alpha')=="")) ? "DESC" : GETPOST('sortorder','alpha'); $sortfield = ((GETPOST('sortfield','alpha')=="")) ? "p.datec" : GETPOST('sortfield','alpha'); -$search_line = GETPOST('search_ligne','alpha'); +$search_line = GETPOST('search_line','alpha'); $search_bon = GETPOST('search_bon','alpha'); $search_code = GETPOST('search_code','alpha'); -$search_societe = GETPOST('search_societe','alpha'); +$search_company = GETPOST('search_company','alpha'); $statut = GETPOST('statut','int'); $bon=new BonPrelevement($db,""); @@ -53,7 +53,14 @@ $ligne=new LignePrelevement($db,$user); $offset = $conf->liste_limit * $page ; - +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_line=""; + $search_bon=""; + $search_code=""; + $search_company=""; + $statut=""; +} /* * View @@ -63,7 +70,7 @@ llxHeader('',$langs->trans("WithdrawalsLines")); $sql = "SELECT p.rowid, p.ref, p.statut, p.datec"; $sql.= " ,f.rowid as facid, f.facnumber, f.total_ttc"; -$sql.= " , s.rowid as socid, s.nom, s.code_client"; +$sql.= " , s.rowid as socid, s.nom as name, s.code_client"; $sql.= " , pl.amount, pl.statut as statut_ligne, pl.rowid as rowid_ligne"; $sql.= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql.= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; @@ -88,9 +95,9 @@ if ($search_code) { $sql.= " AND s.code_client LIKE '%".$db->escape($search_code)."%'"; } -if ($search_societe) +if ($search_company) { - $sql .= " AND s.nom LIKE '%".$db->escape($search_societe)."%'"; + $sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'"; } $sql.=$db->order($sortfield,$sortorder); $sql.=$db->plimit($conf->liste_limit+1, $offset); @@ -120,17 +127,19 @@ if ($result) print ''; print ''; - print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''; - print ''; - print ''; + print ''; print ''; $var=True; @@ -155,16 +164,16 @@ if ($result) print $bon->LibStatut($obj->statut,2); print " "; - print ''.$obj->ref."\n"; + print ''.$obj->ref."\n"; print '\n"; print ''; - print '\n"; + print '\n"; - print '\n"; + print '\n"; print '\n"; diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php index 30b36a59775..0582e4f4091 100644 --- a/htdocs/compta/prelevement/rejets.php +++ b/htdocs/compta/prelevement/rejets.php @@ -85,13 +85,13 @@ if ($result) $num = $db->num_rows($result); $i = 0; - print_barre_liste($langs->trans("WithdrawsRefused"), $page, "rejets.php", $urladd, $sortfield, $sortorder, '', $num); + print_barre_liste($langs->trans("WithdrawsRefused"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num); print"\n\n"; print '
 
'.stripslashes($obj->nom)."'; + print $thirdparty->getNomUrl(1); + print "'.price($obj->amount)." 
   
'; + print ''; + print ''; + print ''; print img_object($langs->trans("ShowBill"),"bill"); print ' '.$obj->facnumber."'.$obj->nom."'.$obj->name."'.$obj->code_client."'.$obj->code_client."'.dol_print_date($db->jdate($obj->datec),'day')."
'; print ''; - print_liste_field_titre($langs->trans("Line"),"rejets.php","p.ref",'',$urladd); - print_liste_field_titre($langs->trans("ThirdParty"),"rejets.php","s.nom",'',$urladd); - print_liste_field_titre($langs->trans("Reason"),"rejets.php","pr.motif","",$urladd); + print_liste_field_titre($langs->trans("Line"),$_SERVER["PHP_SELF"],"p.ref",'',$urladd); + print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom",'',$urladd); + print_liste_field_titre($langs->trans("Reason"),$_SERVER["PHP_SELF"],"pr.motif","",$urladd); print ''; $var=True; @@ -108,7 +108,7 @@ if ($result) print substr('000000'.$obj->rowid, -6).""; - print '\n"; + print '\n"; print ''; print "\n"; diff --git a/htdocs/compta/prelevement/stats.php b/htdocs/compta/prelevement/stats.php index 2c8607a9a56..c3667f8b69f 100644 --- a/htdocs/compta/prelevement/stats.php +++ b/htdocs/compta/prelevement/stats.php @@ -21,7 +21,7 @@ /** * \file htdocs/compta/prelevement/stats.php * \ingroup prelevement - * \brief Page de stats des prelevements + * \brief Page with statistics on withdrawals */ require('../../main.inc.php'); @@ -96,7 +96,7 @@ if ($resql) print ''; print ''; - $var=True; + $var=false; while ($i < $num) { diff --git a/htdocs/compta/recap-compta.php b/htdocs/compta/recap-compta.php index 42f91e3132b..59599e93dc6 100644 --- a/htdocs/compta/recap-compta.php +++ b/htdocs/compta/recap-compta.php @@ -64,8 +64,8 @@ if ($socid > 0) print '
'.stripslashes($obj->nom)."'.stripslashes($obj->nom)."'.$rej->motifs[$obj->motif].'
'.$langs->trans("Status").''.$langs->trans("Number").'%'.$langs->trans("Amount").'%
'; - // Nom - print ''; + // Name + print ''; // Prefix if (! empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field @@ -181,7 +181,7 @@ if ($socid > 0) print '\n"; print ''; + print ''.img_object($langs->trans("ShowPayment"),"payment").' '.$langs->trans("Payment").' '.$objp->rowid.''; print "\n"; print "\n"; print ''; diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 26589be3c5d..9122ece2ed9 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2014 Ferran Marcet * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2014 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,6 +34,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->load("bills"); +$langs->load("donation"); +$langs->load("salaries"); $date_startmonth=GETPOST('date_startmonth'); $date_startday=GETPOST('date_startday'); @@ -96,7 +99,7 @@ else } // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->COMPTA_MODE); +$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->ACCOUNTING_MODE); /* @@ -117,7 +120,7 @@ $total_ttc=0; // Affiche en-tete de rapport if ($modecompta=="CREANCES-DETTES") { - $nom=$langs->trans("AnnualByCompaniesDueDebtMode"); + $name=$langs->trans("AnnualByCompaniesDueDebtMode"); $calcmode=$langs->trans("CalcModeDebt"); $calcmode.='
('.$langs->trans("SeeReportInInputOutputMode",'
','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); @@ -129,7 +132,7 @@ if ($modecompta=="CREANCES-DETTES") //$exportlink=$langs->trans("NotYetAvailable"); } else { - $nom=$langs->trans("AnnualByCompaniesInputOutputMode"); + $name=$langs->trans("AnnualByCompaniesInputOutputMode"); $calcmode=$langs->trans("CalcModeEngagement"); $calcmode.='
('.$langs->trans("SeeReportInDueDebtMode",'','').')'; //$period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',1,1,0,'',1,0,1); @@ -139,7 +142,7 @@ else { $builddate=time(); //$exportlink=$langs->trans("NotYetAvailable"); } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); +report_header($name,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array('modecompta'=>$modecompta),$calcmode); // Show report array print '
'.$langs->trans("Name").''.$societe->nom.'
'.$langs->trans("Name").''.$societe->name.'
'.dol_print_date($db->jdate($objp->dp),'day')."'; print '      '; // Decalage - print ''.img_object($langs->trans("ShowPayment"),"payment").' '.$langs->trans("Payment").' '.$objp->rowid.'  '.price($objp->amount).'
'; @@ -157,7 +160,7 @@ print ''; if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT s.nom, s.rowid as socid, sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc"; + $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total) as amount_ht, sum(f.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."facture as f"; $sql.= " WHERE f.fk_soc = s.rowid"; @@ -175,7 +178,7 @@ else * Liste des paiements (les anciens paiements ne sont pas vus par cette requete car, sur les * vieilles versions, ils n'etaient pas lies via paiement_facture. On les ajoute plus loin) */ - $sql = "SELECT s.nom as nom, s.rowid as socid, sum(pf.amount) as amount_ttc"; + $sql = "SELECT s.nom as name, s.rowid as socid, sum(pf.amount) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."facture as f"; $sql.= ", ".MAIN_DB_PREFIX."paiement_facture as pf"; @@ -191,7 +194,7 @@ if ($socid) $sql.= " AND f.fk_soc = ".$socid; $sql.= " GROUP BY s.nom, s.rowid"; $sql.= " ORDER BY s.nom, s.rowid"; -dol_syslog("get customer invoices sql=".$sql); +dol_syslog("get customer invoices", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -203,7 +206,7 @@ if ($result) { $var=!$var; print ""; - print "\n"; + print "\n"; if ($modecompta == 'CREANCES-DETTES') print "\n"; @@ -222,7 +225,7 @@ if ($result) { // On ajoute les paiements clients anciennes version, non lie par paiement_facture if ($modecompta != 'CREANCES-DETTES') { - $sql = "SELECT 'Autres' as nom, '0' as idp, sum(p.amount) as amount_ttc"; + $sql = "SELECT 'Autres' as name, '0' as idp, sum(p.amount) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."bank as b"; $sql.= ", ".MAIN_DB_PREFIX."bank_account as ba"; $sql.= ", ".MAIN_DB_PREFIX."paiement as p"; @@ -233,10 +236,10 @@ if ($modecompta != 'CREANCES-DETTES') $sql.= " AND ba.entity = ".$conf->entity; if (! empty($date_start) && ! empty($date_end)) $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - $sql.= " GROUP BY nom, idp"; - $sql.= " ORDER BY nom"; + $sql.= " GROUP BY name, idp"; + $sql.= " ORDER BY name"; - dol_syslog("get old customer payments not linked to invoices sql=".$sql); + dol_syslog("get old customer payments not linked to invoices", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -287,7 +290,7 @@ print ''; */ if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT s.nom, s.rowid as socid, sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc"; + $sql = "SELECT s.nom as name, s.rowid as socid, sum(f.total_ht) as amount_ht, sum(f.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."facture_fourn as f"; $sql.= " WHERE f.fk_soc = s.rowid"; @@ -321,7 +324,7 @@ print ''; $subtotal_ht = 0; $subtotal_ttc = 0; -dol_syslog("get suppliers invoices sql=".$sql); +dol_syslog("get suppliers invoices", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -335,7 +338,7 @@ if ($result) { $var=!$var; print ""; - print "\n"; + print "\n"; if ($modecompta == 'CREANCES-DETTES') print "\n"; @@ -378,7 +381,7 @@ print '"; - print ''; + print ''; if ($modecompta == 'CREANCES-DETTES') print ''; print ''; print ''; @@ -452,7 +455,7 @@ print '"; - print ''; + print ''; if ($modecompta == 'CREANCES-DETTES') print ''; print ''; @@ -539,69 +542,140 @@ if ($mysoc->tva_assuj == 'franchise') // Non assujeti print ''; } + /* * Salaries */ -print ''; -$sql = "SELECT p.label as nom, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount, u.firstname, u.lastname, p.fk_user"; -$sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; -$sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user"; -$sql.= " WHERE p.entity = ".$conf->entity; -if (! empty($date_start) && ! empty($date_end)) - $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - -$sql.= " GROUP BY u.rowid"; -$sql.= " ORDER BY u.firstname"; - -dol_syslog("get payment salaries sql=".$sql); -$result=$db->query($sql); -$subtotal_ht = 0; -$subtotal_ttc = 0; -if ($result) +if ($conf->salaries->enabled) { - $num = $db->num_rows($result); - $var=true; - $i = 0; - if ($num) - { - while ($i < $num) - { - $obj = $db->fetch_object($result); + print ''; + $sql = "SELECT u.rowid, u.firstname, u.lastname, p.fk_user, p.label as label, date_format(p.datep,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; + $sql.= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=p.fk_user"; + $sql.= " WHERE p.entity = ".$conf->entity; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; - $total_ht -= $obj->amount; - $total_ttc -= $obj->amount; - $subtotal_ht += $obj->amount; - $subtotal_ttc += $obj->amount; + $sql.= " GROUP BY u.rowid, u.firstname, u.lastname, p.fk_user, p.label, dm"; + $sql.= " ORDER BY u.firstname"; - $var = !$var; - print ""; - - print "\n"; - - if ($modecompta == 'CREANCES-DETTES') print ''; - print ''; - print ''; - $i++; - } - } - else - { - $var = !$var; - print ""; - print ''; - print ''; - } + dol_syslog("get payment salaries"); + $result=$db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + $var=true; + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $total_ht -= $obj->amount; + $total_ttc -= $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + $var = !$var; + print ""; + + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + $i++; + } + } + else + { + $var = !$var; + print ""; + print ''; + print ''; + } + } + else + { + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; } -else + + +/* + * Donation + */ + +if ($conf->donation->enabled) { - dol_print_error($db); + print ''; + $sql = "SELECT p.societe as name, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; + $sql.= " FROM ".MAIN_DB_PREFIX."don as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + $sql.= " AND fk_statut=2"; + if (! empty($date_start) && ! empty($date_end)) + $sql.= " AND p.datedon >= '".$db->idate($date_start)."' AND p.datedon <= '".$db->idate($date_end)."'"; + $sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + $sql.= " ORDER BY p.societe, p.firstname, p.lastname, dm"; + + dol_syslog("get dunning"); + $result=$db->query($sql); + $subtotal_ht = 0; + $subtotal_ttc = 0; + if ($result) + { + $num = $db->num_rows($result); + $var=true; + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + $total_ht += $obj->amount; + $total_ttc += $obj->amount; + $subtotal_ht += $obj->amount; + $subtotal_ttc += $obj->amount; + + $var = !$var; + print ""; + + print "\n"; + + if ($modecompta == 'CREANCES-DETTES') print ''; + print ''; + print ''; + $i++; + } + } + else + { + $var = !$var; + print ""; + print ''; + print ''; + } + } + else + { + dol_print_error($db); + } + print ''; + if ($modecompta == 'CREANCES-DETTES') + print ''; + print ''; + print ''; } -print ''; -if ($modecompta == 'CREANCES-DETTES') - print ''; -print ''; -print ''; /* * VAT @@ -628,7 +702,7 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get vat to pay sql=".$sql); + dol_syslog("get vat to pay", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -673,7 +747,7 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get vat received back sql=".$sql); + dol_syslog("get vat received back", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -717,7 +791,7 @@ else $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get vat really paid sql=".$sql); + dol_syslog("get vat really paid", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -758,7 +832,7 @@ else $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get vat really received back sql=".$sql); + dol_syslog("get vat really received back", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index fdc9b0472f0..b586241c11e 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2014 Ferran Marcet * Copyright (C) 2014 Juanjo Menent + * Copyright (C) 2014 Florian Henry * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -47,7 +48,7 @@ if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accountin // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->COMPTA_MODE); +$modecompta=(GETPOST("modecompta")?GETPOST("modecompta"):$conf->global->ACCOUNTING_MODE); /* @@ -124,7 +125,7 @@ $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; //print $sql; -dol_syslog("get customers invoices sql=".$sql); +dol_syslog("get customers invoices", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -158,7 +159,7 @@ if ($modecompta != 'CREANCES-DETTES') $sql.= " GROUP BY dm"; $sql.= " ORDER BY dm"; - dol_syslog("get old customers payments not linked to invoices sql=".$sql); + dol_syslog("get old customers payments not linked to invoices", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -209,7 +210,7 @@ $sql.= " AND f.entity = ".$conf->entity; if ($socid) $sql.= " AND f.fk_soc = ".$socid; $sql.= " GROUP BY dm"; -dol_syslog("get suppliers invoices sql=".$sql); +dol_syslog("get suppliers invoices", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -250,7 +251,7 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " AND f.entity = ".$conf->entity; $sql.= " GROUP BY dm"; - dol_syslog("get vat to pay sql=".$sql); + dol_syslog("get vat to pay", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -281,7 +282,7 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " AND f.entity = ".$conf->entity; $sql.= " GROUP BY dm"; - dol_syslog("get vat to receive back sql=".$sql); + dol_syslog("get vat to receive back", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -312,7 +313,7 @@ else { $sql.= " AND t.entity = ".$conf->entity; $sql.= " GROUP BY dm"; - dol_syslog("get vat really paid sql=".$sql); + dol_syslog("get vat really paid", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -341,7 +342,7 @@ else { $sql.= " AND t.entity = ".$conf->entity; $sql.= " GROUP BY dm"; - dol_syslog("get vat really received back sql=".$sql); + dol_syslog("get vat really received back", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -391,7 +392,7 @@ else $sql.= " AND cs.entity = ".$conf->entity; $sql.= " GROUP BY c.libelle, dm"; -dol_syslog("get social contributions deductible=0 sql=".$sql); +dol_syslog("get social contributions deductible=0 ", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -441,7 +442,7 @@ else $sql.= " AND cs.entity = ".$conf->entity; $sql.= " GROUP BY c.libelle, dm"; -dol_syslog("get social contributions paid deductible=1 sql=".$sql); +dol_syslog("get social contributions paid deductible=1", LOG_DEBUG); $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -480,7 +481,7 @@ $sql.= " FROM ".MAIN_DB_PREFIX."payment_salary as p"; $sql.= " WHERE p.entity = ".$conf->entity; $sql.= " GROUP BY p.label, dm"; -dol_syslog("get social salaries payments sql=".$sql); +dol_syslog("get social salaries payments"); $result=$db->query($sql); if ($result) { @@ -508,6 +509,45 @@ else dol_print_error($db); } +/* + * get dunning paiement +*/ +$subtotal_ht = 0; +$subtotal_ttc = 0; +$sql = "SELECT p.societe as nom, p.firstname, p.lastname, date_format(p.datedon,'%Y-%m') as dm, sum(p.amount) as amount"; +$sql.= " FROM ".MAIN_DB_PREFIX."don as p"; +$sql.= " WHERE p.entity = ".$conf->entity; +$sql.= " AND fk_statut=2"; +$sql.= " GROUP BY p.societe, p.firstname, p.lastname, dm"; + +dol_syslog("get social salaries payments"); +$result=$db->query($sql); +if ($result) +{ + $num = $db->num_rows($result); + $var=false; + $i = 0; + if ($num) + { + while ($i < $num) + { + $obj = $db->fetch_object($result); + + if (! isset($encaiss[$obj->dm])) $encaiss[$obj->dm]=0; + $encaiss[$obj->dm] += $obj->amount; + + if (! isset($encaiss_ttc[$obj->dm])) $encaiss_ttc[$obj->dm]=0; + $encaiss_ttc[$obj->dm] += $obj->amount; + + $i++; + } + } +} +else +{ + dol_print_error($db); +} + /* * Show result array */ @@ -520,7 +560,7 @@ print ''; for ($annee = $year_start ; $annee <= $year_end ; $annee++) { - print ''; - print ''; + print ''; } print ''; @@ -561,7 +601,7 @@ for ($mois = 1+$nb_mois_decalage ; $mois <= 12+$nb_mois_decalage ; $mois++) } print ""; - print ''; - print ''; + print ''; } print "\n"; @@ -597,7 +637,7 @@ $var=!$var; print ''; for ($annee = $year_start ; $annee <= $year_end ; $annee++) { - print ''; } else @@ -1724,16 +1762,29 @@ else print ""; } + print '
'; - print '
'.$langs->trans("CustomersInvoices").'
 ".$langs->trans("Bills").' '.$objp->nom."".$langs->trans("Bills").' '.$objp->name."".price($objp->amount_ht)."
'.$langs->trans("SuppliersInvoices").'
 ".$langs->trans("Bills")." socid."\">".$objp->nom."".$langs->trans("Bills")." socid."\">".$objp->name."".price(-$objp->amount_ht)."
'.$langs->trans("SocialContributions").' ('.$langs->t if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT c.id, c.libelle as nom, sum(cs.amount) as amount"; + $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE cs.fk_type = c.id"; @@ -388,7 +391,7 @@ if ($modecompta == 'CREANCES-DETTES') } else { - $sql = "SELECT c.id, c.libelle as nom, sum(p.amount) as amount"; + $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -402,7 +405,7 @@ $sql.= " AND cs.entity = ".$conf->entity; $sql.= " GROUP BY c.libelle, c.id"; $sql.= " ORDER BY c.libelle, c.id"; -dol_syslog("get social contributions deductible=0 sql=".$sql); +dol_syslog("get social contributions deductible=0", LOG_DEBUG); $result=$db->query($sql); $subtotal_ht = 0; $subtotal_ttc = 0; @@ -421,7 +424,7 @@ if ($result) { $var = !$var; print "
 '.$obj->nom.''.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
'.$langs->trans("SocialContributions").' ('.$langs->t if ($modecompta == 'CREANCES-DETTES') { - $sql = "SELECT c.id, c.libelle as nom, sum(cs.amount) as amount"; + $sql = "SELECT c.id, c.libelle as label, sum(cs.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " WHERE cs.fk_type = c.id"; @@ -465,7 +468,7 @@ if ($modecompta == 'CREANCES-DETTES') } else { - $sql = "SELECT c.id, c.libelle as nom, sum(p.amount) as amount"; + $sql = "SELECT c.id, c.libelle as label, sum(p.amount) as amount"; $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c"; $sql.= ", ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= ", ".MAIN_DB_PREFIX."paiementcharge as p"; @@ -479,7 +482,7 @@ else $sql.= " ORDER BY c.libelle, c.id"; } -dol_syslog("get social contributions deductible=1 sql=".$sql); +dol_syslog("get social contributions deductible=1", LOG_DEBUG); $result=$db->query($sql); $subtotal_ht = 0; $subtotal_ttc = 0; @@ -498,7 +501,7 @@ if ($result) { $var = !$var; print "
 '.$obj->nom.''.$obj->label.''.price(-$obj->amount).''.price(-$obj->amount).'
'.$langs->trans("Salaries").'
'.$langs->trans("Salaries").'
 ".$langs->trans("Salaries")." fk_user."\">".$obj->firstname." ".$obj->lastname."'.price(-$obj->amount).''.price(-$obj->amount).'
 '.$langs->trans("None").'
 ".$langs->trans("Salaries")." fk_user."\">".$obj->firstname." ".$obj->lastname."'.price(-$obj->amount).''.price(-$obj->amount).'
 '.$langs->trans("None").'
'.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
'.$langs->trans("Donation").'
 ".$langs->trans("Donation")." name."&search_name=".$obj->firstname." ".$obj->lastname."\">".$obj->name. " ".$obj->firstname." ".$obj->lastname."'.price($obj->amount).''.price($obj->amount).'
 '.$langs->trans("None").'
'.price($subtotal_ht).''.price($subtotal_ttc).'
'.price(-$subtotal_ht).''.price(-$subtotal_ttc).'
 '; + print ''; print ''; print $annee; if ($conf->global->SOCIETE_FISCAL_MONTH_START > 1) print '-'.($annee+1); @@ -531,7 +571,7 @@ print '
'.$langs->trans("Month"). for ($annee = $year_start ; $annee <= $year_end ; $annee++) { print ''.$langs->trans("Outcome").''.$langs->trans("Income").''.$langs->trans("Income").'
 '; + print ' '; //if (isset($encaiss_ttc[$case]) && $encaiss_ttc[$case] != 0) if (isset($encaiss_ttc[$case])) { @@ -583,7 +623,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) { $nbcols+=2; print ''.(isset($totsorties[$annee])?price(price2num($totsorties[$annee],'MT')):' ').''.(isset($totentrees[$annee])?price(price2num($totentrees[$annee],'MT')):' ').''.(isset($totentrees[$annee])?price(price2num($totentrees[$annee],'MT')):' ').'
'.$langs->trans("Profit").' '; + print ' '; if (isset($totentrees[$annee]) || isset($totsorties[$annee])) { $in=(isset($totentrees[$annee])?price2num($totentrees[$annee], 'MT'):0); diff --git a/htdocs/compta/salaries/fiche.php b/htdocs/compta/salaries/card.php similarity index 96% rename from htdocs/compta/salaries/fiche.php rename to htdocs/compta/salaries/card.php index c46f83dd6fb..3ee796c6134 100644 --- a/htdocs/compta/salaries/fiche.php +++ b/htdocs/compta/salaries/card.php @@ -17,7 +17,7 @@ */ /** - * \file htdocs/compta/salaries/fiche.php + * \file htdocs/compta/salaries/card.php * \ingroup salaries * \brief Page of salaries payments */ @@ -44,7 +44,7 @@ $result = restrictedArea($user, 'salaries', '', '', ''); $sal = new PaymentSalary($db); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('salarycard')); +$hookmanager->initHooks(array('salarycard','globalcard')); @@ -206,7 +206,7 @@ if ($action == 'create') $datesp=dol_get_first_day($pastmonthyear,$pastmonth,false); $dateep=dol_get_last_day($pastmonthyear,$pastmonth,false); } - print "
\n"; + print "\n"; print ''; print ''; @@ -290,7 +290,7 @@ if ($action == 'create') if ($id) { $h = 0; - $head[$h][0] = DOL_URL_ROOT.'/compta/salaries/fiche.php?id='.$salpayment->id; + $head[$h][0] = DOL_URL_ROOT.'/compta/salaries/card.php?id='.$salpayment->id; $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; @@ -367,7 +367,7 @@ if ($id) { if (! empty($user->rights->tax->charges->supprimer)) { - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; } else { diff --git a/htdocs/compta/salaries/class/index.html b/htdocs/compta/salaries/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/salaries/class/paymentsalary.class.php b/htdocs/compta/salaries/class/paymentsalary.class.php index ecf4b16212b..5e60b76ee13 100644 --- a/htdocs/compta/salaries/class/paymentsalary.class.php +++ b/htdocs/compta/salaries/class/paymentsalary.class.php @@ -1,19 +1,20 @@ + * Copyright (C) 2014 Juanjo Menent * -* This program is free software; you can redistribute it and/or modify -* it under the terms of the GNU General Public License as published by -* the Free Software Foundation; either version 3 of the License, or -* (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU General Public License for more details. -* -* You should have received a copy of the GNU General Public License -* along with this program. If not, see . -*/ + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ /** * \file htdocs/compta/salaries/class/paymentsalary.class.php @@ -72,7 +73,7 @@ class PaymentSalary extends CommonObject * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -114,25 +115,22 @@ class PaymentSalary extends CommonObject $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } if (! $notrigger) { - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_SALARY_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End triggers + // Call trigger + $result=$this->call_trigger('PAYMENT_SALARY_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + + //FIXME: Add rollback if trigger fail } return 1; @@ -146,7 +144,7 @@ class PaymentSalary extends CommonObject * @param User $user User that load * @return int <0 if KO, >0 if OK */ - function fetch($id, $user=0) + function fetch($id, $user=null) { global $langs; $sql = "SELECT"; @@ -174,7 +172,7 @@ class PaymentSalary extends CommonObject $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON s.fk_bank = b.rowid"; $sql.= " WHERE s.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -209,7 +207,6 @@ class PaymentSalary extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -227,27 +224,23 @@ class PaymentSalary extends CommonObject $error=0; + // Call trigger + $result=$this->call_trigger('PAYMENT_SALARY_DELETE',$user); + if ($result < 0) return -1; + // End call triggers + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_salary"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -1; } - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_SALARY_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End triggers - return 1; } @@ -287,6 +280,8 @@ class PaymentSalary extends CommonObject { global $conf,$langs; + $error=0; + // Clean parameters $this->amount=price2num(trim($this->amount)); $this->label=trim($this->label); @@ -355,11 +350,10 @@ class PaymentSalary extends CommonObject $sql.= ", ".$conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { - $ok=1; $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_salary"); @@ -395,19 +389,19 @@ class PaymentSalary extends CommonObject else { $this->error=$acc->error; - $ok=0; + $error++; } - if ($ok) + if (! $error) { // Add link 'payment_salary' in bank_url between payment and bank transaction - $url=DOL_URL_ROOT.'/compta/salaries/fiche.php?id='; + $url=DOL_URL_ROOT.'/compta/salaries/card.php?id='; $result=$acc->add_url_line($bank_line_id, $this->id, $url, "(SalaryPayment)", "payment_salary"); if ($result <= 0) { $this->error=$acc->error; - $ok=0; + $error++; } } @@ -418,47 +412,33 @@ class PaymentSalary extends CommonObject $result=$acc->add_url_line( $bank_line_id, $this->fk_user, - DOL_URL_ROOT.'/user/fiche.php?id=', + DOL_URL_ROOT.'/user/card.php?id=', $langs->trans("SalaryPayment").' '.$fuser->getFullName($langs).' '.dol_print_date($this->datesp,'dayrfc').' '.dol_print_date($this->dateep,'dayrfc'), - '(User)', 'user' ); if ($result <= 0) { $this->error=$acc->error; - $ok=0; + $error++; } } - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_SALARY_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End triggers + // Call trigger + $result=$this->call_trigger('PAYMENT_SALARY_CREATE',$user); + if ($result < 0) $error++; + // End call triggers } - else $ok=0; + else $error++; - if ($ok) + if (! $error) { - if ($ok) - { - $this->db->commit(); - return $this->id; - } - else - { - $this->db->rollback(); - return -3; - } + $this->db->commit(); + return $this->id; } else { - $this->error=$this->db->error(); $this->db->rollback(); return -2; } @@ -507,7 +487,7 @@ class PaymentSalary extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='payment'; diff --git a/htdocs/compta/salaries/index.php b/htdocs/compta/salaries/index.php index 3567263e802..678b3bfaa2e 100644 --- a/htdocs/compta/salaries/index.php +++ b/htdocs/compta/salaries/index.php @@ -33,6 +33,9 @@ $socid = GETPOST("socid","int"); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'salaries', '', '', ''); +$search_ref = GETPOST('search_ref','int'); +$search_label = GETPOST('search_label','alpha'); +$search_amount = GETPOST('search_amount','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -61,6 +64,14 @@ else $typeid=$_REQUEST['typeid']; } +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_label=""; + $search_amount=""; + $typeid=""; +} + /* * View */ @@ -78,8 +89,11 @@ $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON s.fk_typepayment = pst $sql.= " ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE u.rowid = s.fk_user"; $sql.= " AND s.entity = ".$conf->entity; -if (GETPOST("search_label")) $sql.=" AND s.label LIKE '%".$db->escape(GETPOST("search_label"))."%'"; -if (GETPOST("search_amount")) $sql.=" AND s.amount = ".price2num(GETPOST("search_amount")); + +// Search criteria +if ($search_ref) $sql.=" AND s.rowid=".$search_ref; +if ($search_label) $sql.=" AND s.label LIKE '%".$db->escape($search_label)."%'"; +if ($search_amount) $sql.=" AND s.amount='".$db->escape(price2num(trim($search_amount)))."'"; if ($filtre) { $filtre=str_replace(":","=",$filtre); $sql .= " AND ".$filtre; @@ -104,8 +118,6 @@ if ($result) print_barre_liste($langs->trans("SalariesPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$totalnboflines); - dol_htmloutput_mesg($mesg); - print ''; print ''; @@ -120,19 +132,23 @@ if ($result) print "\n"; print ''; + // Ref + print ''; print ''; - print ''; - print ''; + // Label + print ''; print ''; // Type print ''; - print ''; - print ''; - print "\n"; + // Amount + print ''; + print '\n"; while ($i < min($num,$limit)) { diff --git a/htdocs/compta/sociales/charges.php b/htdocs/compta/sociales/charges.php index 4ea2af2c20f..afe2c27a3be 100644 --- a/htdocs/compta/sociales/charges.php +++ b/htdocs/compta/sociales/charges.php @@ -69,7 +69,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes') } else { - $mesg='
'.$chargesociales->error.'
'; + setEventMessage($chargesociales->error, 'errors'); } } @@ -81,22 +81,22 @@ if ($action == 'add' && $user->rights->tax->charges->creer) $dateperiod=@dol_mktime($_POST["periodhour"],$_POST["periodmin"],$_POST["periodsec"],$_POST["periodmonth"],$_POST["periodday"],$_POST["periodyear"]); if (! $dateech) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("DateDue")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("DateDue")), 'errors'); $action = 'create'; } elseif (! $dateperiod) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Period")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Period")), 'errors'); $action = 'create'; } elseif (! $_POST["actioncode"] > 0) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Type")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Type")), 'errors'); $action = 'create'; } elseif (! $_POST["amount"]) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Amount")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Amount")), 'errors'); $action = 'create'; } else @@ -110,13 +110,9 @@ if ($action == 'add' && $user->rights->tax->charges->creer) $chargesociales->amount=$_POST["amount"]; $id=$chargesociales->create($user); - if ($id > 0) + if ($id <= 0) { - //$mesg='
'.$langs->trans("SocialContributionAdded").'
'; - } - else - { - $mesg='
'.$chargesociales->error.'
'; + setEventMessage($chargesociales->error, 'errors'); } } } @@ -128,12 +124,12 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->tax->charges->cr $dateperiod=dol_mktime($_POST["periodhour"],$_POST["periodmin"],$_POST["periodsec"],$_POST["periodmonth"],$_POST["periodday"],$_POST["periodyear"]); if (! $dateech) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("DateDue")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("DateDue")), 'errors'); $action = 'edit'; } elseif (! $dateperiod) { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Period")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Period")), 'errors'); $action = 'edit'; } else @@ -146,17 +142,64 @@ if ($action == 'update' && ! $_POST["cancel"] && $user->rights->tax->charges->cr $chargesociales->periode=$dateperiod; $result=$chargesociales->update($user); - if ($result > 0) + if ($result <= 0) { - //$mesg='
'.$langs->trans("SocialContributionAdded").'
'; - } - else - { - $mesg='
'.$chargesociales->error.'
'; + setEventMessage($chargesociales->error, 'errors'); } } } + // Action clone object +if ($action == 'confirm_clone' && $confirm != 'yes') { $action=''; } +if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->tax->charges->creer)) +{ + $db->begin(); + + $originalId = $id; + + $object = new ChargeSociales($db); + $object->fetch($id); + + if ($object->id > 0) + { + $object->paye = 0; + $object->id = $object->ref = null; + + if(GETPOST('clone_for_next_month') != '') { + + $object->date_ech = strtotime('+1month', $object->date_ech); + $object->periode = strtotime('+1month', $object->periode); + } + + if ($object->check()) + { + $id = $object->create($user); + if ($id > 0) + { + $db->commit(); + $db->close(); + + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } + else + { + $id=$originalId; + $db->rollback(); + + setEventMessages($object->error,$object->errors, 'errors'); + } + } + } + else + { + $db->rollback(); + dol_print_error($db,$object->error); + } +} + + + /* @@ -176,8 +219,6 @@ if ($action == 'create') print_fiche_titre($langs->trans("NewSocialContribution")); print "
\n"; - dol_htmloutput_mesg($mesg); - $var=false; print ''; @@ -246,12 +287,21 @@ if ($id > 0) if ($result > 0) { - dol_htmloutput_mesg($mesg); - $head=tax_prepare_head($object); dol_fiche_head($head, 'card', $langs->trans("SocialContribution"),0,'bill'); + // Clone confirmation + if ($action === 'clone') + { + $formclone=array( + array('type' => 'checkbox', 'name' => 'clone_for_next_month','label' => $langs->trans("CloneTaxForNextMonth"), 'value' => 1), + + ); + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneTax'),$langs->trans('ConfirmCloneTax',$object->ref),'confirm_clone',$formclone,'yes'); + } + // Confirmation de la suppression de la charge if ($action == 'paid') { @@ -331,7 +381,7 @@ if ($id > 0) $objp = $db->fetch_object($resql); $var=!$var; print "'; + 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"; @@ -433,6 +483,12 @@ if ($id > 0) print "id&action=paid\">".$langs->trans("ClassifyPaid").""; } + // Clone + if ($user->rights->tax->charges->creer) + { + print "id&action=clone\">".$langs->trans("ToClone").""; + } + // Delete if ($user->rights->tax->charges->supprimer) { diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index 6404d9f26c8..fb8bc162c83 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -62,19 +62,21 @@ class ChargeSociales extends CommonObject /** * Retrouve et charge une charge sociale * - * @param int $id 1 si trouve, 0 sinon + * @param int $id Id + * @param string $ref Ref * @return void */ - function fetch($id) + function fetch($id, $ref='') { $sql = "SELECT cs.rowid, cs.date_ech,"; $sql.= " cs.libelle as lib, cs.fk_type, cs.amount, cs.paye, cs.periode,"; $sql.= " c.libelle"; $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as cs, ".MAIN_DB_PREFIX."c_chargesociales as c"; $sql.= " WHERE cs.fk_type = c.id"; - $sql.= " AND cs.rowid = ".$id; + if ($ref) $sql.= " AND cs.rowid = ".$ref; + else $sql.= " AND cs.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -107,6 +109,24 @@ class ChargeSociales extends CommonObject } } + /** + * Check if a social contribution can be created into database + * + * @return boolean True or false + */ + function check() + { + $newamount=price2num($this->amount,'MT'); + + // Validation parametres + if (! $newamount > 0 || empty($this->date_ech) || empty($this->periode)) + { + return false; + } + + + return true; + } /** * Create a social contribution into database @@ -121,12 +141,12 @@ class ChargeSociales extends CommonObject // Nettoyage parametres $newamount=price2num($this->amount,'MT'); - // Validation parametres - if (! $newamount > 0 || empty($this->date_ech) || empty($this->periode)) - { - $this->error="ErrorBadParameter"; - return -2; - } + if (!$this->check()) + { + $this->error="ErrorBadParameter"; + return -2; + } + $this->db->begin(); @@ -137,7 +157,7 @@ class ChargeSociales extends CommonObject $sql.= " ".$conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -192,7 +212,7 @@ class ChargeSociales extends CommonObject if (! $error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."paiementcharge where fk_charge='".$this->id."'"; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -204,7 +224,7 @@ class ChargeSociales extends CommonObject if (! $error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."chargesociales where rowid='".$this->id."'"; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -243,7 +263,7 @@ class ChargeSociales extends CommonObject $sql.= " periode='".$this->db->idate($this->periode)."'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -341,7 +361,7 @@ class ChargeSociales extends CommonObject global $langs; $langs->load('customers'); $langs->load('bills'); - + if ($mode == 0) { if ($statut == 0) return $langs->trans("Unpaid"); @@ -419,7 +439,7 @@ class ChargeSociales extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.$table; $sql.= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -449,7 +469,7 @@ class ChargeSociales extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."chargesociales as e"; $sql.= " WHERE e.rowid = ".$id; - dol_syslog(get_class($this)."::info sql=".$sql); + dol_syslog(get_class($this)."::info", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { diff --git a/htdocs/compta/sociales/class/index.html b/htdocs/compta/sociales/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index e89f2a273f8..395932de69f 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -116,7 +116,7 @@ class PaymentSocialContribution extends CommonObject $sql.= " ".$this->paiementtype.", '".$this->db->escape($this->num_paiement)."', '".$this->db->escape($this->note)."', ".$user->id.","; $sql.= " 0)"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -139,7 +139,6 @@ class PaymentSocialContribution extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -173,7 +172,7 @@ class PaymentSocialContribution extends CommonObject $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; $sql.= " WHERE t.rowid = ".$id." AND t.fk_typepaiement = pt.id"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -209,7 +208,6 @@ class PaymentSocialContribution extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -222,7 +220,7 @@ class PaymentSocialContribution extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -263,7 +261,7 @@ class PaymentSocialContribution extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -321,7 +319,7 @@ class PaymentSocialContribution extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; $sql.= " WHERE type='payment_sc' AND url_id=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } @@ -331,7 +329,7 @@ class PaymentSocialContribution extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."paiementcharge"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } @@ -508,7 +506,7 @@ class PaymentSocialContribution extends CommonObject // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction $url=''; - if ($mode == 'payment_sc') $url=DOL_URL_ROOT.'/compta/payment_sc/fiche.php?id='; + if ($mode == 'payment_sc') $url=DOL_URL_ROOT.'/compta/payment_sc/card.php?id='; if ($url) { $result=$acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); @@ -560,7 +558,7 @@ class PaymentSocialContribution extends CommonObject { $sql = "UPDATE ".MAIN_DB_PREFIX."paiementcharge SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update_fk_bank sql=".$sql); + dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -569,7 +567,6 @@ class PaymentSocialContribution extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update_fk_bank ".$this->error, LOG_ERR); return 0; } } @@ -591,7 +588,7 @@ class PaymentSocialContribution extends CommonObject if (!empty($this->id)) { - $lien = ''; + $lien = ''; $lienfin=''; if ($withpicto) $result.=($lien.img_object($langs->trans("ShowPayment").': '.$this->ref,'payment').$lienfin.' '); diff --git a/htdocs/compta/sociales/index.php b/htdocs/compta/sociales/index.php index e7f0d3a2b1b..31e98370003 100644 --- a/htdocs/compta/sociales/index.php +++ b/htdocs/compta/sociales/index.php @@ -36,6 +36,9 @@ $socid = isset($_GET["socid"])?$_GET["socid"]:''; if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); +$search_ref = GETPOST('search_ref','int'); +$search_label = GETPOST('search_label','alpha'); +$search_amount = GETPOST('search_amount','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -65,6 +68,15 @@ else $typeid=$_REQUEST['typeid']; } +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_label=""; + $search_amount=""; + $typeid=""; + $year=""; + $month=""; +} /* * View @@ -85,7 +97,11 @@ $sql.= " ".MAIN_DB_PREFIX."chargesociales as cs"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; $sql.= " WHERE cs.fk_type = c.id"; $sql.= " AND cs.entity = ".$conf->entity; -if (GETPOST("search_label")) $sql.=" AND cs.libelle LIKE '%".$db->escape(GETPOST("search_label"))."%'"; + +// Search criteria +if ($search_ref) $sql.=" AND cs.rowid=".$search_ref; +if ($search_label) $sql.=" AND cs.libelle LIKE '%".$db->escape($search_label)."%'"; +if ($search_amount) $sql.=" AND cs.amount='".$db->escape(price2num(trim($search_amount)))."'"; if ($year > 0) { $sql .= " AND ("; @@ -127,10 +143,6 @@ if ($resql) print_barre_liste($langs->trans("SocialContributions"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$totalnboflines); } - - dol_htmloutput_mesg($mesg); - - if (empty($mysoc->country_id) && empty($mysoc->country_code)) { print '
'; @@ -143,10 +155,8 @@ if ($resql) { print ''; - - print "
'; + print ''; + print '   '; $form->select_types_paiements($typeid,'typeid','',0,0,1,16); print ''; - print ''; - print '
'; + print ''; + print "
"; - print ''.img_object($langs->trans("Payment"),"payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp),'day')."".$labeltype.' '.$objp->num_paiement."
"; - - print ""; + print '
'; + print ''; print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"id","",$param,"",$sortfield,$sortorder); print_liste_field_titre($langs->trans("Label"),$_SERVER["PHP_SELF"],"cs.libelle","",$param,'align="left"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); @@ -157,20 +167,26 @@ if ($resql) print "\n"; print ''; - print ''; - print ''; + // Ref + print ''; + // Label + print ''; // Type print ''; // Period end date print ''; - print ''; - print ''; + // Amount print ''; - print "\n"; + print ''; + print '\n"; while ($i < min($num,$limit)) { diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index 2b2ad5be02f..8263dc76cb8 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -39,7 +39,7 @@ if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user,'compta' if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accounting','','','comptarapport'); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta = $conf->global->COMPTA_MODE; +$modecompta = $conf->global->ACCOUNTING_MODE; if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); $sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"]; @@ -132,6 +132,8 @@ $tableparams = array_merge($commonparams, $tableparams); foreach($allparams as $key => $value) { $paramslink .= '&' . $key . '=' . $value; } + + /* * View */ @@ -174,12 +176,12 @@ report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportl // SQL request $catotal=0; -if ($modecompta == 'CREANCES-DETTES') +if ($modecompta == 'CREANCES-DETTES') { $sql = "SELECT DISTINCT p.rowid as rowid, p.ref as ref, p.label as label,"; $sql.= " sum(l.total_ht) as amount, sum(l.total_ttc) as amount_ttc"; $sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as l, ".MAIN_DB_PREFIX."product as p"; - if ($selected_cat === -2) // Without any category + if ($selected_cat === -2) // Without any category { $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON p.rowid = cp.fk_product"; } @@ -198,7 +200,7 @@ if ($modecompta == 'CREANCES-DETTES') if ($date_start && $date_end) { $sql.= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; } - if ($selected_cat === -2) // Without any category + if ($selected_cat === -2) // Without any category { $sql.=" AND cp.fk_product is null"; } @@ -209,10 +211,10 @@ if ($modecompta == 'CREANCES-DETTES') $sql.= " AND cp.fk_categorie = c.rowid AND cp.fk_product = p.rowid"; } $sql.= " AND f.entity = ".$conf->entity; - $sql.= " GROUP BY p.rowid"; + $sql.= " GROUP BY p.rowid, p.ref, p.label"; $sql.= " ORDER BY p.ref"; - dol_syslog("cabyprodserv sql=".$sql); + dol_syslog("cabyprodserv", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -336,7 +338,7 @@ if ($modecompta == 'CREANCES-DETTES') // Product $fullname=$name[$key]; if ($key >= 0) { - $linkname=''.img_object($langs->trans("ShowProduct"),'product').' '.$fullname.''; + $linkname=''.img_object($langs->trans("ShowProduct"),'product').' '.$fullname.''; } else { $linkname=$langs->trans("PaymentsNotLinkedToProduct"); } @@ -390,7 +392,7 @@ if ($modecompta == 'CREANCES-DETTES') // $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. + // Because there is no way to know this, this report is not relevant. print '
'.$langs->trans("TurnoverPerProductInCommitmentAccountingNotRelevant") . '
'; } diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index 708c77708cf..e88d370a0c6 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -36,7 +36,7 @@ if (! empty($conf->comptabilite->enabled)) $result=restrictedArea($user,'compta' if (! empty($conf->accounting->enabled)) $result=restrictedArea($user,'accounting','','','comptarapport'); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta = $conf->global->COMPTA_MODE; +$modecompta = $conf->global->ACCOUNTING_MODE; if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); $sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"]; @@ -348,7 +348,7 @@ if (count($amount)) { // Third party $fullname=$name[$key]; if ($key >= 0) { - $linkname=''.img_object($langs->trans("ShowUser"),'user').' '.$fullname.''; + $linkname=''.img_object($langs->trans("ShowUser"),'user').' '.$fullname.''; } else { $linkname=$langs->trans("PaymentsNotLinkedToUser"); } @@ -359,9 +359,9 @@ if (count($amount)) { if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { - print ''; + print ''; } else { - print ''; + print ''; } } else { if ($key > 0) { @@ -377,9 +377,9 @@ if (count($amount)) { print ''; for ($annee = $year_start ; $annee <= $year_end ; $annee++) { if ($modecompta == 'CREANCES-DETTES') print ''; print ''; - print ''; + print ''; if ($annee != $year_end) print ''; } print ''; @@ -244,7 +244,7 @@ for ($mois = 1+$nb_mois_decalage ; $mois <= 12+$nb_mois_decalage ; $mois++) } print ""; } - + // Valeur CA du mois print ''; + print ''; } if ($cum[$caseprev] && ! $cum[$case]) { - print ''; + print ''; } if (! $cum[$caseprev] && $cum[$case]) { //print ''; - print ''; + print ''; } if (isset($cum[$caseprev]) && ! $cum[$caseprev] && ! $cum[$case]) { - print ''; + print ''; } if (! isset($cum[$caseprev]) && ! $cum[$case]) { - print ''; + print ''; } } else { - print ''; @@ -382,7 +382,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) print ''; } } - + // Montant total if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear,$maxyear))) { @@ -398,24 +398,24 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) { if ($total[$annee-1] && $total[$annee]) { $percent=(round(($total[$annee]-$total[$annee-1])/$total[$annee-1],4)*100); - print ''; + print ''; } if ($total[$annee-1] && ! $total[$annee]) { - print ''; + print ''; } if (! $total[$annee-1] && $total[$annee]) { - print ''; + print ''; } if (! $total[$annee-1] && ! $total[$annee]) { - print ''; + print ''; } } else { - print ''; diff --git a/htdocs/compta/tva/fiche.php b/htdocs/compta/tva/card.php similarity index 96% rename from htdocs/compta/tva/fiche.php rename to htdocs/compta/tva/card.php index a4a5a8831c4..268a1af8e66 100644 --- a/htdocs/compta/tva/fiche.php +++ b/htdocs/compta/tva/card.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/compta/tva/fiche.php + * \file htdocs/compta/tva/card.php * \ingroup tax * \brief Page of VAT payments */ @@ -42,7 +42,7 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); $tva = new Tva($db); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('taxvatcard')); +$hookmanager->initHooks(array('taxvatcard','globalcard')); @@ -181,7 +181,7 @@ if ($id) // Formulaire saisie tva if ($action == 'create') { - print "\n"; + print "\n"; print ''; print ''; @@ -246,7 +246,7 @@ if ($action == 'create') if ($id) { $h = 0; - $head[$h][0] = DOL_URL_ROOT.'/compta/tva/fiche.php?id='.$vatpayment->id; + $head[$h][0] = DOL_URL_ROOT.'/compta/tva/card.php?id='.$vatpayment->id; $head[$h][1] = $langs->trans('Card'); $head[$h][2] = 'card'; $h++; @@ -307,7 +307,7 @@ if ($id) { if (! empty($user->rights->tax->charges->supprimer)) { - print ''.$langs->trans("Delete").''; + print ''.$langs->trans("Delete").''; } else { diff --git a/htdocs/compta/tva/class/index.html b/htdocs/compta/tva/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index c605c97fed9..a86af28cace 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -115,37 +115,35 @@ class Tva extends CommonObject $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('TVA_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End triggers + // Call trigger + $result=$this->call_trigger('TVA_CREATE',$user); + if ($result < 0) $error++; + // End call triggers + //FIXME: Add rollback if trigger fail return $this->id; } else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } } /** * Update database - * + * * @param User $user User that modify * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -178,23 +176,22 @@ class Tva extends CommonObject $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } if (! $notrigger) { - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('TVA_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End triggers + // Call trigger + $result=$this->call_trigger('TVA_MODIFY',$user); + if ($result < 0) $error++; + // End call triggers + + //FIXME: Add rollback if trigger fail } return 1; @@ -203,12 +200,12 @@ class Tva extends CommonObject /** * Load object in memory from database - * + * * @param int $id id object * @param User $user User that load * @return int <0 if KO, >0 if OK */ - function fetch($id, $user=0) + function fetch($id, $user=null) { global $langs; $sql = "SELECT"; @@ -233,7 +230,7 @@ class Tva extends CommonObject $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -265,7 +262,6 @@ class Tva extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -273,7 +269,7 @@ class Tva extends CommonObject /** * Delete object in database - * + * * @param User $user User that delete * @return int <0 if KO, >0 if OK */ @@ -283,24 +279,22 @@ class Tva extends CommonObject $error=0; + // Call trigger + $result=$this->call_trigger('TVA_DELETE',$user); + if ($result < 0) return -1; + // End call triggers + $sql = "DELETE FROM ".MAIN_DB_PREFIX."tva"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -1; } - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('TVA_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End triggers return 1; } @@ -331,7 +325,7 @@ class Tva extends CommonObject /** * Balance of VAT - * + * * @param int $year Year * @return double Amount */ @@ -350,7 +344,7 @@ class Tva extends CommonObject /** * Total of the VAT from invoices emitted by the society. - * + * * @param int $year Year * @return double Amount */ @@ -359,32 +353,30 @@ class Tva extends CommonObject $sql = "SELECT sum(f.tva) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) { $sql .= " AND f.datef >= '".$year."-01-01' AND f.datef <= '".$year."-12-31' "; } $result = $this->db->query($sql); - if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->amount; + $ret = $obj->amount; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free($result); - } else { - print $this->db->error(); + print $this->db->lasterror(); return -1; } } @@ -400,31 +392,30 @@ class Tva extends CommonObject $sql = "SELECT sum(f.total_tva) as total_tva"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) { $sql .= " WHERE f.datef >= '".$year."-01-01' AND f.datef <= '".$year."-12-31' "; } - $result = $this->db->query($sql); + $result = $this->db->query($sql); if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->total_tva; + $ret = $obj->total_tva; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free(); - } else { - print $this->db->error(); + print $this->db->lasterror(); return -1; } } @@ -448,25 +439,24 @@ class Tva extends CommonObject } $result = $this->db->query($sql); - if ($result) { if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); - return $obj->amount; + $ret = $obj->amount; + $this->db->free($result); + return $ret; } else - { - return 0; + { + $this->db->free($result); + return 0; } - - $this->db->free(); - } else { - print $this->db->error(); + print $this->db->lasterror(); return -1; } } @@ -491,7 +481,7 @@ class Tva extends CommonObject $this->fk_bank=trim($this->fk_bank); $this->fk_user_creat=trim($this->fk_user_creat); $this->fk_user_modif=trim($this->fk_user_modif); - + // Check parameters if (! $this->label) { @@ -539,18 +529,21 @@ class Tva extends CommonObject $sql.= ", ".$conf->entity; $sql.= ")"; - dol_syslog(get_class($this)."::addPayment sql=".$sql); + dol_syslog(get_class($this)."::addPayment", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called paiementtva - // Start triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('TVA_ADDPAYMENT',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End triggers + // Call trigger + //XXX: Should be done just befor commit no ? + $result=$this->call_trigger('TVA_ADDPAYMENT',$user); + if ($result < 0) + { + $this->id = 0; + $ok = 0; + } + // End call triggers if ($this->id > 0) { @@ -578,7 +571,7 @@ class Tva extends CommonObject } // Update links - $result=$acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/fiche.php?id=', "(VATPayment)", "payment_vat"); + $result=$acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', "(VATPayment)", "payment_vat"); if ($result < 0) { $this->error=$acc->error; @@ -599,7 +592,6 @@ class Tva extends CommonObject } else { - $this->error=$this->db->error(); $this->db->rollback(); return -2; } @@ -647,7 +639,7 @@ class Tva extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='payment'; diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index 422354ee7c3..c2620fd34df 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -110,10 +110,10 @@ $fsearch.=' '; // Affiche en-tete du rapport if ($modetax==1) // Calculate on invoice for goods and services { - $nom=$langs->trans("VATReportByCustomersInDueDebtMode"); + $name=$langs->trans("VATReportByCustomersInDueDebtMode"); $calcmode=$langs->trans("CalcModeVATDebt"); $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - //$nom.='
('.$langs->trans("SeeVATReportInInputOutputMode",'','').')'; + //$name.='
('.$langs->trans("SeeVATReportInInputOutputMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink=($year_start?"".img_previous()."".img_next()."":""); $description=$langs->trans("RulesVATDueServices"); @@ -138,10 +138,10 @@ if ($modetax==1) // Calculate on invoice for goods and services } if ($modetax==0) // Invoice for goods, payment for services { - $nom=$langs->trans("VATReportByCustomersInInputOutputMode"); + $name=$langs->trans("VATReportByCustomersInInputOutputMode"); $calcmode=$langs->trans("CalcModeVATEngagement"); $calcmode.='
('.$langs->trans("TaxModuleSetupToModifyRules",DOL_URL_ROOT.'/admin/taxes.php').')'; - //$nom.='
('.$langs->trans("SeeVATReportInDueDebtMode",'','').')'; + //$name.='
('.$langs->trans("SeeVATReportInDueDebtMode",'','').')'; $period=$form->select_date($date_start,'date_start',0,0,0,'',1,0,1).' - '.$form->select_date($date_end,'date_end',0,0,0,'',1,0,1); //$periodlink=($year_start?"".img_previous()."".img_next()."":""); $description=$langs->trans("RulesVATInServices"); @@ -165,7 +165,7 @@ if ($modetax==0) // Invoice for goods, payment for services $amountsup=$langs->trans("AmountHT"); if ($mysoc->tva_assuj) $vatsup.=' ('.$langs->trans("ToGetBack").')'; } -report_header($nom,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); +report_header($name,$nomlink,$period,$periodlink,$description,$builddate,$exportlink,array(),$calcmode); $vatcust=$langs->trans("VATReceived"); $vatsup=$langs->trans("VATPaid"); @@ -223,7 +223,7 @@ if (is_array($coll_list)) print ""; print '"; $company_static->id=$coll->socid; - $company_static->nom=$coll->nom; + $company_static->name=$coll->name; $company_static->client=1; print ''; $find = array(' ','.'); @@ -304,7 +304,7 @@ if (is_array($coll_list)) print ""; print '"; $company_static->id=$coll->socid; - $company_static->nom=$coll->nom; + $company_static->name=$coll->name; $company_static->fournisseur=1; print ''; $find = array(' ','.'); diff --git a/htdocs/compta/tva/quadri.php b/htdocs/compta/tva/quadri.php index 0e22dc77f1b..f5d0065e7f3 100644 --- a/htdocs/compta/tva/quadri.php +++ b/htdocs/compta/tva/quadri.php @@ -60,7 +60,7 @@ function tva_coll($db,$y,$q) { global $conf; - if ($conf->global->COMPTA_MODE == "CREANCES-DETTES") + if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") { // if vat paid on due invoices $sql = "SELECT d.fk_facture as facid, f.facnumber as facnum, d.tva_tx as rate, d.total_ht as totalht, d.total_tva as amount"; @@ -128,7 +128,7 @@ function tva_paye($db, $y,$q) { global $conf; - if ($conf->global->COMPTA_MODE == "CREANCES-DETTES") + if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") { // Si on paye la tva sur les factures dues (non brouillon) $sql = "SELECT d.fk_facture_fourn as facid, f.facnumber as facnum, d.tva_tx as rate, d.total_ht as totalht, d.tva as amount"; @@ -212,7 +212,7 @@ print ""; print ""; print "\n"; -if ($conf->global->COMPTA_MODE == "CREANCES-DETTES") +if ($conf->global->ACCOUNTING_MODE == "CREANCES-DETTES") { $y = $year_current; @@ -250,7 +250,7 @@ if ($conf->global->COMPTA_MODE == "CREANCES-DETTES") } $x_both[$my_paye_rate]['paye']['links'] = ''; foreach($x_paye[$my_paye_rate]['facid'] as $id=>$dummy){ - $x_both[$my_paye_rate]['paye']['links'] .= '..'.substr($x_paye[$my_paye_rate]['facnum'][$id],-2).' '; + $x_both[$my_paye_rate]['paye']['links'] .= '..'.substr($x_paye[$my_paye_rate]['facnum'][$id],-2).' '; } } //now we have an array (x_both) indexed by rates for coll and paye diff --git a/htdocs/compta/tva/reglement.php b/htdocs/compta/tva/reglement.php index c10f7f4509c..45a69076492 100644 --- a/htdocs/compta/tva/reglement.php +++ b/htdocs/compta/tva/reglement.php @@ -35,6 +35,9 @@ $socid = isset($_GET["socid"])?$_GET["socid"]:''; if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'tax', '', '', 'charges'); +$search_ref = GETPOST('search_ref','int'); +$search_label = GETPOST('search_label','alpha'); +$search_amount = GETPOST('search_amount','alpha'); $sortfield = GETPOST("sortfield",'alpha'); $sortorder = GETPOST("sortorder",'alpha'); $page = GETPOST("page",'int'); @@ -63,6 +66,14 @@ else $typeid=$_REQUEST['typeid']; } +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_label=""; + $search_amount=""; + $typeid=""; +} + /* * View */ @@ -76,8 +87,9 @@ $sql = "SELECT t.rowid, t.amount, t.label, t.datev as dm, t.fk_typepayment as ty $sql.= " FROM ".MAIN_DB_PREFIX."tva as t"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pst ON t.fk_typepayment = pst.id"; $sql.= " WHERE t.entity = ".$conf->entity; -if (GETPOST("search_label")) $sql.=" AND t.label LIKE '%".$db->escape(GETPOST("search_label"))."%'"; -if (GETPOST("search_amount")) $sql.=" AND t.amount = ".price2num(GETPOST("search_amount")); +if ($search_ref) $sql.=" AND t.rowid=".$search_ref; +if ($search_label) $sql.=" AND t.label LIKE '%".$db->escape($search_label)."%'"; +if ($search_amount) $sql.=" AND t.amount='".$db->escape(price2num(trim($search_amount)))."'"; if ($filtre) { $filtre=str_replace(":","=",$filtre); $sql .= " AND ".$filtre; @@ -85,7 +97,6 @@ if ($filtre) { if ($typeid) { $sql .= " AND t.fk_typepayment=".$typeid; } -$sql.= " GROUP BY t.rowid, t.fk_typepayment, t.amount, t.datev, t.label"; $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit+1,$offset); @@ -99,51 +110,48 @@ if ($result) $param=''; if ($typeid) $param.='&typeid='.$typeid; - + print_barre_liste($langs->trans("VATPayments"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$totalnboflines); - dol_htmloutput_mesg($mesg); - print ''; print '
 '; + print ''; + print ''; $formsocialcontrib->select_type_socialcontrib($typeid,'typeid',1,16,0); print '   '; - print ''; + print ''; print '
 '; + print ''; + print "
'; if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { - print ''; + print ''; } else { - print ''; + print ''; } } else { if ($key > 0) { diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index fd4afbfdf01..1d34f78a181 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -34,7 +34,7 @@ $langs->load("companies"); $langs->load("categories"); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta = $conf->global->COMPTA_MODE; +$modecompta = $conf->global->ACCOUNTING_MODE; if (GETPOST("modecompta")) $modecompta=GETPOST("modecompta"); $sortorder=isset($_GET["sortorder"])?$_GET["sortorder"]:$_POST["sortorder"]; @@ -250,7 +250,7 @@ $sql.= " GROUP BY s.rowid, s.nom"; $sql.= " ORDER BY s.rowid"; //echo $sql; -dol_syslog("casoc sql=".$sql); +dol_syslog("casoc", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); @@ -429,9 +429,9 @@ if (count($amount)) { print ''; if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { - print ''; + print ''; } else { - print ''; + print ''; } } else { if ($key > 0) { @@ -447,9 +447,9 @@ if (count($amount)) { print ''; if ($modecompta != 'CREANCES-DETTES') { if ($key > 0) { - print ''; + print ''; } else { - print ''; + print ''; } } else { if ($key > 0) { diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 59a7e478f9b..b3fb130e185 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -38,7 +38,7 @@ else { $userid=GETPOST('userid','int'); $socid = GETPOST('socid','int'); // Define modecompta ('CREANCES-DETTES' or 'RECETTES-DEPENSES') -$modecompta = $conf->global->COMPTA_MODE; +$modecompta = $conf->global->ACCOUNTING_MODE; if ($_GET["modecompta"]) $modecompta=$_GET["modecompta"]; // Security check @@ -184,7 +184,7 @@ print '
 '; - else print ''; + else print ''; print ''; print $annee; if ($conf->global->SOCIETE_FISCAL_MONTH_START > 1) print '-'.($annee+1); @@ -198,7 +198,7 @@ for ($annee = $year_start ; $annee <= $year_end ; $annee++) { if ($modecompta == 'CREANCES-DETTES') print ''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("Delta").''.$langs->trans("Delta").' 
'; if ($cum[$case]) @@ -266,29 +266,29 @@ for ($mois = 1+$nb_mois_decalage ; $mois <= 12+$nb_mois_decalage ; $mois++) { $percent=(round(($cum[$case]-$cum[$caseprev])/$cum[$caseprev],4)*100); //print "X $cum[$case] - $cum[$caseprev] - $cum[$caseprev] - $percent X"; - print ''.($percent>=0?"+$percent":"$percent").'%'.($percent>=0?"+$percent":"$percent").'%-100%-100%+Inf%--+0%+0%--'; + print ''; if ($minyearmonth <= $case && $case <= $maxyearmonth) { print '-'; } else { print ' '; } print ' '.($percent>=0?"+$percent":"$percent").'%'.($percent>=0?"+$percent":"$percent").'%-100%-100%+Inf%+Inf%+0%+0%'; + print ''; if ($total[$annee] || ($minyear <= $annee && $annee <= max($nowyear,$maxyear))) { print '-'; } else { print ' '; } print '
'.$i."'.$company_static->getNomUrl(1,'customer').'
'.$i."'.$company_static->getNomUrl(1,'supplier').'".$langs->trans("Invoices")."".$langs->trans("TotalToPay")."
'; print ''; - print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"t.rowid","",$param,"",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Label"),$_SERVER["PHP_SELF"],"t.label","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("DatePayment"),$_SERVER["PHP_SELF"],"dm","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("PayedByThisPayment"),$_SERVER["PHP_SELF"],"t.amount","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre(""); + print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"t.rowid","",$param,"",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Label"),$_SERVER["PHP_SELF"],"t.label","",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("DatePayment"),$_SERVER["PHP_SELF"],"dm","",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Type"),$_SERVER["PHP_SELF"],"type","",$param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("PayedByThisPayment"),$_SERVER["PHP_SELF"],"t.amount","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre(""); print "\n"; - + print ''; - print ''; - print ''; + print ''; + print ''; print ''; // Type print ''; - print ''; - print ''; - print "\n"; - + print ''; + print '\n"; + while ($i < min($num,$limit)) { $obj = $db->fetch_object($result); $var=!$var; - + if ($obj->payment_code <> '') { - $type = ''; + $type = ''; } else { $type = ''; } - + print ""; $tva_static->id=$obj->rowid; @@ -163,12 +171,12 @@ if ($result) } print ''; print ""; - print ""; + print ""; print "
  '; $form->select_types_paiements($typeid,'typeid','',0,0,1,16); print ''; - print ''; - print '
'; + print ''; + print "
'.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.''.$langs->trans("PaymentTypeShort".$obj->payment_code).' '.$obj->num_payment.' 
'.$langs->trans("Total").'".price($total)." 
 
"; - + print ''; - + $db->free($result); } else @@ -177,6 +185,6 @@ else } -$db->close(); - llxFooter(); + +$db->close(); diff --git a/htdocs/compta/ventilation/fiche.php b/htdocs/compta/ventilation/card.php similarity index 96% rename from htdocs/compta/ventilation/fiche.php rename to htdocs/compta/ventilation/card.php index b55f2b59475..7201dfe9e29 100644 --- a/htdocs/compta/ventilation/fiche.php +++ b/htdocs/compta/ventilation/card.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/compta/ventilation/fiche.php + * \file htdocs/compta/ventilation/card.php * \ingroup compta * \brief Page fiche ventilation */ @@ -106,7 +106,7 @@ if($_GET["id"]) if($objp->fk_code_ventilation == 0) { - print '
'."\n"; + print ''."\n"; print ''; print ''; } diff --git a/htdocs/compta/ventilation/fournisseur/fiche.php b/htdocs/compta/ventilation/fournisseur/card.php similarity index 96% rename from htdocs/compta/ventilation/fournisseur/fiche.php rename to htdocs/compta/ventilation/fournisseur/card.php index 168b99eea35..d62694512fc 100644 --- a/htdocs/compta/ventilation/fournisseur/fiche.php +++ b/htdocs/compta/ventilation/fournisseur/card.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/compta/ventilation/fournisseur/fiche.php + * \file htdocs/compta/ventilation/fournisseur/card.php * \ingroup compta * \brief Page fiche ventilation */ @@ -95,7 +95,7 @@ if($_GET["id"]) if($objp->fk_code_ventilation == 0) { - print ''."\n"; + print ''."\n"; print ''; print ''; } diff --git a/htdocs/compta/ventilation/fournisseur/index.php b/htdocs/compta/ventilation/fournisseur/index.php deleted file mode 100644 index ebd4d2c4af5..00000000000 --- a/htdocs/compta/ventilation/fournisseur/index.php +++ /dev/null @@ -1,127 +0,0 @@ - - * Copyright (C) 2004 Laurent Destailleur - * Copyright (C) 2005 Simon TOSSER - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/compta/ventilation/fournisseur/index.php - * \ingroup compta - * \brief Page accueil ventilation - */ - -require '../../../main.inc.php'; -$langs->load("suppliers"); - - -llxHeader('','Compta - Ventilation'); - -print_titre("Ventilation Comptable"); - -print ''; - -print '
'; - - - -$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."facturedet"; -$sql .= " WHERE fk_code_ventilation = 0"; -$result = $db->query($sql); -if ($result) -{ - $row = $db->fetch_row($result); - $nbfac = $row[0]; - - $db->free($result); -} - -$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."paiement"; -$sql .= " WHERE fk_code_ventilation = 0"; - -$result = $db->query($sql); -if ($result) -{ - $row = $db->fetch_row($result); - $nbp = $row[0]; - - $db->free($result); -} - -$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."facture_fourn_det"; -$sql .= " WHERE fk_code_ventilation = 0"; -$result = $db->query($sql); -if ($result) -{ - $row = $db->fetch_row($result); - $nbfacfourn = $row[0]; - - $db->free($result); -} - -/*$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."paiementfourn"; -$sql .= " WHERE fk_code_ventilation = 0"; - -$result = $db->query($sql); -if ($result) -{ - $row = $db->fetch_row($result); - $nbpfourn = $row[0]; - - $db->free($result); -}*/ - -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -//print ''; -print "
Lignes a ventiler
TypeNb
Factures clients'.$nbfac.'
Paiements clients'.$nbp.'
Factures fournisseurs'.$nbfacfourn.'
Paiements fournisseurs'.$nbpfourn.'
\n"; - -print '
'; - -print ''; -print ''; - -$sql = "SELECT count(*), ccg.intitule FROM ".MAIN_DB_PREFIX."facturedet as fd"; -$sql .= " ,".MAIN_DB_PREFIX."compta_compte_generaux as ccg"; -$sql .= " WHERE fd.fk_code_ventilation = ccg.rowid"; -$sql .= " GROUP BY ccg.rowid"; - -$resql = $db->query($sql); -if ($resql) -{ - $i = 0; - $num = $db->num_rows($resql); - - while ($i < $num) - { - - $row = $db->fetch_row($resql); - - print ''; - $i++; - } - $db->free($resql); -} -print "
TypeNb de lignes
'.$row[1].''.$row[0].'
\n"; - -print '
'; - -llxFooter(); - diff --git a/htdocs/compta/ventilation/fournisseur/lignes.php b/htdocs/compta/ventilation/fournisseur/lignes.php deleted file mode 100644 index cb2a0e1439a..00000000000 --- a/htdocs/compta/ventilation/fournisseur/lignes.php +++ /dev/null @@ -1,114 +0,0 @@ - - * Copyright (C) 2005 Simon TOSSER - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/compta/ventilation/fournisseur/lignes.php - * \ingroup facture - * \brief Page de detail des lignes de ventilation d'une facture - */ - -require '../../../main.inc.php'; - -$langs->load("bills"); - -if (!$user->rights->facture->lire) accessforbidden(); -if (!$user->rights->compta->ventilation->creer) accessforbidden(); -/* - * Securite acces client - */ -if ($user->societe_id > 0) accessforbidden(); - -llxHeader(''); - -/* - * Lignes de factures - * - */ -$page = $_GET["page"]; -if ($page < 0) $page = 0; -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -$sql = "SELECT f.facnumber, f.rowid as facid, l.fk_product, l.description, l.total_ttc as price, l.qty, l.rowid, l.tva_tx, l.fk_code_ventilation, c.intitule, c.numero "; -$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as l"; -$sql .= " , ".MAIN_DB_PREFIX."facture_fourn as f"; -$sql .= " , ".MAIN_DB_PREFIX."compta_compte_generaux as c"; - -$sql .= " WHERE f.rowid = l.fk_facture_fourn AND f.fk_statut = 1 AND l.fk_code_ventilation <> 0 "; -$sql .= " AND c.rowid = l.fk_code_ventilation"; - -if (dol_strlen(trim($_GET["search_facture"]))) -{ - $sql .= " AND f.facnumber like '%".$_GET["search_facture"]."%'"; -} - -$sql .= " ORDER BY l.rowid DESC"; -$sql .= $db->plimit($limit+1,$offset); - -$result = $db->query($sql); - -if ($result) -{ - $num_lignes = $db->num_rows($result); - $i = 0; - - print_barre_liste("Lignes de facture ventilées",$page,"lignes.php","",$sortfield,$sortorder,'',$num_lignes); - - print ''; - print ''; - print ""; - print ''; - print ''; - print ''; - print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - $var=True; - while ($i < min($num_lignes, $limit)) - { - $objp = $db->fetch_object($result); - $var=!$var; - print ""; - - print ''; - - print ''; - print ''; - print ''; - print ''; - - print ""; - $i++; - } -} -else -{ - print $db->error(); -} - -print "
Facture'.$langs->trans("Description").''.$langs->trans("Montant").''.$langs->trans("Compte").'
   
'.$objp->facnumber.''.stripslashes(nl2br($objp->description)).''.price($objp->price).''.$objp->numero.''.stripslashes($objp->intitule).'
"; - -$db->close(); - -llxFooter(); diff --git a/htdocs/compta/ventilation/fournisseur/liste.php b/htdocs/compta/ventilation/fournisseur/list.php similarity index 87% rename from htdocs/compta/ventilation/fournisseur/liste.php rename to htdocs/compta/ventilation/fournisseur/list.php index e3eb4cf487d..5213a4686be 100644 --- a/htdocs/compta/ventilation/fournisseur/liste.php +++ b/htdocs/compta/ventilation/fournisseur/list.php @@ -20,7 +20,7 @@ /** - * \file htdocs/compta/ventilation/liste.php + * \file htdocs/compta/ventilation/list.php * \ingroup compta * \brief Page de ventilation des lignes de facture */ @@ -60,7 +60,7 @@ if ($result) $num_lignes = $db->num_rows($result); $i = 0; - print_barre_liste("Lignes de facture à ventiler",$page,"liste.php","",$sortfield,$sortorder,'',$num_lignes); + print_barre_liste("Lignes de facture à ventiler",$page,"list.php","",$sortfield,$sortorder,'',$num_lignes); print ''; print ''; @@ -76,14 +76,14 @@ if ($result) $var=!$var; print ""; - print ''; + print ''; print ''; print ''; - print ''; diff --git a/htdocs/compta/ventilation/index.php b/htdocs/compta/ventilation/index.php deleted file mode 100644 index 8b9710844a7..00000000000 --- a/htdocs/compta/ventilation/index.php +++ /dev/null @@ -1,102 +0,0 @@ - - * Copyright (C) 2004-2005 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/compta/ventilation/index.php - * \ingroup compta - * \brief Page accueil ventilation - */ - -require '../../main.inc.php'; - -$langs->load("compta"); -$langs->load("bills"); - -llxHeader('','Compta - Ventilation'); - -print_fiche_titre("Ventilation Comptable"); - -//print '
Facture
'.$objp->facnumber.''.$objp->facnumber.''.stripslashes(nl2br($objp->description)).''; print price($objp->price); print ''; + print ''; print img_edit(); print '
'; -//print '
'; -print '
'; - -$sql = "SELECT count(*) FROM ".MAIN_DB_PREFIX."facturedet as fd"; -$sql.= " , ".MAIN_DB_PREFIX."facture as f"; -$sql.= " WHERE fd.fk_code_ventilation = 0"; -$sql.= " AND f.rowid = fd.fk_facture AND f.fk_statut = 1"; - -$result = $db->query($sql); -if ($result) -{ - $row = $db->fetch_row($result); - $nbfac = $row[0]; - - $db->free($result); -} - -$var=true; - -print ''; -print ''; -print ''; -$var=!$var; -print "".''; -$var=!$var; -print "
'.$langs->trans("Lines").'
'.$langs->trans("Type").''.$langs->trans("Nb").'
'.$langs->trans("Invoices").''.$nbfac.'
\n"; - - -//print '
'; -print '
'; - - -print ''; -print ''; - -$sql = "SELECT count(*), ccg.intitule, ccg.rowid,ccg.numero FROM ".MAIN_DB_PREFIX."facturedet as fd"; -$sql.= " ,".MAIN_DB_PREFIX."compta_compte_generaux as ccg"; -$sql.= " WHERE fd.fk_code_ventilation = ccg.rowid"; -$sql.= " GROUP BY ccg.rowid"; - -$resql = $db->query($sql); -if ($resql) -{ - $i = 0; - $num = $db->num_rows($resql); - $var=true; - - while ($i < $num) - { - - $row = $db->fetch_row($resql); - $var=!$var; - print ''; - print ''; - $i++; - } - $db->free($resql); -} -print "
'.$langs->trans("Type").''.$langs->trans("NbOfLines").''.$langs->trans("AccountNumber").''.$langs->trans("TransID").'
'.$row[1].''.$row[0].''.$row[3].''.$row[2].'
\n"; - -//print '
'; -print ''; - - -llxFooter(); - -$db->close(); diff --git a/htdocs/compta/ventilation/lignes.php b/htdocs/compta/ventilation/lignes.php deleted file mode 100644 index 46276937afe..00000000000 --- a/htdocs/compta/ventilation/lignes.php +++ /dev/null @@ -1,141 +0,0 @@ - - * Copyright (C) 2006 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -/** - * \file htdocs/compta/ventilation/lignes.php - * \ingroup facture - * \brief Page de detail des lignes de ventilation d'une facture - */ - -require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; -require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; - -$langs->load("bills"); -$langs->load("compta"); - -if (!$user->rights->facture->lire) accessforbidden(); -if (!$user->rights->compta->ventilation->creer) accessforbidden(); - -// Securite acces client -if ($user->societe_id > 0) accessforbidden(); - - -llxHeader(''); - -/* -* Lignes de factures -* -*/ -$page = $_GET["page"]; -if ($page < 0) $page = 0; -$limit = $conf->liste_limit; -$offset = $limit * $page ; - -$sql = "SELECT f.facnumber, f.rowid as facid, l.fk_product, l.description, f.total_ttc as price, l.qty, l.rowid, l.tva_tx, l.fk_code_ventilation, c.intitule, c.numero,"; -$sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type"; -$sql.= " FROM ".MAIN_DB_PREFIX."facture as f"; -$sql.= " , ".MAIN_DB_PREFIX."compta_compte_generaux as c"; -$sql.= " , ".MAIN_DB_PREFIX."facturedet as l"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = l.fk_product"; -$sql.= " WHERE f.rowid = l.fk_facture AND f.fk_statut = 1 AND l.fk_code_ventilation <> 0 "; -$sql.= " AND f.entity = ".$conf->entity; -$sql.= " AND c.rowid = l.fk_code_ventilation"; -if (dol_strlen(trim($_GET["search_facture"]))) -{ - $sql .= " AND f.facnumber LIKE '%".$_GET["search_facture"]."%'"; -} - -$sql .= " ORDER BY l.rowid DESC"; -$sql .= $db->plimit($limit+1,$offset); - -$result = $db->query($sql); - -if ($result) -{ - $num_lignes = $db->num_rows($result); - $i = 0; - - print_barre_liste($langs->trans("InvoiceDispatched"),$page,"lignes.php","",$sortfield,$sortorder,'',$num_lignes); - - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - - $facture_static=new Facture($db); - $product_static=new Product($db); - - $var=True; - while ($i < min($num_lignes, $limit)) - { - $objp = $db->fetch_object($result); - $var=!$var; - $codeCompta = $objp->numero.' '.$objp->intitule; - - print ""; - - // Ref facture - $facture_static->ref=$objp->facnumber; - $facture_static->id=$objp->facid; - print ''; - - // Ref produit - $product_static->ref=$objp->product_ref; - $product_static->id=$objp->product_id; - $product_static->type=$objp->type; - print ''; - - print ''; - print ''; - print ''; - print ''; - - print ""; - $i++; - } -} -else -{ - print $db->error(); -} - -print "
'.$langs->trans("Invoice").''.$langs->trans("Ref").''.$langs->trans("Label").''.$langs->trans("Description").''.$langs->trans("Montant").''.$langs->trans("Compte").'
    '; - print ''; - print '
'.$facture_static->getNomUrl(1).''; - if ($product_static->id) print $product_static->getNomUrl(1); - else print ' '; - print ''.dol_trunc($objp->product_label,24).''.nl2br(dol_trunc($objp->description,32)).''.price($objp->price).''.$codeCompta.'
"; - - -llxFooter(); -$db->close(); diff --git a/htdocs/compta/ventilation/liste.php b/htdocs/compta/ventilation/list.php similarity index 95% rename from htdocs/compta/ventilation/liste.php rename to htdocs/compta/ventilation/list.php index effa7689821..03a1b658cd2 100644 --- a/htdocs/compta/ventilation/liste.php +++ b/htdocs/compta/ventilation/list.php @@ -20,7 +20,7 @@ /** - * \file htdocs/compta/ventilation/liste.php + * \file htdocs/compta/ventilation/list.php * \ingroup compta * \brief Page de ventilation des lignes de facture */ @@ -69,7 +69,7 @@ if ($result) $num_lignes = $db->num_rows($result); $i = 0; - print_barre_liste($langs->trans("InvoiceLinesToDispatch"),$page,"liste.php","",$sortfield,$sortorder,'',$num_lignes); + print_barre_liste($langs->trans("InvoiceLinesToDispatch"),$page,"list.php","",$sortfield,$sortorder,'',$num_lignes); print ''; print ''; @@ -111,7 +111,7 @@ if ($result) print price($objp->price); print ''; - print ''; diff --git a/htdocs/conf/conf.php.example b/htdocs/conf/conf.php.example index 990a10c2500..32adc4b87c9 100644 --- a/htdocs/conf/conf.php.example +++ b/htdocs/conf/conf.php.example @@ -12,8 +12,8 @@ //################### // dolibarr_main_url_root -// This parameter defines the root URL of your Dolibarr index.php page. -// It must link to the htdocs directory htdocs. +// This parameter defines the root URL of your Dolibarr index.php page without ending "/". +// It must link to the directory htdocs. // In most cases, this is autodetected but it's still required // * to show full url bookmarks for some services (ie: agenda rss export url, ...) // * or when using Apache dir aliases (autodetect fails) diff --git a/htdocs/conf/index.html b/htdocs/conf/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php index 50b45918f9c..9e6624dda72 100644 --- a/htdocs/contact/canvas/actions_contactcard_common.class.php +++ b/htdocs/contact/canvas/actions_contactcard_common.class.php @@ -450,7 +450,7 @@ abstract class ActionsContactCardCommon // We set country_id, and country_code label of the chosen country if ($this->object->country_id) { - $sql = "SELECT code, libelle FROM ".MAIN_DB_PREFIX."c_pays WHERE rowid = ".$this->object->country_id; + $sql = "SELECT code, label FROM ".MAIN_DB_PREFIX."c_country WHERE rowid = ".$this->object->country_id; $resql=$this->db->query($sql); if ($resql) { @@ -460,9 +460,9 @@ abstract class ActionsContactCardCommon { dol_print_error($this->db); } - $this->object->country_id = $langs->trans("Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->libelle; + $this->object->country_id = $langs->trans("Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label; $this->object->country_code = $obj->code; - $this->object->country = $langs->trans("Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->libelle; + $this->object->country = $langs->trans("Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label; } } diff --git a/htdocs/contact/canvas/default/index.html b/htdocs/contact/canvas/default/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/canvas/default/index.php b/htdocs/contact/canvas/default/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/contact/canvas/default/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php index a0605d3656e..70d6b41bf35 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php @@ -50,7 +50,7 @@ echo $this->control->tpl['ajax_selectcountry']; ?> - + diff --git a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php index a445444e42c..3be1d16bc8d 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php @@ -59,7 +59,7 @@ echo $this->control->tpl['ajax_selectcountry']; - + diff --git a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php index 623fad27e77..0b4b8a07fcb 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php @@ -44,7 +44,7 @@ dol_htmloutput_errors($this->control->tpl['error'],$this->control->tpl['errors'] - + diff --git a/htdocs/contact/canvas/default/tpl/index.html b/htdocs/contact/canvas/default/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/canvas/default/tpl/index.php b/htdocs/contact/canvas/default/tpl/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/contact/canvas/default/tpl/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/contact/canvas/index.html b/htdocs/contact/canvas/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/canvas/index.php b/htdocs/contact/canvas/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/contact/canvas/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/contact/fiche.php b/htdocs/contact/card.php similarity index 76% rename from htdocs/contact/fiche.php rename to htdocs/contact/card.php index 9cb52738bb8..af07cbb9a62 100644 --- a/htdocs/contact/fiche.php +++ b/htdocs/contact/card.php @@ -23,7 +23,7 @@ */ /** - * \file htdocs/contact/fiche.php + * \file htdocs/contact/card.php * \ingroup societe * \brief Card of a contact */ @@ -74,7 +74,7 @@ if (! empty($canvas)) $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', $objcanvas); // If we create a contact with no company (shared contacts), no check on write permission // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('contactcard')); +$hookmanager->initHooks(array('contactcard','globalcard')); /* @@ -83,7 +83,7 @@ $hookmanager->initHooks(array('contactcard')); $parameters=array('id'=>$id, 'objcanvas'=>$objcanvas); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks -$error=$hookmanager->error; $errors=array_merge($errors, (array) $hookmanager->errors); +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) { @@ -138,19 +138,30 @@ if (empty($reshook)) if ($action == 'disable') { $object->fetch($id); - $object->setstatus(0); - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); - exit; + if ($object->setstatus(0)<0) + { + setEventMessage($object->error,'errors'); + } + else + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); + exit; + } } // Confirmation activation if ($action == 'enable') { $object->fetch($id); - $object->setstatus(1); - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); - exit; - + if ($object->setstatus(1)<0) + { + setEventMessage($object->error,'errors'); + } + else + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); + exit; + } } // Add contact @@ -210,7 +221,7 @@ if (empty($reshook)) { $db->commit(); if (! empty($backtopage)) $url=$backtopage; - else $url='fiche.php?id='.$id; + else $url='card.php?id='.$id; header("Location: ".$url); exit; } @@ -230,12 +241,20 @@ if (empty($reshook)) $result = $object->delete(); if ($result > 0) { - header("Location: ".DOL_URL_ROOT.'/contact/list.php'); - exit; + if ($backtopage) + { + header("Location: ".$backtopage); + exit; + } + else + { + header("Location: ".DOL_URL_ROOT.'/contact/list.php'); + exit; + } } else { - $error=$object->error; $errors=$object->errors; + setEventMessage($object->error,$object->errors,'errors'); } } @@ -295,7 +314,8 @@ if (empty($reshook)) } else { - $error=$object->error; $errors=$object->errors; + setEventMessage($object->error,'errors'); + setEventMessage($object->errors,'errors'); $action = 'edit'; } } @@ -347,7 +367,7 @@ else { if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id,$langs->trans("DeleteContact"),$langs->trans("ConfirmDeleteContact"),"confirm_delete",'',0,1); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage?'&backtopage='.$backtopage:''),$langs->trans("DeleteContact"),$langs->trans("ConfirmDeleteContact"),"confirm_delete",'',0,1); } } @@ -367,6 +387,8 @@ else $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); dol_fiche_head($head, 'card', $title, 0, 'contact'); + + dol_htmloutput_events(); } if ($user->rights->societe->contact->creer) @@ -424,42 +446,45 @@ else print '
'.$langs->trans("Invoice").''; + print ''; print img_edit(); print '
trans("Company"); ?>trans("ThirdParty"); ?> control->tpl['company']; ?>
trans("Company"); ?>trans("ThirdParty"); ?> control->tpl['company']; ?>
trans("Company"); ?>trans("ThirdParty"); ?> control->tpl['company']; ?>
'; // Name - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; // Company if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { if ($socid > 0) { - print ''; + print ''; print ''; - print ''; + print ''; print ''; } else { - print ''; } } // Civility - print ''; - print ''; + print ''; + print ''; $colspan=3; if ($conf->use_javascript_ajax && $socid > 0) $colspan=2; // Address if (($objsoc->typent_code == 'TE_PRIVATE' || ! empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->address)) == 0) $object->address = $objsoc->address; // Predefined with third party - print ''; + print ''; + print ''; if ($conf->use_javascript_ajax && $socid > 0) { @@ -475,13 +500,13 @@ else // Zip / Town 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 ''; @@ -489,7 +514,7 @@ else // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; if (($objsoc->typent_code == 'TE_PRIVATE' || ! empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->fax)) == 0) $object->fax = $objsoc->fax; // Predefined with third party - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; // EMail 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 - print ''; + print ''; + print ''; if (! empty($conf->mailing->enabled)) { - print ''; + print ''; + print ''; } else { @@ -524,16 +555,18 @@ else print ''; // Instant message and no email - print ''; + print ''; + print ''; // Skype if (! empty($conf->skype->enabled)) { - print ''; + print ''; + print ''; } // Visibility - print ''; @@ -555,7 +588,7 @@ else print '
'.$langs->trans("Lastname").' / '.$langs->trans("Label").'lastname).'">'.$langs->trans("Firstname").'firstname).'">
lastname).'" autofocus="autofocus">firstname).'">
'.$langs->trans("Company").'
'; print $objsoc->getNomUrl(1); print '
'.$langs->trans("Company").''; + print '
'; print $form->select_company($socid,'socid','',1); print '
'.$langs->trans("UserTitle").''; + print '
'; print $formcompany->select_civility(GETPOST("civility_id",'alpha')?GETPOST("civility_id",'alpha'):$object->civility_id); print '
'.$langs->trans("PostOrFunction").'poste).'">
poste).'">
'.$langs->trans("Address"); - print '
'.$langs->trans("Zip").' / '.$langs->trans("Town").''; + print '
/ '; print $formcompany->select_ziptown((GETPOST("zipcode")?GETPOST("zipcode"):$object->zip),'zipcode',array('town','selectcountry_id','state_id'),6).' '; print $formcompany->select_ziptown((GETPOST("town")?GETPOST("town"):$object->town),'town',array('zipcode','selectcountry_id','state_id')); print '
'.$langs->trans("Country").''; + print '
'; 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 '
'.$langs->trans('State').''; + print '
'; if ($object->country_id) { print $formcompany->select_state(GETPOST("state_id",'alpha')?GETPOST("state_id",'alpha'):$object->state_id,$object->country_code,'state_id'); @@ -503,19 +528,25 @@ else // Phone / Fax if (($objsoc->typent_code == 'TE_PRIVATE' || ! empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) && dol_strlen(trim($object->phone_pro)) == 0) $object->phone_pro = $objsoc->phone; // Predefined with third party - print '
'.$langs->trans("PhonePro").'phone_pro).'">'.$langs->trans("PhonePerso").'phone_perso).'">
phone_pro).'">phone_perso).'">
'.$langs->trans("PhoneMobile").'phone_mobile).'">'.$langs->trans("Fax").'fax).'">
phone_mobile).'">fax).'">
'.$langs->trans("Email").'email).'">
email).'">'.$langs->trans("No_Email").''.$form->selectyesno('no_email',(GETPOST("no_email",'alpha')?GETPOST("no_email",'alpha'):$object->no_email), 1).''.$form->selectyesno('no_email',(GETPOST("no_email",'alpha')?GETPOST("no_email",'alpha'):$object->no_email), 1).'
'.$langs->trans("IM").'jabberid).'">
jabberid).'">
'.$langs->trans("Skype").'skype).'">
skype).'">
'.$langs->trans("ContactVisibility").''; + print '
'; $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); print $form->selectarray('priv',$selectarray,(GETPOST("priv",'alpha')?GETPOST("priv",'alpha'):$object->priv),0); print '
'; // Date To Birth - print ''; - print ''; + print ''; } else { - print ''; + print ''; } print ''; @@ -649,13 +682,15 @@ else print ''; // Lastname - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; // Company if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { - print ''; + print ''; print ''; @@ -663,15 +698,16 @@ else } // Civility - print ''; - print ''; + print ''; + print ''; // Address - print ''; + print ''; + print ''; $rowspan=3; if (empty($conf->global->SOCIETE_DISABLE_STATE)) $rowspan++; @@ -681,13 +717,13 @@ else print ''; // Zip / Town - print ''; // Country - print ''; @@ -695,20 +731,25 @@ else // State if (empty($conf->global->SOCIETE_DISABLE_STATE)) { - print ''; } // Phone - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; // EMail - print ''; + print ''; + print ''; if (! empty($conf->mailing->enabled)) { $langs->load("mails"); @@ -722,10 +763,12 @@ else print ''; // Jabberid - print ''; + print ''; + print ''; if (! empty($conf->mailing->enabled)) { - print ''; + print ''; + print ''; } else { @@ -736,23 +779,24 @@ else // Skype if (! empty($conf->skype->enabled)) { - print ''; + print ''; + print ''; } // Visibility - print ''; // Note Public - print ''; // Note Private - print ''; @@ -880,7 +924,7 @@ else // Company if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { - print ''; - print ''; + print ''; } else { @@ -1045,27 +1089,27 @@ else { if ($user->rights->societe->contact->creer) { - print ''.$langs->trans('Modify').''; + print ''.$langs->trans('Modify').''; } if (! $object->user_id && $user->rights->user->user->creer) { - print ''.$langs->trans("CreateDolibarrLogin").''; + print ''.$langs->trans("CreateDolibarrLogin").''; } if ($user->rights->societe->contact->supprimer) { - print ''.$langs->trans('Delete').''; + print ''.$langs->trans('Delete').''; } // Activer if ($object->statut == 0 && $user->rights->societe->contact->creer) { - print ''.$langs->trans("Reactivate").''; + print ''.$langs->trans("Reactivate").''; } // Desactiver if ($object->statut == 1 && $user->rights->societe->contact->creer) { - print ''.$langs->trans("DisableUser").''; + print ''.$langs->trans("DisableUser").''; } } @@ -1073,7 +1117,22 @@ else if (! empty($conf->agenda->enabled)) { - print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),'',''); + $objthirdparty=$objsoc; + $objcon=$object; + + $out=''; + $permok=$user->rights->agenda->myactions->create; + if ((! empty($objthirdparty->id) || ! empty($objcon->id)) && $permok) + { + $out.=''; + $out.=$langs->trans("AddAnAction").' '; + $out.=img_picto($langs->trans("AddAnAction"),'filenew'); + $out.=""; + } + + print load_fiche_titre($langs->trans("TasksHistoryForThisContact"),$out,''); print show_actions_todo($conf,$langs,$db,$objsoc,$object); diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 4187de7136c..6a7776b27bd 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -155,7 +155,7 @@ class Contact extends CommonObject $sql.= " ".(! empty($this->import_key)?"'".$this->import_key."'":"null"); $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -183,12 +183,10 @@ class Contact extends CommonObject if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTACT_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTACT_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -222,7 +220,7 @@ class Contact extends CommonObject * @param string $action Current action for hookmanager * @return int <0 if KO, >0 if OK */ - function update($id, $user=0, $notrigger=0, $action='update') + function update($id, $user=null, $notrigger=0, $action='update') { global $conf, $langs, $hookmanager; @@ -251,7 +249,7 @@ class Contact extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET "; if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',"; else if ($this->socid == -1) $sql .= " fk_soc=null,"; - $sql .= " civilite='".$this->db->escape($this->civility_id)."'"; + $sql .= " civility='".$this->db->escape($this->civility_id)."'"; $sql .= ", lastname='".$this->db->escape($this->lastname)."'"; $sql .= ", firstname='".$this->db->escape($this->firstname)."'"; $sql .= ", address='".$this->db->escape($this->address)."'"; @@ -276,7 +274,7 @@ class Contact extends CommonObject $sql .= ", no_email=".($this->no_email?"'".$this->no_email."'":"0"); $sql .= " WHERE rowid=".$this->db->escape($id); - dol_syslog(get_class($this)."::update sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -285,6 +283,8 @@ class Contact extends CommonObject unset($this->state_code); unset($this->state); + $action='update'; + // Actions on extra fields (by external module or standard code) $hookmanager->initHooks(array('contactdao')); $parameters=array('socid'=>$this->id); @@ -304,12 +304,10 @@ class Contact extends CommonObject if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTACT_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTACT_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -319,7 +317,6 @@ class Contact extends CommonObject } else { - $this->error=join(',',$this->errors); dol_syslog(get_class($this)."::update Error ".$this->error,LOG_ERR); $this->db->rollback(); return -$error; @@ -328,7 +325,6 @@ class Contact extends CommonObject else { $this->error=$this->db->lasterror().' sql='.$sql; - dol_syslog(get_class($this)."::update Error ".$this->error,LOG_ERR); $this->db->rollback(); return -1; } @@ -380,7 +376,7 @@ class Contact extends CommonObject $soc = new Societe($this->db); $soc->fetch($this->socid); - $info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->nom; + $info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name; if ($soc->client == 1) $info["businessCategory"] = "Customers"; if ($soc->client == 2) $info["businessCategory"] = "Prospects"; if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers"; @@ -433,7 +429,7 @@ class Contact extends CommonObject * @param User $user User asking to change alert or birthday * @return int <0 if KO, >=0 if OK */ - function update_perso($id, $user=0) + function update_perso($id, $user=null) { $error=0; $result=false; @@ -444,7 +440,7 @@ class Contact extends CommonObject if ($user) $sql .= ", fk_user_modif=".$user->id; $sql.= " WHERE rowid=".$this->db->escape($id); - dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." - sql=".$sql); + dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { @@ -498,13 +494,13 @@ class Contact extends CommonObject * @param User $user Utilisateur (abonnes aux alertes) qui veut les alertes de ce contact * @return int -1 if KO, 0 if OK but not found, 1 if OK */ - function fetch($id, $user=0) + function fetch($id, $user=null) { global $langs; $langs->load("companies"); - $sql = "SELECT c.rowid, c.fk_soc, c.ref_ext, c.civilite as civility_id, c.lastname, c.firstname,"; + $sql = "SELECT c.rowid, c.fk_soc, c.ref_ext, c.civility as civility_id, c.lastname, c.firstname,"; $sql.= " c.address, c.statut, c.zip, c.town,"; $sql.= " c.fk_pays as country_id,"; $sql.= " c.fk_departement,"; @@ -512,18 +508,18 @@ class Contact extends CommonObject $sql.= " c.poste, c.phone, c.phone_perso, c.phone_mobile, c.fax, c.email, c.jabberid, c.skype,"; $sql.= " c.priv, c.note_private, c.note_public, c.default_lang, c.no_email, c.canvas,"; $sql.= " c.import_key,"; - $sql.= " p.libelle as country, p.code as country_code,"; + $sql.= " co.label as country, co.code as country_code,"; $sql.= " d.nom as state, d.code_departement as state_code,"; $sql.= " u.rowid as user_id, u.login as user_login,"; $sql.= " s.nom as socname, s.address as socaddress, s.zip as soccp, s.town as soccity, s.default_lang as socdefault_lang"; $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_pays as p ON c.fk_pays = p.rowid"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON c.fk_pays = co.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON c.fk_departement = d.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; $sql.= " WHERE c.rowid = ". $id; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -599,7 +595,6 @@ class Contact extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } @@ -624,7 +619,6 @@ class Contact extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -640,7 +634,6 @@ class Contact extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -664,7 +657,7 @@ class Contact extends CommonObject $sql.=" AND fk_socpeople = ". $this->id; $sql.=" GROUP BY tc.element"; - dol_syslog(get_class($this)."::load_ref_elements sql=".$sql); + dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -685,7 +678,6 @@ class Contact extends CommonObject else { $this->error=$this->db->error()." - ".$sql; - dol_syslog(get_class($this)."::load_ref_elements Error ".$this->error, LOG_ERR); return -1; } } @@ -716,7 +708,7 @@ class Contact extends CommonObject $sql.= " WHERE ec.fk_socpeople=".$this->id; $sql.= " AND ec.fk_c_type_contact=tc.rowid"; $sql.= " AND tc.source='external'"; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -729,7 +721,7 @@ class Contact extends CommonObject $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; $sqldel.=" WHERE rowid = ".$obj->rowid; - dol_syslog(get_class($this)."::delete sql=".$sqldel); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sqldel); if (! $result) { @@ -751,14 +743,13 @@ class Contact extends CommonObject { // Remove category $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag=-1; - dol_syslog(get_class($this)."::delete error ".$errorflag." ".$this->error, LOG_ERR); } } @@ -766,7 +757,7 @@ class Contact extends CommonObject { $sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople"; $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $result = $this->db->query($sql); if (! $result) { @@ -783,14 +774,10 @@ class Contact extends CommonObject if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTACT_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - - if ($error) $this->error=join(',',$this->errors); + // Call trigger + $result=$this->call_trigger('CONTACT_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -866,7 +853,7 @@ class Contact extends CommonObject $sql.= " WHERE mc.email = '".$this->db->escape($this->email)."'"; $sql.= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes - dol_syslog(get_class($this)."::getNbOfEMailings sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getNbOfEMailings", LOG_DEBUG); $resql=$this->db->query($sql); @@ -892,20 +879,21 @@ class Contact extends CommonObject * @param int $withpicto Include picto with link * @param string $option Where the link point to * @param int $maxlen Max length of + * @param string $moreparam Add more param into URL * @return string String with URL */ - function getNomUrl($withpicto=0,$option='',$maxlen=0) + function getNomUrl($withpicto=0,$option='',$maxlen=0,$moreparam='') { global $langs; $result=''; - $lien = ''; + $lien = ''; $lienfin=''; if ($option == 'xxx') { - $lien = ''; + $lien = ''; $lienfin=''; } @@ -924,9 +912,9 @@ class Contact extends CommonObject global $langs; $langs->load("dict"); - $code=(! empty($this->civility_id)?$this->civility_id:(! empty($this->civility_id)?$this->civility_id:'')); + $code=(! empty($this->civility_id)?$this->civility_id:(! empty($this->civilite_id)?$this->civilite_id:'')); if (empty($code)) return ''; - return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civilite", "code", "civilite", $code); + return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); } /** @@ -1070,15 +1058,13 @@ class Contact extends CommonObject $sql.= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - dol_syslog(get_class($this)."::setstatus sql=".$sql); + dol_syslog(get_class($this)."::setstatus", LOG_DEBUG); if ($result) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTACT_ENABLEDISABLE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTACT_ENABLEDISABLE',$user); + if ($result < 0) { $error++; } + // End call triggers } if ($error) diff --git a/htdocs/contact/class/index.html b/htdocs/contact/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/exportimport.php b/htdocs/contact/exportimport.php index bcb3b9c2be0..e9e9c70966c 100644 --- a/htdocs/contact/exportimport.php +++ b/htdocs/contact/exportimport.php @@ -77,11 +77,11 @@ if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) $objsoc = new Societe($db); $objsoc->fetch($contact->socid); - print ''; + print ''; } else { - print ''; } diff --git a/htdocs/contact/index.html b/htdocs/contact/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contact/index.php b/htdocs/contact/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/contact/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 1681324323a..170ed039904 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -49,8 +49,6 @@ $contact->fetch($id, $user); if ($action == 'dolibarr2ldap') { - $message=""; - $db->begin(); $ldap=new Ldap(); @@ -64,12 +62,12 @@ if ($action == 'dolibarr2ldap') if ($result >= 0) { - $message.='
'.$langs->trans("ContactSynchronized").'
'; + setEventMessage($langs->trans("ContactSynchronized")); $db->commit(); } else { - $message.='
'.$ldap->error.'
'; + setEventMessage($ldap->error, 'errors'); $db->rollback(); } } @@ -107,11 +105,11 @@ if ($contact->socid > 0) $objsoc = new Societe($db); $objsoc->fetch($contact->socid); - print ''; + print ''; } else { - print ''; } @@ -136,10 +134,6 @@ print '
'.$langs->trans("DateToBirth").''; + print '
'; $form=new Form($db); if ($object->birthday) { @@ -567,14 +600,14 @@ else } print ''.$langs->trans("Alert").': '; + print ': '; if ($object->birthday_alert) { - print '
'.$langs->trans("Lastname").' / '.$langs->trans("Label").'lastname).'">'.$langs->trans("Firstname").'firstname).'">
lastname).'" autofocus="autofocus">firstname).'">
'.$langs->trans("Company").'
'; print $form->select_company(GETPOST('socid','int')?GETPOST('socid','int'):($object->socid?$object->socid:-1),'socid','',1); print '
'.$langs->trans("UserTitle").''; + print '
'; print $formcompany->select_civility(isset($_POST["civility_id"])?$_POST["civility_id"]:$object->civility_id); print '
'.$langs->trans("PostOrFunction").'poste).'">
poste).'">
'.$langs->trans("Address"); - print '
'.$langs->trans("Zip").' / '.$langs->trans("Town").''; + print '
/ '; print $formcompany->select_ziptown((isset($_POST["zipcode"])?$_POST["zipcode"]:$object->zip),'zipcode',array('town','selectcountry_id','state_id'),6).' '; print $formcompany->select_ziptown((isset($_POST["town"])?$_POST["town"]:$object->town),'town',array('zipcode','selectcountry_id','state_id')); print '
'.$langs->trans("Country").''; + print '
'; print $form->select_country(isset($_POST["country_id"])?$_POST["country_id"]:$object->country_id,'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); print '
'.$langs->trans('State').''; + print '
'; print $formcompany->select_state($object->state_id,isset($_POST["country_id"])?$_POST["country_id"]:$object->country_id,'state_id'); print '
'.$langs->trans("PhonePro").'phone_pro).'">'.$langs->trans("PhonePerso").'phone_perso).'">
phone_pro).'">phone_perso).'">
'.$langs->trans("PhoneMobile").'phone_mobile).'">'.$langs->trans("Fax").'fax).'">
phone_mobile).'">fax).'">
'.$langs->trans("EMail").'email).'">
email).'">
'.$langs->trans("Jabberid").'jabberid).'">
jabberid).'">'.$langs->trans("No_Email").''.$form->selectyesno('no_email',(isset($_POST["no_email"])?$_POST["no_email"]:$object->no_email), 1).''.$form->selectyesno('no_email',(isset($_POST["no_email"])?$_POST["no_email"]:$object->no_email), 1).'
'.$langs->trans("Skype").'skype).'">
skype).'">
'.$langs->trans("ContactVisibility").''; + print '
'; $selectarray=array('0'=>$langs->trans("ContactPublic"),'1'=>$langs->trans("ContactPrivate")); print $form->selectarray('priv',$selectarray,$object->priv,0); print '
'.$langs->trans("NotePublic").''; + print '
'; $doleditor = new DolEditor('note_public', $object->note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70); print $doleditor->Create(1); print '
'.$langs->trans("NotePrivate").''; + print '
'; $doleditor = new DolEditor('note_private', $object->note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70); print $doleditor->Create(1); print '
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; if ($object->socid > 0) { $objsoc->fetch($object->socid); @@ -938,7 +982,7 @@ else { $langs->load("mails"); print ''.$langs->trans("NbOfEMailingsSend").''.$object->getNbOfEMailings().''.$object->getNbOfEMailings().'
'.$langs->trans("Company").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print '
'.$langs->trans("Company").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print '
'; print ''; - -dol_htmloutput_mesg($message); - - /* * Barre d'actions */ diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index fadabea88c1..4413b721fc9 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -39,6 +39,7 @@ $contactid = GETPOST('id','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'contact', $contactid,''); +$search_firstlast_only=GETPOST("search_firstlast_only"); $search_lastname=GETPOST("search_lastname"); $search_firstname=GETPOST("search_firstname"); $search_societe=GETPOST("search_societe"); @@ -51,8 +52,8 @@ $search_fax=GETPOST("search_fax"); $search_email=GETPOST("search_email"); $search_skype=GETPOST("search_skype"); $search_priv=GETPOST("search_priv"); -$search_categ = GETPOST("search_categ",'int'); -$search_status = GETPOST("search_status",'int'); +$search_categ=GETPOST("search_categ",'int'); +$search_status=GETPOST("search_status",'int'); if ($search_status=='') $search_status=1; // always display activ customer first @@ -74,15 +75,20 @@ $offset = $limit * $page; $langs->load("companies"); $titre = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); -if ($type == "c" || $type=="p") +if ($type == "p") +{ + $titre.=' ('.$langs->trans("ThirdPartyProspects").')'; + $urlfiche="card.php"; +} +if ($type == "c") { $titre.=' ('.$langs->trans("ThirdPartyCustomers").')'; - $urlfiche="fiche.php"; + $urlfiche="card.php"; } else if ($type == "f") { $titre.=' ('.$langs->trans("ThirdPartySuppliers").')'; - $urlfiche="fiche.php"; + $urlfiche="card.php"; } else if ($type == "o") { @@ -90,8 +96,9 @@ else if ($type == "o") $urlfiche=""; } -if (GETPOST('button_removefilter')) +if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter')) // Both tests are required to be compatible with all browsers { + $search_firstlast_only=""; $search_lastname=""; $search_firstname=""; $search_societe=""; @@ -124,9 +131,9 @@ $formother=new FormOther($db); $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql.= " p.rowid as cidp, p.lastname as lastname, p.statut, p.firstname, p.poste, p.email, p.skype,"; $sql.= " p.phone, p.phone_mobile, p.fax, p.fk_pays, p.priv, p.tms,"; -$sql.= " cp.code as country_code"; +$sql.= " co.code as country_code"; $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as p"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_pays as cp ON cp.rowid = p.fk_pays"; +$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = p.fk_pays"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; if (! empty($search_categ)) $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_contact as cs ON p.rowid = cs.fk_socpeople"; // We need this table joined to the select in order to filter by categ if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; @@ -154,6 +161,9 @@ else if ($search_categ > 0) $sql.= " AND cs.fk_categorie = ".$search_categ; if ($search_categ == -2) $sql.= " AND cs.fk_categorie IS NULL"; +if ($search_firstlast_only) { + $sql .= natural_search(array('p.lastname','p.firstname'), $search_firstlast_only); +} if ($search_lastname) { // filter on lastname $sql .= natural_search('p.lastname', $search_lastname); } @@ -213,7 +223,7 @@ else if ($type == "p") // filtre sur type } if ($sall) { - $sql .= natural_search(array('p.lastname', 'p.firstname', 'p.email'), $sall); + $sql .= natural_search(array('p.lastname', 'p.firstname', 'p.email', 's.nom'), $sall); } if (! empty($socid)) { @@ -239,7 +249,7 @@ else } //print $sql; -dol_syslog("contact/list.php sql=".$sql); +dol_syslog("contact/list.php", LOG_DEBUG); $result = $db->query($sql); if ($result) { @@ -277,9 +287,12 @@ if ($result) if ($sall) { - print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname")." ".$langs->trans("or")." ".$langs->trans("EMail")."): ".$sall; + print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname").", ".$langs->trans("ThirdParty")." ".$langs->trans("or")." ".$langs->trans("EMail")."): ".$sall; } - + if ($search_firstlast_only) + { + print $langs->trans("Filter")." (".$langs->trans("Lastname").", ".$langs->trans("Firstname")."): ".$search_firstlast_only; + } print ''; // Ligne des titres @@ -287,9 +300,9 @@ if ($result) print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"p.lastname", $begin, $param, '', $sortfield,$sortorder); print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"p.firstname", $begin, $param, '', $sortfield,$sortorder); print_liste_field_titre($langs->trans("PostOrFunction"),$_SERVER["PHP_SELF"],"p.poste", $begin, $param, '', $sortfield,$sortorder); - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom", $begin, $param, '', $sortfield,$sortorder); print_liste_field_titre($langs->trans("Phone"),$_SERVER["PHP_SELF"],"p.phone", $begin, $param, '', $sortfield,$sortorder); - print_liste_field_titre($langs->trans("PhoneMobile"),$_SERVER["PHP_SELF"],"p.phone_mob", $begin, $param, '', $sortfield,$sortorder); + print_liste_field_titre($langs->trans("PhoneMobile"),$_SERVER["PHP_SELF"],"p.phone_mobile", $begin, $param, '', $sortfield,$sortorder); print_liste_field_titre($langs->trans("Fax"),$_SERVER["PHP_SELF"],"p.fax", $begin, $param, '', $sortfield,$sortorder); print_liste_field_titre($langs->trans("EMail"),$_SERVER["PHP_SELF"],"p.email", $begin, $param, '', $sortfield,$sortorder); if (! empty($conf->skype->enabled)) { print_liste_field_titre($langs->trans("Skype"),$_SERVER["PHP_SELF"],"p.skype", $begin, $param, '', $sortfield,$sortorder); } @@ -343,9 +356,8 @@ if ($result) print $form->selectarray('search_status', array('0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); print ''; print ''; print ''; @@ -378,7 +390,7 @@ if ($result) print ''; + print ''; } else { - print ''; } diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 92ba03e9861..6ec43320e54 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -111,11 +111,11 @@ if ($action == 'edit') $objsoc = new Societe($db); $objsoc->fetch($object->socid); - print ''; + print ''; } else { - print ''; } @@ -179,12 +179,12 @@ else $objsoc = new Societe($db); $objsoc->fetch($object->socid); - print ''; + print ''; } else { - print ''; } diff --git a/htdocs/contact/vcard.php b/htdocs/contact/vcard.php index e78c298c541..77abf31ac89 100644 --- a/htdocs/contact/vcard.php +++ b/htdocs/contact/vcard.php @@ -75,7 +75,7 @@ if ($company->id) if (! $contact->zip) $v->setAddress("", "", $company->address, $company->town, "", $company->zip, $company->country_code, "WORK;POSTAL"); if ($company->email != $contact->email) $v->setEmail($company->email,'internet'); // Si contact lie a un tiers non de type "particulier" - if ($contact->typent_code != 'TE_PRIVATE') $v->setOrg($company->nom); + if ($contact->typent_code != 'TE_PRIVATE') $v->setOrg($company->name); } // Personal informations diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 227ef23f741..afb86224151 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -39,7 +39,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); diff --git a/htdocs/contrat/admin/index.html b/htdocs/contrat/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contrat/fiche.php b/htdocs/contrat/card.php similarity index 90% rename from htdocs/contrat/fiche.php rename to htdocs/contrat/card.php index 38a2b3f1095..e4a8c644615 100644 --- a/htdocs/contrat/fiche.php +++ b/htdocs/contrat/card.php @@ -1,7 +1,7 @@ - * Copyright (C) 2004-2012 Laurent Destailleur - * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2013 Christophe Battarel @@ -23,7 +23,7 @@ */ /** - * \file htdocs/contrat/fiche.php + * \file htdocs/contrat/card.php * \ingroup contrat * \brief Page of a contract */ @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php'; require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; if (! empty($conf->produit->enabled) || ! empty($conf->service->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (! empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; if (! empty($conf->projet->enabled)) { @@ -48,6 +49,7 @@ $langs->load("orders"); $langs->load("companies"); $langs->load("bills"); $langs->load("products"); +$langs->load('compta'); $action=GETPOST('action','alpha'); $confirm=GETPOST('confirm','alpha'); @@ -64,11 +66,20 @@ $result=restrictedArea($user,'contrat',$id); $usehm=(! empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE)?$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE:0); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('contractcard')); +$hookmanager->initHooks(array('contractcard','globalcard')); $object = new Contrat($db); $extrafields = new ExtraFields($db); +// Load object +if ($id > 0 || ! empty($ref)) { + $ret = $object->fetch($id, $ref); + if ($ret > 0) + $ret = $object->fetch_thirdparty(); + if ($ret < 0) + dol_print_error('', $object->error); +} + // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); @@ -83,7 +94,6 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { - $object->fetch($id); $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); if ($result > 0) @@ -105,7 +115,6 @@ else if ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->c } if (! $error) { - $object->fetch($id); $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); if ($result > 0) { @@ -206,6 +215,7 @@ if ($action == 'add' && $user->rights->contrat->creer) $object->fk_project = GETPOST('projectid','int'); $object->remise_percent = GETPOST('remise_percent','alpha'); $object->ref = GETPOST('ref','alpha'); + $object->ref_supplier = GETPOST('ref_supplier','alpha'); // If creation from another object of another module (Example: origin=propal, originid=1) if ($_POST['origin'] && $_POST['originid']) @@ -263,7 +273,7 @@ if ($action == 'add' && $user->rights->contrat->creer) { $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0); - if ($product_type == 1) { //only services // TODO Exclude also deee + if ($product_type == 1 || (! empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0,1)))) { // TODO Exclude also deee // service prédéfini if ($lines[$i]->fk_product > 0) { @@ -279,7 +289,7 @@ if ($action == 'add' && $user->rights->contrat->creer) $outputlangs = $langs; $newlang=''; if (empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id'); - if (empty($newlang)) $newlang=$srcobject->client->default_lang; + if (empty($newlang)) $newlang=$srcobject->thirdparty->default_lang; if (! empty($newlang)) { $outputlangs = new Translate("",$conf); @@ -361,7 +371,6 @@ if ($action == 'add' && $user->rights->contrat->creer) else if ($action == 'classin' && $user->rights->contrat->creer) { - $object->fetch($id); $object->setProject(GETPOST('projectid')); } @@ -400,14 +409,6 @@ else if ($action == 'addline' && $user->rights->contrat->creer) if (! $error) { - $ret=$object->fetch($id); - if ($ret < 0) - { - setEventMessage($object->error,'errors'); - exit; - } - $ret=$object->fetch_thirdparty(); - // Clean parameters $date_start=dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end=dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); @@ -443,7 +444,7 @@ else if ($action == 'addline' && $user->rights->contrat->creer) $prodcustprice = new Productcustomerprice($db); - $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->client->id); + $filter = array('t.fk_product' => $prod->id,'t.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); if ($result) { @@ -524,23 +525,22 @@ else if ($action == 'addline' && $user->rights->contrat->creer) if ($result > 0) { - /* - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $ret=$object->fetch($id); // Reload to get new records - contrat_pdf_create($db, $object->id, $object->modelpdf, $outputlangs); - } - */ + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + + $ret = $object->fetch($id); // Reload to get new records + + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } unset($_POST ['prod_entry_mode']); @@ -582,14 +582,6 @@ else if ($action == 'addline' && $user->rights->contrat->creer) else if ($action == 'updateligne' && $user->rights->contrat->creer && ! GETPOST('cancel')) { - $ret=$object->fetch($id); - if ($ret < 0) - { - dol_print_error($db,$object->error); - exit; - } - - $object->fetch_thirdparty(); $objectline = new ContratLigne($db); if ($objectline->fetch(GETPOST('elrowid'))) { @@ -645,7 +637,6 @@ else if ($action == 'updateligne' && $user->rights->contrat->creer && ! GETPOST( else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->fetch($id); $result = $object->deleteline(GETPOST('lineid'),$user); if ($result >= 0) @@ -661,21 +652,17 @@ else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights-> else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->fetch($id); $result = $object->validate($user); } // Close all lines else if ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { - $object->fetch($id); $result = $object->cloture($user); } else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) { - $object->fetch($id); - $object->fetch_thirdparty(); $result=$object->delete($user); if ($result >= 0) { @@ -712,7 +699,6 @@ else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contra } } else if ($action == 'update_extras') { // Fill array 'array_options' with data from update form - $object->fetch($id); $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); $ret = $extrafields->setOptionalsFromPost($extralabels, $object, GETPOST('attribute')); if ($ret < 0) @@ -731,19 +717,81 @@ else if ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contra $action = 'edit_extras'; setEventMessage($object->error,'errors'); } +} elseif ($action=='setref_supplier') { + $result = $object->fetch($id); + if ($result < 0) { + setEventMessage($object->errors,'errors'); + } + $object->ref_supplier=GETPOST('ref_supplier','alpha'); + + $result = $object->update($user); + if ($result < 0) { + setEventMessage($object->errors,'errors'); + $action='editref_supplier'; + } else { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } +} elseif ($action=='setref') { + $object->ref=GETPOST('ref','alpha'); + + $result = $object->update($user); + if ($result < 0) { + setEventMessage($object->errors,'errors'); + $action='editref'; + } else { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } +} + +// Generation doc (depuis lien ou depuis cartouche doc) +else if ($action == 'builddoc' && $user->rights->contrat->creer) { + if (GETPOST('model')) { + $object->setDocModel($user, GETPOST('model')); + } + + // Define output language + $outputlangs = $langs; + if (! empty($conf->global->MAIN_MULTILANGS)) { + $outputlangs = new Translate("", $conf); + $newlang = (GETPOST('lang_id') ? GETPOST('lang_id') : $object->thirdparty->default_lang); + $outputlangs->setDefaultLang($newlang); + } + $ret = $object->fetch($id); // Reload to get new records + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + + if ($result <= 0) { + dol_print_error($db, $result); + exit(); + } else { + header('Location: ' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc')); + exit(); + } +} + +// Remove file in doc form +else if ($action == 'remove_file' && $user->rights->contrat->creer) { + if ($object->id > 0) { + require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php'; + + $langs->load("other"); + $upload_dir = $conf->contrat->dir_output; + $file = $upload_dir . '/' . GETPOST('file'); + $ret = dol_delete_file($file, 0, 0, 0, $object); + if ($ret) + setEventMessage($langs->trans("FileWasRemoved", GETPOST('file'))); + else + setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), 'errors'); + } } if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) { if ($action == 'addcontact') { - $result = $object->fetch($id); - - if ($result > 0 && $id > 0) - { - $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $result = $object->add_contact($contactid, GETPOST('type'), GETPOST('source')); - } + $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); + $result = $object->add_contact($contactid, GETPOST('type'), GETPOST('source')); if ($result >= 0) { @@ -767,20 +815,12 @@ if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat- // bascule du statut d'un contact else if ($action == 'swapstatut') { - if ($object->fetch($id)) - { - $result=$object->swapContactStatus(GETPOST('ligne')); - } - else - { - setEventMessage($object->error,'errors'); - } + $result=$object->swapContactStatus(GETPOST('ligne')); } // Efface un contact else if ($action == 'deletecontact') { - $object->fetch($id); $result = $object->delete_contact(GETPOST('lineid')); if ($result >= 0) @@ -802,9 +842,22 @@ if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat- llxHeader('',$langs->trans("ContractCard"),"Contrat"); $form = new Form($db); +$formfile = new FormFile($db); $objectlignestatic=new ContratLigne($db); +// Load object modContract +$module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_serpis'); +if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') +{ + $module = substr($module, 0, dol_strlen($module)-4); +} +$result=dol_include_once('/core/modules/contract/'.$module.'.php'); +if ($result > 0) +{ + $modCodeContract = new $module(); +} + /********************************************************************* * @@ -865,8 +918,6 @@ if ($action == 'create') $object->date_contrat = dol_now(); - $numct = $object->getNextNumRef($soc); - print '
'; print ''; @@ -877,7 +928,16 @@ if ($action == 'create') print '
'; - print ''; - print '  '; - print ''; + print ''; + print ''; print '
'; if ($obj->socid) { - print ''; + print ''; print img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,20).''; } else @@ -410,7 +422,7 @@ if ($result) // Links Add action and Export vcard print ''; - print ''.img_object($langs->trans("AddAction"),"action").''; + print ''.img_object($langs->trans("AddAction"),"action").''; print '   '; print ''; print img_picto($langs->trans("VCard"),'vcard.png').' '; diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index 73b0f513db9..ab8101dd739 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -98,12 +98,12 @@ if ($id > 0) $objsoc = new Societe($db); $objsoc->fetch($object->socid); - print '
'.$langs->trans("Company").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print '
'.$langs->trans("Company").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print '
'.$langs->trans("Company").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("Company").''; + print '
'.$langs->trans("ThirdParty").''; print $langs->trans("ContactNotLinkedToCompany"); print '
'; // Ref - print ''; + if (! empty($modCodeContract->code_auto)) { + $tmpcode=$langs->trans("Draft"); + } else { + $tmpcode=''; + } + print ''; + + // Ref supplier + print ''; + print ''; // Customer print ''; @@ -960,13 +1020,18 @@ if ($action == 'create') print "
'.$langs->trans('Ref').''.$langs->trans("Draft").'
'.$langs->trans('Ref').''.$tmpcode.'
'.$langs->trans('RefSupplier').'
\n"; + print '
'; + if (is_object($objectsrc)) { print ''; print ''; - } - print '
'; + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) + { + print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); + } + } print "\n"; @@ -981,14 +1046,12 @@ else { $now=dol_now(); - if ($id > 0 || ! empty($ref)) + if ($object->id > 0) { - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db,$object->error); + $object->fetch_thirdparty(); + $result=$object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed if ($result < 0) dol_print_error($db,$object->error); - $result=$object->fetch_thirdparty(); - if ($result < 0) dol_print_error($db,$object->error); $nbofservices=count($object->lines); @@ -1023,7 +1086,7 @@ else if ($action == 'valid') { $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV') + if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) { $numref = $object->getNextNumRef($soc); } @@ -1059,12 +1122,30 @@ else print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref du contrat - print '"; + if (!empty($modCodeContract->code_auto)) { + print '"; + } else { + print ''; + print ''; + print ''; + } + + print ''; + print ''; + print ''; // Customer print ""; @@ -1114,52 +1195,8 @@ else } // Other attributes - $parameters=array('colspan' => ' colspan="3"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - - $res = $object->fetch_optionals($object->id, $extralabels); - if (empty($reshook) && ! empty($extrafields->attribute_label)) { - foreach ($extrafields->attribute_label as $key => $label) { - if ($action == 'edit_extras') { - $value = (isset($_POST ["options_" . $key]) ? $_POST ["options_" . $key] : $object->array_options ["options_" . $key]); - } else { - $value = $object->array_options ["options_" . $key]; - } - if ($extrafields->attribute_type [$key] == 'separate') { - print $extrafields->showSeparator($key); - } else { - print 'attribute_required [$key])) - print ' class="fieldrequired"'; - print '>' . $label . '' . "\n"; - } - } - } - - - + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; print "
'.$langs->trans("Ref").''; - print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); - print "
'.$langs->trans("Ref").''; + print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', ''); + print "
'; + print $form->editfieldkey("Ref",'ref',$object->ref,$object,$user->rights->contrat->creer); + print ''; + print $form->editfieldval("Ref",'ref',$object->ref,$object,$user->rights->contrat->creer); + print '
'; + print $form->editfieldkey("RefSupplier",'ref_supplier',$object->ref_supplier,$object,$user->rights->contrat->creer); + print ''; + print $form->editfieldval("RefSupplier",'ref_supplier',$object->ref_supplier,$object,$user->rights->contrat->creer); + print '
".$langs->trans("Customer")."
'; - // Convert date into timestamp format - if (in_array($extrafields->attribute_type [$key], array('date','datetime'))) { - $value = isset($_POST ["options_" . $key]) ? dol_mktime($_POST ["options_" . $key . "hour"], $_POST ["options_" . $key . "min"], 0, $_POST ["options_" . $key . "month"], $_POST ["options_" . $key . "day"], $_POST ["options_" . $key . "year"]) : $db->jdate($object->array_options ['options_' . $key]); - } - - if ($action == 'edit_extras' && $user->rights->commande->creer && GETPOST('attribute') == $key) { - print '
'; - print ''; - print ''; - print ''; - print ''; - - print $extrafields->showInputField($key, $value); - - print ''; - print '
'; - } else { - print $extrafields->showOutputField($key, $value); - if ($object->statut == 0 && $user->rights->commande->creer) - print '' . img_picto('', 'edit') . ' ' . $langs->trans('Modify') . ''; - } - print '
"; @@ -1260,7 +1297,8 @@ else $productstatic->ref=$objp->label; print $productstatic->getNomUrl(0,'',16); } - if ($objp->description) print '
'.dol_nl2br($objp->description); + if (! empty($conf->global->PRODUIT_DESC_IN_FORM) and $objp->description) + print '
'.dol_nl2br($objp->description); print '
'; + /* + * Documents generes + */ + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->contrat->creer; + $delallowed = $user->rights->contrat->supprimer; + + $var = true; + + $somethingshown = $formfile->show_documents('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); /* * Linked object block */ $somethingshown=$object->showLinkedObjectBlock(); - print ''; - print '
'; + print '
'; + + print '
'; } } diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 6cf04c10522..1399ae40215 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -4,9 +4,10 @@ * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2008 Raphael Bertrand - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2013 Christophe Battarel * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -28,9 +29,9 @@ * \brief File of class to manage contracts */ -require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; -require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; -require_once(DOL_DOCUMENT_ROOT ."/margin/lib/margins.lib.php"); +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/margin/lib/margins.lib.php'; /** * Class to manage contracts @@ -45,6 +46,8 @@ class Contrat extends CommonObject var $id; var $ref; + var $ref_ext; + var $ref_supplier; var $socid; var $societe; // Objet societe var $statut=0; // 0=Draft, @@ -63,6 +66,7 @@ class Contrat extends CommonObject var $note; // deprecated var $note_private; var $note_public; + var $modelpdf; var $fk_projet; @@ -155,16 +159,14 @@ class Contrat extends CommonObject $sql.= " commentaire = '".$this->db->escape($comment)."'"; $sql.= " WHERE rowid = ".$line_id . " AND (statut = 0 OR statut = 3 OR statut = 5)"; - dol_syslog(get_class($this)."::active_line sql=".$sql); + dol_syslog(get_class($this)."::active_line", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTRACT_SERVICE_ACTIVATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTRACT_SERVICE_ACTIVATE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers $this->db->commit(); return 1; @@ -172,7 +174,6 @@ class Contrat extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::active_line error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -207,12 +208,10 @@ class Contrat extends CommonObject $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTRACT_SERVICE_CLOSE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTRACT_SERVICE_CLOSE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers $this->db->commit(); return 1; @@ -220,7 +219,6 @@ class Contrat extends CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::close_line error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -280,9 +278,10 @@ class Contrat extends CommonObject * * @param User $user Objet User * @param string $force_number Reference to force on contract (not implemented yet) + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >0 if OK */ - function validate($user, $force_number='') + function validate($user, $force_number='', $notrigger=0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; global $langs, $conf; @@ -309,6 +308,7 @@ class Contrat extends CommonObject { $num = $this->ref; } + $this->newref = $num; if ($num) { @@ -316,39 +316,54 @@ class Contrat extends CommonObject //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; $sql .= " WHERE rowid = ".$this->id . " AND statut = 0"; - dol_syslog(get_class($this)."::validate sql=".$sql); + dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::validate Echec update - 10 - sql=".$sql, LOG_ERR); dol_print_error($this->db); $error++; + $this->error=$this->db->lasterror(); + } + + // Trigger calls + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('CONTRACT_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) { - $this->oldref = ''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Rename of object directory ($this->ref = old ref, $num = new ref) // to not lose the linked files - $facref = dol_sanitizeFileName($this->ref); - $snumfa = dol_sanitizeFileName($num); - $dirsource = $conf->contract->dir_output.'/'.$facref; - $dirdest = $conf->contract->dir_output.'/'.$snumfa; + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); + $dirsource = $conf->contract->dir_output.'/'.$oldref; + $dirdest = $conf->contract->dir_output.'/'.$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { - $this->oldref = $facref; - dol_syslog("Rename ok"); - // Deleting old PDF in new rep - dol_delete_file($conf->contract->dir_output.'/'.$snumfa.'/'.$facref.'*.*'); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -362,17 +377,6 @@ class Contrat extends CommonObject $this->brouillon=0; $this->date_validation=$now; } - - // Trigger calls - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTRACT_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - } } else { @@ -387,7 +391,6 @@ class Contrat extends CommonObject else { $this->db->rollback(); - $this->error=$this->db->lasterror(); return -1; } @@ -408,7 +411,9 @@ class Contrat extends CommonObject $sql.= " fk_user_author,"; $sql.= " fk_projet,"; $sql.= " fk_commercial_signature, fk_commercial_suivi,"; - $sql.= " note_private, note_public, extraparams"; + $sql.= " note_private, note_public, model_pdf, extraparams"; + $sql.= " ,ref_supplier"; + $sql.= " ,ref_ext"; $sql.= " FROM ".MAIN_DB_PREFIX."contrat"; if ($ref) { @@ -417,7 +422,7 @@ class Contrat extends CommonObject } else $sql.= " WHERE rowid=".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -427,6 +432,8 @@ class Contrat extends CommonObject { $this->id = $result["rowid"]; $this->ref = (!isset($result["ref"]) || !$result["ref"]) ? $result["rowid"] : $result["ref"]; + $this->ref_supplier = $result["ref_supplier"]; + $this->ref_ext = $result["ref_ext"]; $this->statut = $result["statut"]; $this->mise_en_service = $this->db->jdate($result["datemise"]); $this->date_contrat = $this->db->jdate($result["datecontrat"]); @@ -439,6 +446,7 @@ class Contrat extends CommonObject $this->note = $result["note_private"]; // deprecated $this->note_private = $result["note_private"]; $this->note_public = $result["note_public"]; + $this->modelpdf = $result["model_pdf"]; $this->fk_projet = $result["fk_projet"]; // deprecated $this->fk_project = $result["fk_projet"]; @@ -514,7 +522,7 @@ class Contrat extends CommonObject $sql.= " WHERE d.fk_contrat = ".$this->id ." AND d.fk_product = p.rowid"; $sql.= " ORDER by d.rowid ASC"; - dol_syslog(get_class($this)."::fetch_lines sql=".$sql); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -727,7 +735,7 @@ class Contrat extends CommonObject // Insert contract $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,"; $sql.= " fk_commercial_signature, fk_commercial_suivi, fk_projet,"; - $sql.= " ref, entity, note_private, note_public)"; + $sql.= " ref, entity, note_private, note_public, ref_supplier, ref_ext)"; $sql.= " VALUES ('".$this->db->idate($now)."',".$this->socid.",".$user->id; $sql.= ", '".$this->db->idate($this->date_contrat)."'"; $sql.= ",".($this->commercial_signature_id>0?$this->commercial_signature_id:"NULL"); @@ -737,6 +745,8 @@ class Contrat extends CommonObject $sql.= ", ".$conf->entity; $sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL"); $sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL"); + $sql.= ", ".(!empty($this->ref_supplier)?("'".$this->db->escape($this->ref_supplier)."'"):"NULL"); + $sql.= ", ".(!empty($this->ref_ext)?("'".$this->db->escape($this->ref_ext)."'"):"NULL"); $sql.= ")"; $resql=$this->db->query($sql); if ($resql) @@ -745,13 +755,28 @@ class Contrat extends CommonObject $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat"); - // Mise a jour ref - $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) + + // Load object modContract + $module=(! empty($conf->global->CONTRACT_ADDON)?$conf->global->CONTRACT_ADDON:'mod_contract_olive'); + if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { - if ($this->id) + $module = substr($module, 0, dol_strlen($module)-4); + } + $result=dol_include_once('/core/modules/contract/'.$module.'.php'); + if ($result > 0) + { + $modCodeContract = new $module(); + } + + if (!empty($modCodeContract->code_auto)) { + // Mise a jour ref + $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; + if ($this->db->query($sql)) { - $this->ref="(PROV".$this->id.")"; + if ($this->id) + { + $this->ref="(PROV".$this->id.")"; + } } } @@ -778,12 +803,10 @@ class Contrat extends CommonObject if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTRACT_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('CONTRACT_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers if (! $error) { @@ -798,7 +821,6 @@ class Contrat extends CommonObject } else { - $this->error=$interface->error; dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR); $this->db->rollback(); @@ -816,8 +838,7 @@ class Contrat extends CommonObject } else { - $this->error=$langs->trans("UnknownError: ".$this->db->error()." - sql=".$sql); - dol_syslog(get_class($this)."::create - 10 - ".$this->error, LOG_ERR); + $this->error=$langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG); $this->db->rollback(); return -1; @@ -840,6 +861,11 @@ class Contrat extends CommonObject $this->db->begin(); + // Call trigger + $result=$this->call_trigger('CONTRACT_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers + if (! $error) { // Delete linked contacts @@ -863,7 +889,7 @@ class Contrat extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd"; $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".$this->id; - dol_syslog(get_class($this)."::delete contratdet_log sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -884,7 +910,7 @@ class Contrat extends CommonObject $sql= "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log "; $sql.= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".implode(",",$tab_resql).")"; - dol_syslog(get_class($this)."::delete contratdet_log sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -900,7 +926,7 @@ class Contrat extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet"; $sql.= " WHERE fk_contrat=".$this->id; - dol_syslog(get_class($this)."::delete contratdet sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -915,7 +941,7 @@ class Contrat extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete contrat sql=".$sql); + dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { @@ -924,18 +950,6 @@ class Contrat extends CommonObject } } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('CONTRACT_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } - if (! $error) { // We remove directory @@ -962,13 +976,110 @@ class Contrat extends CommonObject } else { - $this->error=$this->db->error(); - dol_syslog(get_class($this)."::delete ERROR ".$this->error, LOG_ERR); + $this->error=$this->db->lasterror(); $this->db->rollback(); return -1; } } + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + function update($user=null, $notrigger=0) + { + global $conf, $langs; + $error=0; + + // Clean parameters + + if (isset($this->ref)) $this->ref=trim($this->ref); + if (isset($this->ref_supplier)) $this->ref_supplier=trim($this->ref_supplier); + if (isset($this->ref_ext)) $this->ref_ext=trim($this->ref_ext); + if (isset($this->entity)) $this->entity=trim($this->entity); + if (isset($this->statut)) $this->statut=trim($this->statut); + if (isset($this->fk_soc)) $this->fk_soc=trim($this->fk_soc); + if (isset($this->fk_projet)) $this->fk_projet=trim($this->fk_projet); + if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature=trim($this->fk_commercial_signature); + if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi=trim($this->fk_commercial_suivi); + if (isset($this->fk_user_mise_en_service)) $this->fk_user_mise_en_service=trim($this->fk_user_mise_en_service); + if (isset($this->fk_user_cloture)) $this->fk_user_cloture=trim($this->fk_user_cloture); + if (isset($this->note_private)) $this->note_private=trim($this->note_private); + if (isset($this->note_public)) $this->note_public=trim($this->note_public); + if (isset($this->import_key)) $this->import_key=trim($this->import_key); + if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams); + + + + // Check parameters + // Put here code to add a control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET"; + + $sql.= " ref=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").","; + $sql.= " ref_supplier=".(isset($this->ref_supplier)?"'".$this->db->escape($this->ref_supplier)."'":"null").","; + $sql.= " ref_ext=".(isset($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null").","; + $sql.= " entity=".$conf->entity.","; + $sql.= " date_contrat=".(dol_strlen($this->date_contrat)!=0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').","; + $sql.= " statut=".(isset($this->statut)?$this->statut:"null").","; + $sql.= " mise_en_service=".(dol_strlen($this->mise_en_service)!=0 ? "'".$this->db->idate($this->mise_en_service)."'" : 'null').","; + $sql.= " fin_validite=".(dol_strlen($this->fin_validite)!=0 ? "'".$this->db->idate($this->fin_validite)."'" : 'null').","; + $sql.= " date_cloture=".(dol_strlen($this->date_cloture)!=0 ? "'".$this->db->idate($this->date_cloture)."'" : 'null').","; + $sql.= " fk_soc=".(isset($this->fk_soc)?$this->fk_soc:"null").","; + $sql.= " fk_projet=".(isset($this->fk_projet)?$this->fk_projet:"null").","; + $sql.= " fk_commercial_signature=".(isset($this->fk_commercial_signature)?$this->fk_commercial_signature:"null").","; + $sql.= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi)?$this->fk_commercial_suivi:"null").","; + $sql.= " fk_user_mise_en_service=".(isset($this->fk_user_mise_en_service)?$this->fk_user_mise_en_service:"null").","; + $sql.= " fk_user_cloture=".(isset($this->fk_user_cloture)?$this->fk_user_cloture:"null").","; + $sql.= " note_private=".(isset($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null").","; + $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").","; + $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null").","; + $sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null").""; + + + $sql.= " WHERE rowid=".$this->id; + + $this->db->begin(); + + $resql = $this->db->query($sql); + if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } + + if (! $error) + { + if (! $notrigger) + { + // Uncomment this and change MYOBJECT to your own tag if you + // want this action calls a trigger. + + //// Call triggers + //$result=$this->call_trigger('MYOBJECT_MODIFY',$user); + //if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail} + //// End call triggers + } + } + + // Commit or rollback + if ($error) + { + foreach($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error.=($this->error?', '.$errmsg:$errmsg); + } + $this->db->rollback(); + return -1*$error; + } + else + { + $this->db->commit(); + return 1; + } + } + /** * Ajoute une ligne de contrat en base @@ -1031,7 +1142,7 @@ class Contrat extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->societe, $mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1,'', $localtaxes_type); $total_ht = $tabprice[0]; @@ -1090,7 +1201,7 @@ class Contrat extends CommonObject if ($date_end > 0) { $sql.= ",'".$this->db->idate($date_end)."'"; } $sql.= ")"; - dol_syslog(get_class($this)."::addline sql=".$sql); + dol_syslog(get_class($this)."::addline", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -1098,12 +1209,20 @@ class Contrat extends CommonObject $result=$this->update_statut($user); if ($result > 0) { + // Call trigger + $result=$this->call_trigger('LINECONTRACT_CREATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -1; + } + // End call triggers + $this->db->commit(); return 1; } else { - dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR); $this->db->rollback(); return -1; } @@ -1112,7 +1231,6 @@ class Contrat extends CommonObject { $this->db->rollback(); $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::addline ".$this->error,LOG_ERR); return -1; } } @@ -1179,7 +1297,7 @@ class Contrat extends CommonObject // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($tvatx,0,$mysoc); + $localtaxes_type=getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtaxtx1, $txlocaltaxtx2, 0, $price_base_type, $info_bits, 1, '', $localtaxes_type); $total_ht = $tabprice[0]; @@ -1237,13 +1355,22 @@ class Contrat extends CommonObject else { $sql.=",date_cloture=null"; } $sql .= " WHERE rowid = ".$rowid; - dol_syslog(get_class($this)."::updateline sql=".$sql); + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $result=$this->update_statut($user); if ($result >= 0) { + // Call trigger + $result=$this->call_trigger('LINECONTRACT_UPDATE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -3; + } + // End call triggers + $this->db->commit(); return 1; } @@ -1278,25 +1405,27 @@ class Contrat extends CommonObject if ($this->statut >= 0) { + + // Call trigger + $result=$this->call_trigger('LINECONTRACT_DELETE',$user); + if ($result < 0) return -1; + // End call triggers + + $this->db->begin(); + $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet"; $sql.= " WHERE rowid=".$idline; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + $this->db->rollback(); return -1; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINECONTRACT_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - + $this->db->commit(); return 1; } else @@ -1414,7 +1543,7 @@ class Contrat extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='contract'; @@ -1491,7 +1620,7 @@ class Contrat extends CommonObject $sql.= " WHERE fk_contrat =".$this->id; if ($statut >= 0) $sql.= " AND statut = '$statut'"; - dol_syslog(get_class($this)."::array_detail() sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1527,7 +1656,7 @@ class Contrat extends CommonObject $sql.= " WHERE fk_soc =".$this->socid; if ($option == 'others') $sql.= " AND c.rowid != ".$this->id; - dol_syslog(get_class($this)."::getOtherContracts() sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1748,19 +1877,48 @@ class Contrat extends CommonObject $this->total_tva = $xnbp*19.6; $this->total_ttc = $xnbp*119.6; } + + /** + * Create a document onto disk according to template module. + * + * @param string $modele Force model to use ('' to not force) + * @param Translate $outputlangs Object langs to use for output + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf,$user,$langs; + + $langs->load("contracts"); + + // Positionne le modele sur le nom du modele a utiliser + if (! dol_strlen($modele)) + { + if (! empty($conf->global->CONTRACT_ADDON_PDF)) + { + $modele = $conf->global->CONTRACT_ADDON_PDF; + } + else + { + $modele = 'strato'; + } + } + + $modelpath = "core/modules/contract/doc/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } } /** * Classe permettant la gestion des lignes de contrats */ -class ContratLigne +class ContratLigne extends CommonObject { - var $db; //!< To store db handler - var $error; //!< To return error code (or message) - var $errors=array(); //!< To return several error codes (or messages) - //var $element='contratdet'; //!< Id that identify managed objects - //var $table_element='contratdet'; //!< Name of table without prefix where object is stored var $id; var $ref; @@ -1901,7 +2059,7 @@ class ContratLigne $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='contract'; @@ -1967,7 +2125,7 @@ class ContratLigne if ($id) $sql.= " WHERE t.rowid = ".$id; if ($ref) $sql.= " WHERE t.rowid = '".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -2020,7 +2178,6 @@ class ContratLigne else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -2087,6 +2244,8 @@ class ContratLigne $this->pa_ht = $this->subprice * (1 - $this->remise_percent / 100); } + $this->db->begin(); + // Update request $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET"; $sql.= " fk_contrat='".$this->fk_contrat."',"; @@ -2122,7 +2281,7 @@ class ContratLigne $sql.= " commentaire='".$this->db->escape($this->commentaire)."'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -2133,20 +2292,19 @@ class ContratLigne else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); + $this->db->rollback(); return -1; } if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINECONTRACT_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINECONTRACT_UPDATE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } + $this->db->commit(); return 1; } @@ -2170,7 +2328,7 @@ class ContratLigne $sql.= ",total_ttc=".price2num($this->total_ttc,'MT').""; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog(get_class($this)."::update_total sql=".$sql); + dol_syslog(get_class($this)."::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -2181,7 +2339,6 @@ class ContratLigne else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -2203,7 +2360,7 @@ class ContratLigne if (! $sql) return -1; //print $sql; - dol_syslog(get_class($this)."::get_element_list sql=" . $sql); + dol_syslog(get_class($this)."::get_element_list", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -2229,5 +2386,3 @@ class ContratLigne } } - - diff --git a/htdocs/contrat/class/index.html b/htdocs/contrat/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index dcec3598e7f..1528e472cbe 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -67,15 +67,14 @@ if ($action == 'addcontact' && $user->rights->contrat->creer) } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; - } - else - { - $mesg = '
'.$object->error.'
'; + $msg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); + } else { + $mesg = $object->error; } + + setEventMessage($mesg, 'errors'); } } @@ -117,8 +116,6 @@ $formcompany= new FormCompany($db); $contactstatic=new Contact($db); $userstatic=new User($db); -dol_htmloutput_mesg($mesg); - /* *************************************************************************** */ /* */ /* Mode vue et edition */ @@ -129,8 +126,6 @@ if ($id > 0 || ! empty($ref)) { if ($object->fetch($id, $ref) > 0) { - dol_htmloutput_mesg($mesg); - $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -144,7 +139,7 @@ if ($id > 0 || ! empty($ref)) */ print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Reference du contrat print ''; print ''; @@ -298,7 +298,7 @@ $sql.= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NULL OR cd.d $sql.= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now)."')",1,0).') as nb_expired,'; $sql.= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now - $conf->contrat->services->expires->warning_delay)."')",1,0).') as nb_late,'; $sql.= ' sum('.$db->ifsql("cd.statut=5",1,0).') as nb_closed,'; -$sql.= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid as socid"; +$sql.= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s,"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; $sql.= " ".MAIN_DB_PREFIX."contrat as c"; @@ -312,7 +312,7 @@ $sql.= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid"; $sql.= " ORDER BY c.tms DESC"; $sql.= " LIMIT ".$max; -dol_syslog("contrat/index.php sql=".$sql, LOG_DEBUG); +dol_syslog("contrat/index.php", LOG_DEBUG); $result=$db->query($sql); if ($result) { @@ -342,7 +342,7 @@ if ($result) print ''; print ''; print ''; @@ -369,7 +369,7 @@ print '
'; // Last modified services $sql = "SELECT c.ref, c.fk_soc, "; $sql.= " cd.rowid as cid, cd.statut, cd.label, cd.fk_product, cd.description as note, cd.fk_contrat, cd.date_fin_validite,"; -$sql.= " s.nom,"; +$sql.= " s.nom as name,"; $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype"; $sql.= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; @@ -416,17 +416,17 @@ if ($resql) } else { - print ''.img_object($langs->trans("ShowService"),"service"); + print ''.img_object($langs->trans("ShowService"),"service"); if ($obj->label) print ' '.dol_trunc($obj->label,20).''; else print ' '.dol_trunc($obj->note,20); } print ''; print ''; - print ''; @@ -447,7 +447,7 @@ print '
'; // Not activated services $sql = "SELECT c.ref, c.fk_soc, cd.rowid as cid, cd.statut, cd.label, cd.fk_product, cd.description as note, cd.fk_contrat,"; -$sql.= " s.nom,"; +$sql.= " s.nom as name,"; $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype"; $sql.= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; @@ -496,14 +496,14 @@ if ($resql) } else { - print ''.img_object($langs->trans("ShowService"),"service"); + print ''.img_object($langs->trans("ShowService"),"service"); if ($obj->label) print ' '.dol_trunc($obj->label,20).''; else print ' '.dol_trunc($obj->note,20); } print ''; print ''; print ''; print ''; print ''; - $colspan='0'; - } - else - { - $out .= ''; - } - // Convert date into timestamp format - if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) - { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]); - } - - if($extrafields->attribute_required[$key]) - $label = ''.$label.''; - - $out .= ''; - $out .=''; - - switch($mode) { - case "view": - $out .= $extrafields->showOutputField($key,$value); - break; - case "edit": - $out .= $extrafields->showInputField($key,$value,'',$keyprefix); - break; - } - - $out .= ''."\n"; - - if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; - else $out .= ''; - $e++; - } - } - $out .= "\n"; - $out .= ' '; - $out .= ' - '; - } - return $out; - } - - /** * Function to check if an object is used by others. * Check is done into this->childtables. There is no check into llx_element_element. @@ -2437,7 +2214,6 @@ abstract class CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete error -1 ".$this->error, LOG_ERR); return -1; } } @@ -2486,7 +2262,7 @@ abstract class CommonObject $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det"; $sql.= " WHERE ".$this->fk_element." = ".$this->id; - dol_syslog(get_class($this).'::getTotalDiscount sql='.$sql); + dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -2507,7 +2283,6 @@ abstract class CommonObject $i++; } } - else dol_syslog(get_class($this).'::getTotalDiscount '.$this->db->lasterror(), LOG_ERR); //print $total_discount; exit; return price2num($total_discount); @@ -2528,12 +2303,11 @@ abstract class CommonObject $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null"); $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::setExtraParameters sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::setExtraParameters ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2736,33 +2510,33 @@ abstract class CommonObject if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ''; // Description - print ''; + print ''; // VAT - print ''; + print ''; // Price HT - print ''; + print ''; - if ($conf->global->MAIN_FEATURES_LEVEL > 1) print ''; + if ($inputalsopricewithtax) print ''; // Qty - print ''; + print ''; // Reduction short - print ''; + print ''; if (! empty($conf->margin->enabled) && empty($user->societe_id)) { if ($conf->global->MARGIN_TYPE == "1") - print ''; + print ''; else - print ''; + print ''; if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) - print ''; + print ''; if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) - print ''; + print ''; } // Total HT @@ -2799,6 +2573,11 @@ abstract class CommonObject $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); $reshook=$hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks } + else + { + $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline); + $reshook=$hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + } } else { @@ -3233,24 +3012,37 @@ abstract class CommonObject if (! $user->rights->margins->liretous) return; - $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT); + $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); $marginInfo = $this->getMarginInfos($force_price); - print '
'.$langs->trans("Ref").''; diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index e17a0c67389..6c520105c36 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -107,7 +107,7 @@ if ($object->id) print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Reference print ''; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 772b0e1ecdc..02a580174c3 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -75,7 +75,7 @@ print '
'; if (! empty($conf->contrat->enabled)) { $var=false; - print '
'; + print ''; print ''; print '
'.$langs->trans('Ref').''.$form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '').'
'; print ''; @@ -227,7 +227,7 @@ print "
'.$langs->trans("SearchAContract").'

"; if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $sql = "SELECT c.rowid as ref, c.rowid,"; - $sql.= " s.nom, s.rowid as socid"; + $sql.= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.rowid = c.fk_soc"; @@ -262,7 +262,7 @@ if (! empty($conf->contrat->enabled) && $user->rights->contrat->lire) print '
'; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'',16); print ''; $staticcompany->id=$obj->socid; - $staticcompany->nom=$obj->nom; + $staticcompany->name=$obj->name; print $staticcompany->getNomUrl(1,'',20); print ''.dol_print_date($obj->tms,'dayhour').''; $staticcompany->id=$obj->fk_soc; - $staticcompany->nom=$obj->nom; + $staticcompany->name=$obj->name; print $staticcompany->getNomUrl(1,'',20); print ''; + print ''; $dateend=$db->jdate($obj->date_fin_validite); print $staticcontratligne->LibStatut($obj->statut, 3, ($dateend && $dateend < $now)?1:0); print ''; $staticcompany->id=$obj->fk_soc; - $staticcompany->nom=$obj->nom; + $staticcompany->name=$obj->name; print $staticcompany->getNomUrl(1,'',20); print ''; @@ -526,7 +526,7 @@ print '
'; // Expired services $sql = "SELECT c.ref, c.fk_soc, cd.rowid as cid, cd.statut, cd.label, cd.fk_product, cd.description as note, cd.fk_contrat,"; -$sql.= " s.nom,"; +$sql.= " s.nom as name,"; $sql.= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype"; $sql.= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; @@ -576,14 +576,14 @@ if ($resql) } else { - print '
'.img_object($langs->trans("ShowService"),"service"); + print ''.img_object($langs->trans("ShowService"),"service"); if ($obj->label) print ' '.dol_trunc($obj->label,20).''; else print ' '.dol_trunc($obj->note,20); } print '
'; $staticcompany->id=$obj->fk_soc; - $staticcompany->nom=$obj->nom; + $staticcompany->name=$obj->name; print $staticcompany->getNomUrl(1,'',20); print ''; diff --git a/htdocs/contrat/liste.php b/htdocs/contrat/list.php similarity index 74% rename from htdocs/contrat/liste.php rename to htdocs/contrat/list.php index e1e49a5d7fd..debe18e995e 100644 --- a/htdocs/contrat/liste.php +++ b/htdocs/contrat/list.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2010 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2013 Cédric Salvador + * Copyright (C) 2014 Juanjo Menent * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,7 +20,7 @@ */ /** - * \file htdocs/contrat/liste.php + * \file htdocs/contrat/list.php * \ingroup contrat * \brief Page liste des contrats */ @@ -30,6 +31,7 @@ require_once (DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"); $langs->load("contracts"); $langs->load("products"); $langs->load("companies"); +$langs->load("compta"); $sortfield=GETPOST('sortfield','alpha'); $sortorder=GETPOST('sortorder','alpha'); @@ -38,10 +40,11 @@ if ($page == -1) { $page = 0 ; } $limit = $conf->liste_limit; $offset = $limit * $page ; -$search_nom=GETPOST('search_nom'); +$search_name=GETPOST('search_name'); $search_contract=GETPOST('search_contract'); +$search_ref_supplier=GETPOST('search_ref_supplier','alpha'); $sall=GETPOST('sall'); -$statut=GETPOST('statut')?GETPOST('statut'):1; +$search_status=GETPOST('search_status'); $socid=GETPOST('socid'); if (! $sortfield) $sortfield="c.rowid"; @@ -55,6 +58,17 @@ $result = restrictedArea($user, 'contrat', $id); $staticcontrat=new Contrat($db); $staticcontratligne=new ContratLigne($db); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_name=""; + $search_contract=""; + $search_ref_supplier=""; + $sall=""; + $search_status=""; +} + +if ($search_status == '') $search_status=1; + /* * View @@ -65,13 +79,13 @@ $now=dol_now(); llxHeader(); $sql = 'SELECT'; +$sql.= " c.rowid as cid, c.ref, c.datec, c.date_contrat, c.statut, c.ref_supplier,"; +$sql.= " s.nom as name, s.rowid as socid,"; $sql.= ' SUM('.$db->ifsql("cd.statut=0",1,0).') as nb_initial,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NULL OR cd.date_fin_validite >= '".$db->idate($now)."')",1,0).') as nb_running,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now)."')",1,0).') as nb_expired,'; $sql.= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AND cd.date_fin_validite < '".$db->idate($now - $conf->contrat->services->expires->warning_delay)."')",1,0).') as nb_late,'; -$sql.= ' SUM('.$db->ifsql("cd.statut=5",1,0).') as nb_closed,'; -$sql.= " c.rowid as cid, c.ref, c.datec, c.date_contrat, c.statut,"; -$sql.= " s.nom, s.rowid as socid"; +$sql.= ' SUM('.$db->ifsql("cd.statut=5",1,0).') as nb_closed'; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ", ".MAIN_DB_PREFIX."contrat as c"; @@ -80,18 +94,20 @@ $sql.= " WHERE c.fk_soc = s.rowid "; $sql.= " AND c.entity = ".$conf->entity; if ($socid) $sql.= " AND s.rowid = ".$socid; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; -if ($search_nom) { - $sql .= natural_search('s.nom', $search_nom); +if ($search_name) { + $sql .= natural_search('s.nom', $search_name); } if ($search_contract) { $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); } +if (!empty($search_ref_supplier)) { + $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); +} if ($sall) { $sql .= natural_search(array('s.nom', 'cd.label', 'cd.description'), $sall); } -$sql.= " GROUP BY c.rowid, c.ref, c.datec, c.date_contrat, c.statut,"; -$sql.= " s.nom, s.rowid"; -$sql.= " ORDER BY $sortfield $sortorder"; +$sql.= " GROUP BY c.rowid, c.ref, c.datec, c.date_contrat, c.statut, c.ref_supplier, s.nom, s.rowid"; +$sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($conf->liste_limit + 1, $offset); $resql=$db->query($sql); @@ -100,14 +116,16 @@ if ($resql) $num = $db->num_rows($resql); $i = 0; - print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], '&search_contract='.$search_contract.'&search_nom='.$search_nom, $sortfield, $sortorder,'',$num); + print_barre_liste($langs->trans("ListOfContracts"), $page, $_SERVER["PHP_SELF"], '&search_contract='.$search_contract.'&search_name='.$search_name, $sortfield, $sortorder,'',$num); print ''; print ''; $param='&search_contract='.$search_contract; - $param.='&search_nom='.$search_nom; + $param.='&search_name='.$search_name; + $param.='&search_ref_supplier='.$search_ref_supplier; print_liste_field_titre($langs->trans("Ref"), $_SERVER["PHP_SELF"], "c.rowid","","$param",'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("RefCustomer"), $_SERVER["PHP_SELF"], "c.ref_supplier","","$param",'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"), $_SERVER["PHP_SELF"], "s.nom","","$param",'',$sortfield,$sortorder); //print_liste_field_titre($langs->trans("DateCreation"), $_SERVER["PHP_SELF"], "c.datec","","$param",'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateContract"), $_SERVER["PHP_SELF"], "c.date_contrat","","$param",'align="center"',$sortfield,$sortorder); @@ -125,13 +143,16 @@ if ($resql) print ''; print ''; print ''; + print ''; print ''; //print ''; - print '"; - print "\n"; + print '\n"; print ''; $var=true; @@ -140,11 +161,12 @@ if ($resql) $obj = $db->fetch_object($resql); $var=!$var; print ''; - print ''; - print ''; + print ''; + print ''; //print ''; print ''; //print ''; diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index 3ac3ca47496..502b354ee69 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -64,8 +64,6 @@ $form = new Form($db); if ($id > 0 || ! empty($ref)) { - dol_htmloutput_mesg($mesg); - $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -77,7 +75,7 @@ if ($id > 0 || ! empty($ref)) print '
'; - print ''; + print ''; + print ''; + print ''; print '  '; - print "
'; + print ''; + print "
'; + print ''; print img_object($langs->trans("ShowContract"),"contract").' '.(isset($obj->ref) ? $obj->ref : $obj->cid) .''; if ($obj->nb_late) print img_warning($langs->trans("Late")); print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.$obj->ref_supplier.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.dol_print_date($obj->datec).''.dol_print_date($db->jdate($obj->date_contrat)).''.$staticcontrat->LibStatut($obj->statut,3).'
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Reference print ''; diff --git a/htdocs/contrat/services.php b/htdocs/contrat/services.php index 382dcad5e93..22ae64ef9cd 100644 --- a/htdocs/contrat/services.php +++ b/htdocs/contrat/services.php @@ -44,7 +44,7 @@ if (! $sortfield) $sortfield="c.rowid"; if (! $sortorder) $sortorder="ASC"; $filter=GETPOST("filter"); -$search_nom=GETPOST("search_nom"); +$search_name=GETPOST("search_name"); $search_contract=GETPOST("search_contract"); $search_service=GETPOST("search_service"); $statut=GETPOST('statut')?GETPOST('statut'):1; @@ -69,6 +69,21 @@ $staticcontrat=new Contrat($db); $staticcontratligne=new ContratLigne($db); $companystatic=new Societe($db); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_name=""; + $search_contract=""; + $search_service=""; + $op1month=""; + $op1day=""; + $op1year=""; + $filter_op1=""; + $op2month=""; + $op2day=""; + $op2year=""; + $filter_op2=""; +} + /* * View */ @@ -80,7 +95,7 @@ $form=new Form($db); llxHeader(); $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut,"; -$sql.= " s.rowid as socid, s.nom,"; +$sql.= " s.rowid as socid, s.nom as name,"; $sql.= " cd.rowid, cd.description, cd.statut,"; $sql.= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype,"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; @@ -101,7 +116,7 @@ if ($mode == "0") $sql.= " AND cd.statut = 0"; if ($mode == "4") $sql.= " AND cd.statut = 4"; if ($mode == "5") $sql.= " AND cd.statut = 5"; if ($filter == "expired") $sql.= " AND cd.date_fin_validite < '".$db->idate($now)."'"; -if ($search_nom) $sql.= " AND s.nom LIKE '%".$db->escape($search_nom)."%'"; +if ($search_name) $sql.= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; if ($search_contract) $sql.= " AND c.rowid = '".$db->escape($search_contract)."'"; if ($search_service) $sql.= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; if ($socid > 0) $sql.= " AND s.rowid = ".$socid; @@ -113,7 +128,7 @@ $sql .= $db->order($sortfield,$sortorder); $sql .= $db->plimit($limit + 1, $offset); //print $sql; -dol_syslog("contrat/services.php sql=".$sql); +dol_syslog("contrat/services.php", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -122,7 +137,7 @@ if ($resql) $param=''; if ($search_contract) $param.='&search_contract='.urlencode($search_contract); - if ($search_nom) $param.='&search_nom='.urlencode($search_nom); + if ($search_name) $param.='&search_name='.urlencode($search_name); if ($search_service) $param.='&search_service='.urlencode($search_service); if ($mode) $param.='&mode='.$mode; if ($filter) $param.='&filter='.$filter; @@ -136,24 +151,24 @@ if ($resql) if ($mode == "4" && $filter != "expired") $title=$langs->trans("ListOfRunningServices"); if ($mode == "4" && $filter == "expired") $title=$langs->trans("ListOfExpiredServices"); if ($mode == "5") $title=$langs->trans("ListOfClosedServices"); - print_barre_liste($title, $page, "services.php", $param, $sortfield, $sortorder,'',$num); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,'',$num); print '
'.$langs->trans('Ref').''.$form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '').'
'; print ''; - print_liste_field_titre($langs->trans("Contract"),"services.php", "c.rowid",$param,"","",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Service"),"services.php", "p.description",$param,"","",$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Company"),"services.php", "s.nom",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Contract"),$_SERVER["PHP_SELF"], "c.rowid",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Service"),$_SERVER["PHP_SELF"], "p.description",$param,"","",$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"], "s.nom",$param,"","",$sortfield,$sortorder); // Date debut - if ($mode == "0") print_liste_field_titre($langs->trans("DateStartPlannedShort"),"services.php", "cd.date_ouverture_prevue",$param,'',' align="center"',$sortfield,$sortorder); - if ($mode == "" || $mode > 0) print_liste_field_titre($langs->trans("DateStartRealShort"),"services.php", "cd.date_ouverture",$param,'',' align="center"',$sortfield,$sortorder); + if ($mode == "0") print_liste_field_titre($langs->trans("DateStartPlannedShort"),$_SERVER["PHP_SELF"], "cd.date_ouverture_prevue",$param,'',' align="center"',$sortfield,$sortorder); + if ($mode == "" || $mode > 0) print_liste_field_titre($langs->trans("DateStartRealShort"),$_SERVER["PHP_SELF"], "cd.date_ouverture",$param,'',' align="center"',$sortfield,$sortorder); // Date fin - if ($mode == "" || $mode < 5) print_liste_field_titre($langs->trans("DateEndPlannedShort"),"services.php", "cd.date_fin_validite",$param,'',' align="center"',$sortfield,$sortorder); - else print_liste_field_titre($langs->trans("DateEndRealShort"),"services.php", "cd.date_cloture",$param,'',' align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Status"),"services.php", "cd.statut,c.statut",$param,"","align=\"right\"",$sortfield,$sortorder); + if ($mode == "" || $mode < 5) print_liste_field_titre($langs->trans("DateEndPlannedShort"),$_SERVER["PHP_SELF"], "cd.date_fin_validite",$param,'',' align="center"',$sortfield,$sortorder); + else print_liste_field_titre($langs->trans("DateEndRealShort"),$_SERVER["PHP_SELF"], "cd.date_cloture",$param,'',' align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"], "cd.statut,c.statut",$param,"","align=\"right\"",$sortfield,$sortorder); print "\n"; - print ''; + print ''; print ''; print ''; @@ -168,7 +183,7 @@ if ($resql) print ''; // Third party print ''; print ''; - print '"; - print "\n"; + print '\n"; print ''; $contractstatic=new Contrat($db); @@ -225,7 +240,7 @@ if ($resql) // Third party print ''; diff --git a/htdocs/contrat/tpl/index.html b/htdocs/contrat/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/contrat/tpl/linkedobjectblock.tpl.php b/htdocs/contrat/tpl/linkedobjectblock.tpl.php index 702ed8d81ff..d94d45489fd 100644 --- a/htdocs/contrat/tpl/linkedobjectblock.tpl.php +++ b/htdocs/contrat/tpl/linkedobjectblock.tpl.php @@ -43,7 +43,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > + trans("ShowContract"),"contract").' '.$object->ref; ?> diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index 89edfcbae8e..d5f8ea7c18c 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -141,7 +141,7 @@ if ($action == 'add') } } - $result=$extrafields->addExtraField($_POST['attrname'],$_POST['label'],$_POST['type'],$_POST['pos'],$extrasize,$elementtype,(GETPOST('unique')?1:0),(GETPOST('required')?1:0),$default_value,$params); + $result=$extrafields->addExtraField($_POST['attrname'],$_POST['label'],$_POST['type'],$_POST['pos'],$extrasize,$elementtype,(GETPOST('unique')?1:0),(GETPOST('required')?1:0),$default_value,$params,(GETPOST('alwayseditable')?1:0)); if ($result > 0) { setEventMessage($langs->trans('SetupSaved')); @@ -278,7 +278,7 @@ if ($action == 'update') $params['options'][$key] = $value; } } - $result=$extrafields->update($_POST['attrname'],$_POST['label'],$_POST['type'],$extrasize,$elementtype,(GETPOST('unique')?1:0),(GETPOST('required')?1:0),$pos,$params); + $result=$extrafields->update($_POST['attrname'],$_POST['label'],$_POST['type'],$extrasize,$elementtype,(GETPOST('unique')?1:0),(GETPOST('required')?1:0),$pos,$params,(GETPOST('alwayseditable')?1:0)); if ($result > 0) { setEventMessage($langs->trans('SetupSaved')); diff --git a/htdocs/core/actions_printipp.inc.php b/htdocs/core/actions_printipp.inc.php new file mode 100644 index 00000000000..3c18faa813b --- /dev/null +++ b/htdocs/core/actions_printipp.inc.php @@ -0,0 +1,45 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * or see http://www.gnu.org/ + */ + +/** + * \file htdocs/core/actions_printipp.inc.php + * \brief Code for actions print_file to print file using ipp + */ + + +// $action must be defined +// $db, $user, $conf, $langs must be defined +// Filename to print must be provided into 'file' parameter + +// Print file +if ($action == 'print_file' and $user->rights->printipp->read) +{ + $langs->load("printipp"); + require_once DOL_DOCUMENT_ROOT . '/core/class/dolprintipp.class.php'; + $printer = new dolPrintIPP($db, $conf->global->PRINTIPP_HOST, $conf->global->PRINTIPP_PORT, $user->login, $conf->global->PRINTIPP_USER, $conf->global->PRINTIPP_PASSWORD); + $result = $printer->print_file(GETPOST('file', 'alpha'), GETPOST('printer', 'alpha')); + if ($result) + { + setEventMessage($result,'warnings'); + } + else + { + setEventMessage($langs->trans("FileWasSentToPrinter", basename(GETPOST('file')))); + } + $action = ''; +} diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 3af164abfab..40e177404f9 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -26,7 +26,8 @@ // $id must be defined // $actiontypecode must be defined - +// $paramname must be defined +// $mode must be defined /* * Add file in email form @@ -86,10 +87,10 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO if ($result > 0) { - if ($_POST['sendto']) + if (trim($_POST['sendto'])) { // Recipient is provided into free text - $sendto = $_POST['sendto']; + $sendto = trim($_POST['sendto']); $sendtoid = 0; } elseif ($_POST['receiver'] != '-1') @@ -106,6 +107,22 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $sendtoid = $_POST['receiver']; } } + if (trim($_POST['sendtocc'])) + { + $sendtocc = trim($_POST['sendtocc']); + } + elseif ($_POST['receivercc'] != '-1') + { + // Recipient was provided from combo list + if ($_POST['receivercc'] == 'thirdparty') // Id of third party + { + $sendtocc = $thirdparty->email; + } + else // Id du contact + { + $sendtocc = $thirdparty->contact_get_property($_POST['receivercc'],'email'); + } + } if (dol_strlen($sendto)) { @@ -114,19 +131,25 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>'; $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>'; $message = $_POST['message']; - $sendtocc = $_POST['sendtocc']; + $sendtocc = $sendtocc; + $sendtobcc= GETPOST('sendtoccc'); + if ($mode == 'emailfromproposal') $sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO); + if ($mode == 'emailfromorder') $sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO); + if ($mode == 'emailfrominvoice') $sendtobcc = (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)?'':$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO); + $deliveryreceipt = $_POST['deliveryreceipt']; if ($action == 'send' || $action == 'relance') { if (dol_strlen($_POST['subject'])) $subject = $_POST['subject']; - $actionmsg2=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg2=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } } @@ -141,7 +164,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Send mail require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; - $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); + $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1); if ($mailfile->error) { $mesgs[]='
'.$mailfile->error.'
'; @@ -165,7 +188,7 @@ if (($action == 'send' || $action == 'relance') && ! $_POST['addfile'] && ! $_PO // Appel des triggers include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; $interface=new Interfaces($db); - $result=$interface->run_triggers('COMPANY_SENTBYMAIL',$object,$user,$langs,$conf); + $result=$interface->run_triggers($trigger_name,$object,$user,$langs,$conf); if ($result < 0) { $error++; $this->errors=$interface->errors; } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index d1a64f6b256..997e27adb20 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -153,7 +153,7 @@ if ($type == 'directory') $sorting = (strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC); // Right area. If module is defined, we are in automatic ecm. - $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project'); + $automodules = array('company', 'invoice', 'invoice_supplier', 'propal', 'order', 'order_supplier', 'contract', 'product', 'tax', 'project', 'fichinter', 'user'); // TODO change for multicompany sharing // Auto area for suppliers invoices @@ -184,6 +184,10 @@ if ($type == 'directory') else if ($module == 'tax') $upload_dir = $conf->tax->dir_output; // Auto area for projects else if ($module == 'project') $upload_dir = $conf->projet->dir_output; + // Auto area for interventions + else if ($module == 'fichinter') $upload_dir = $conf->ficheinter->dir_output; + // Auto area for users + else if ($module == 'user') $upload_dir = $conf->user->dir_output; if (in_array($module, $automodules)) { @@ -203,7 +207,6 @@ if ($type == 'directory') if ($section === '0') { $filearray=array(); - $textifempty='
'.$langs->trans("DirNotSynchronizedSyncFirst").'

'; } else $filearray=dol_dir_list($upload_dir,"files",0,'',array('^\.','(\.meta|_preview\.png)$','^temp$','^CVS$'),$sortfield, $sorting,1); @@ -212,6 +215,7 @@ if ($type == 'directory') $param.='§ion='.$section; $textifempty = $langs->trans('NoFileFound'); } + else if ($section === '0') $textifempty='
'.$langs->trans("DirNotSynchronizedSyncFirst").'

'; else $textifempty=($showonrightsize=='featurenotyetavailable'?$langs->trans("FeatureNotYetAvailable"):$langs->trans("ECMSelectASection")); $formfile->list_of_documents($filearray,'','ecm',$param,1,$relativepath,$user->rights->ecm->upload,1,$textifempty,$maxlengthname,'',$url); diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php index b4ceaeaced1..ae70d1a418a 100644 --- a/htdocs/core/ajax/ajaxdirtree.php +++ b/htdocs/core/ajax/ajaxdirtree.php @@ -145,7 +145,8 @@ if (file_exists($fullpathselecteddir)) { if (empty($val['fullrelativename'])) // If we did not find entry into database, but found a directory (dol_is_dir was ok at previous test) { - $val['fullrelativename']=$file; $val['id']=0; + $val['fullrelativename']=$file; + $val['id']=0; $val['label']=$file; $val['description']=''; $nboffilesinsubdir=$langs->trans("Unknown"); diff --git a/htdocs/core/ajax/index.html b/htdocs/core/ajax/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/core/ajax/index.php b/htdocs/core/ajax/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/core/ajax/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/core/ajax/loadinplace.php b/htdocs/core/ajax/loadinplace.php index 69a0bbc72c7..de3a4e57d19 100644 --- a/htdocs/core/ajax/loadinplace.php +++ b/htdocs/core/ajax/loadinplace.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2011-2014 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 @@ -98,7 +98,7 @@ if (! empty($field) && ! empty($element) && ! empty($table_element) && ! empty($ dol_include_once('/'.$module.'/class/actions_'.$subelement.'.class.php'); $classname = 'Actions'.ucfirst($subelement); $object = new $classname($db); - $ret = $object->$methodname(); + $ret = $object->$methodname($fk_element); if ($ret > 0) echo json_encode($object->$cachename); } } diff --git a/htdocs/core/ajax/objectonoff.php b/htdocs/core/ajax/objectonoff.php new file mode 100644 index 00000000000..6ac5abd3bbb --- /dev/null +++ b/htdocs/core/ajax/objectonoff.php @@ -0,0 +1,49 @@ +. + */ + +/** + * \file htdocs/core/ajax/productonoff.php + * \brief File to set tosell and tobuy for product + */ + +if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal +if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); +if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); +if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); +if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1'); +if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; + +$action=GETPOST('action','alpha'); +$id=GETPOST('id', 'int'); +$value=GETPOST('value', 'int'); +$field=GETPOST('field', 'alpha'); +$element=GETPOST('element', 'alpha'); + +$object = new GenericObject($db); +/* + * View + */ + +top_httphead(); + +print ''."\n"; + +// Registering new values +if (($action == 'set') && ! empty($id)) + $object->setValueFrom($field, $value, $element, $id); diff --git a/htdocs/core/ajax/ziptown.php b/htdocs/core/ajax/ziptown.php index 291d7a6647d..30e0211ece1 100644 --- a/htdocs/core/ajax/ziptown.php +++ b/htdocs/core/ajax/ziptown.php @@ -63,14 +63,14 @@ if (! empty($_GET['zipcode']) || ! empty($_GET['town'])) if (! empty($conf->global->MAIN_USE_ZIPTOWN_DICTIONNARY)) // Use zip-town table { $sql = "SELECT z.rowid, z.zip, z.town, z.fk_county, z.fk_pays as fk_country"; - $sql.= ", p.rowid as fk_country, p.code as country_code, p.libelle as country"; + $sql.= ", c.rowid as fk_country, c.code as country_code, c.label as country"; $sql.= ", d.rowid as fk_county, d.code_departement as county_code, d.nom as county"; $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as z"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."c_departements as d ON z.fk_county = d.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_regions as r ON d.fk_region = r.code_region,"; - $sql.= " ".MAIN_DB_PREFIX."c_pays as p"; - $sql.= " WHERE z.fk_pays = p.rowid"; - $sql.= " AND z.active = 1 AND p.active = 1"; + $sql.= " ".MAIN_DB_PREFIX."c_country as c"; + $sql.= " WHERE z.fk_pays = c.rowid"; + $sql.= " AND z.active = 1 AND c.active = 1"; if ($zipcode) $sql.=" AND z.zip LIKE '" . $db->escape($zipcode) . "%'"; if ($town) $sql.=" AND z.town LIKE '%" . $db->escape($town) . "%'"; $sql.= " ORDER BY z.zip, z.town"; @@ -79,11 +79,11 @@ if (! empty($_GET['zipcode']) || ! empty($_GET['town'])) else // Use table of third parties { $sql = "SELECT DISTINCT s.zip, s.town, s.fk_departement as fk_county, s.fk_pays as fk_country"; - $sql.= ", p.code as country_code, p.libelle as country"; + $sql.= ", c.code as country_code, c.label as country"; $sql.= ", d.code_departement as county_code , d.nom as county"; $sql.= " FROM ".MAIN_DB_PREFIX.'societe as s'; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."c_departements as d ON s.fk_departement = d.rowid"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.'c_pays as p ON s.fk_pays = p.rowid'; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid'; $sql.= " WHERE"; if ($zipcode) $sql.= " s.zip LIKE '".$db->escape($zipcode)."%'"; if ($town) $sql.= " s.town LIKE '%" . $db->escape($town) . "%'"; diff --git a/htdocs/core/antispamimage.php b/htdocs/core/antispamimage.php index c3bc217e100..a16844dd715 100644 --- a/htdocs/core/antispamimage.php +++ b/htdocs/core/antispamimage.php @@ -51,8 +51,6 @@ for($i = 0; $i < $length; $i++) $sessionkey='dol_antispam_value'; $_SESSION[$sessionkey]=$string; -header("Content-type: image/png"); - $img = imagecreate(80,32); if (empty($img)) { @@ -60,6 +58,8 @@ if (empty($img)) exit; } +header("Content-type: image/png"); + $background_color = imagecolorallocate($img, 250, 250, 250); $ecriture_color = imagecolorallocate($img, 0, 0, 0); imagestring($img, 4, 24, 8, $string, $ecriture_color); diff --git a/htdocs/core/boxes/box_actions.php b/htdocs/core/boxes/box_actions.php index ff63927b526..89d05b92b79 100644 --- a/htdocs/core/boxes/box_actions.php +++ b/htdocs/core/boxes/box_actions.php @@ -2,6 +2,7 @@ /* Copyright (C) 2003-2007 Rodolphe Quiedeville * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2011 Regis Houssin + * Copyright (C) 2014 Charles-Fr BENKE * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -62,8 +63,8 @@ class box_actions extends ModeleBoxes if ($user->rights->agenda->myactions->read) { $sql = "SELECT a.id, a.label, a.datep as dp, a.percent as percentage,"; - $sql.= " ta.code,"; - $sql.= " s.nom, s.rowid as socid"; + $sql.= " ta.code, ta.libelle as type_label,"; + $sql.= " s.nom as name, s.rowid as socid"; $sql.= " FROM (".MAIN_DB_PREFIX."c_actioncomm AS ta, "; $sql.= MAIN_DB_PREFIX."actioncomm AS a)"; if (! $user->rights->societe->client->voir && ! $user->societe_id) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; @@ -77,7 +78,7 @@ class box_actions extends ModeleBoxes $sql.= " ORDER BY a.datec DESC"; $sql.= $db->plimit($max, 0); - dol_syslog("Box_actions::loadBox sql=".$sql, LOG_DEBUG); + dol_syslog("Box_actions::loadBox", LOG_DEBUG); $result = $db->query($sql); if ($result) { @@ -95,23 +96,23 @@ class box_actions extends ModeleBoxes if ($objp->percentage >= 0 && $objp->percentage < 100 && $datelimite < ($now - $delay_warning)) $late=img_warning($langs->trans("Late")); //($langs->transnoentities("Action".$objp->code)!=("Action".$objp->code) ? $langs->transnoentities("Action".$objp->code) : $objp->label) - $label=$objp->label; + $label=empty($objp->label)?$objp->type_label:$objp->label; $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => ("action"), - 'url' => DOL_URL_ROOT."/comm/action/fiche.php?id=".$objp->id); + 'url' => DOL_URL_ROOT."/comm/action/card.php?id=".$objp->id); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => dol_trunc($label,32), 'text2'=> $late, - 'url' => DOL_URL_ROOT."/comm/action/fiche.php?id=".$objp->id); + 'url' => DOL_URL_ROOT."/comm/action/card.php?id=".$objp->id); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => ($objp->socid?'company':''), 'url' => ($objp->socid?DOL_URL_ROOT."/societe/soc.php?socid=".$objp->socid:'')); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => dol_trunc($objp->nom,24), + 'text' => dol_trunc($objp->name,24), 'url' => DOL_URL_ROOT."/societe/soc.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="left" class="nowrap"', @@ -151,7 +152,71 @@ class box_actions extends ModeleBoxes */ function showBox($head = null, $contents = null) { + global $langs, $conf; parent::showBox($this->info_box_head, $this->info_box_contents); + if ($conf->global->SHOW_DIALOG_HOMEPAGE) + { + $actioncejour=false; + $contents=$this->info_box_contents; + $nblines=count($contents); + $bcx=array(); + $bcx[0] = 'class="box_pair"'; + $bcx[1] = 'class="box_impair"'; + if ($contents[0][0]['text'] != $langs->trans("NoActionsToDo")) + { + print '
trans("ActionsToDo").'">'; + print '
'; - print ''; + print ''; print ''; $arrayofoperators=array('<'=>'<','>'=>'>'); @@ -184,9 +199,9 @@ if ($resql) $filter_date2=dol_mktime(0,0,0,$op2month,$op2day,$op2year); print $form->select_date($filter_date2,'op2',0,0,1); print ''; - print "
'; + print ''; + print "
'; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=1; print $companystatic->getNomUrl(1,'customer',28); print '
- trans("ShowContract"),"contract").' '.$object->ref; ?> date_contrat,'day'); ?>   getLibStatut(6); ?>
'; + for ($i=0, $n=$nblines; $i < $n; $i++) + { + if (isset($contents[$i])) + { + // on affiche que les évènement du jours ou passé + // qui ne sont pas à 100% + $actioncejour=true; + $var=!$var; + // TR + $logo=$contents[$i][0]['logo']; + $label=$contents[$i][1]['text']; + $urlevent=$contents[$i][1]['url']; + $logosoc=$contents[$i][2]['logo']; + $nomsoc=$contents[$i][3]['text']; + $urlsoc=$contents[$i][3]['url']; + $dateligne=$contents[$i][4]['text']; + $percentage=$contents[$i][5]['text']; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + } + print '
'; + print img_object("",$logo); + print ''.$label.''.img_object("",$logosoc)." ".$nomsoc.''.$dateligne.''.$percentage.'
'; + + } + print ''; + if ($actioncejour) + { + print ''; + } + else + { + print ''; + } + } } } diff --git a/htdocs/core/boxes/box_activity.php b/htdocs/core/boxes/box_activity.php index 773bb13a3cb..d118bc8a4bc 100644 --- a/htdocs/core/boxes/box_activity.php +++ b/htdocs/core/boxes/box_activity.php @@ -214,7 +214,7 @@ class box_activity extends ModeleBoxes $this->info_box_contents[$i][2] = array('td' => 'align="right"', 'text' => $objp->nb, - 'url' => DOL_URL_ROOT."/commande/liste.php?mainmenu=commercial&leftmenu=orders&viewstatut=".$objp->fk_statut + 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&viewstatut=".$objp->fk_statut ); $totalnb += $objp->nb; @@ -283,7 +283,7 @@ class box_activity extends ModeleBoxes // Add the sum in the bottom of the boxes $this->info_box_contents[$i][1] = array('td' => 'align="left" ', 'text' => $langs->trans("Total")." ".$textHead); - $this->info_box_contents[$i][2] = array('td' => 'align="right" ', 'text' => price($totalnb,1,$langs,0,0,-1,$conf->currency)); + $this->info_box_contents[$i][2] = array('td' => 'align="right" ', 'text' => $totalnb); $this->info_box_contents[$i][3] = array('td' => 'align="right" ', 'text' => price($totalMnt,1,$langs,0,0,-1,$conf->currency)); $this->info_box_contents[$i][4] = array('td' => 'align="right" ', 'text' => ""); $this->info_box_contents[$i][5] = array('td' => 'align="right"', 'text' => ""); diff --git a/htdocs/core/boxes/box_bookmarks.php b/htdocs/core/boxes/box_bookmarks.php index 5cb1e3ddad4..968eefef4b9 100644 --- a/htdocs/core/boxes/box_bookmarks.php +++ b/htdocs/core/boxes/box_bookmarks.php @@ -53,7 +53,7 @@ class box_bookmarks extends ModeleBoxes $this->max=$max; $this->info_box_head = array('text' => $langs->trans("BoxMyLastBookmarks",$max), - 'sublink' => DOL_URL_ROOT.'/bookmarks/liste.php'); + 'sublink' => DOL_URL_ROOT.'/bookmarks/list.php'); if ($user->rights->bookmark->creer) { $this->info_box_head['subpicto']='object_bookmark'; @@ -101,7 +101,7 @@ class box_bookmarks extends ModeleBoxes { $mytxt=$langs->trans("NoRecordedBookmarks"); if ($user->rights->bookmark->creer) $mytxt.=' '.$langs->trans("ClickToAdd"); - $this->info_box_contents[$i][0] = array('td' => 'align="center" colspan="2"', 'url'=> DOL_URL_ROOT.'/bookmarks/liste.php', 'text'=>$mytxt); + $this->info_box_contents[$i][0] = array('td' => 'align="center" colspan="2"', 'url'=> DOL_URL_ROOT.'/bookmarks/list.php', 'text'=>$mytxt); } $db->free($result); diff --git a/htdocs/core/boxes/box_clients.php b/htdocs/core/boxes/box_clients.php index b65702b643f..4e651e8bdcc 100644 --- a/htdocs/core/boxes/box_clients.php +++ b/htdocs/core/boxes/box_clients.php @@ -79,7 +79,7 @@ class box_clients extends ModeleBoxes if ($user->rights->societe->lire) { - $sql = "SELECT s.nom, s.rowid as socid, s.datec, s.tms, s.status"; + $sql = "SELECT s.nom as name, s.rowid as socid, s.datec, s.tms, s.status"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.client IN (1, 3)"; @@ -89,12 +89,12 @@ class box_clients extends ModeleBoxes $sql.= " ORDER BY s.tms DESC"; $sql.= $db->plimit($max, 0); - dol_syslog(get_class($this)."::loadBox sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url= DOL_URL_ROOT."/comm/fiche.php?socid="; + if (empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) $url= DOL_URL_ROOT."/comm/card.php?socid="; else $url= DOL_URL_ROOT."/societe/soc.php?socid="; $i = 0; @@ -109,7 +109,7 @@ class box_clients extends ModeleBoxes 'url' => $url.$objp->socid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', - 'text' => $objp->nom, + 'text' => $objp->name, 'url' => $url.$objp->socid); $this->info_box_contents[$i][2] = array('td' => 'align="right"', diff --git a/htdocs/core/boxes/box_commandes.php b/htdocs/core/boxes/box_commandes.php index 1b7de3cca7f..1bb6fe9b27a 100644 --- a/htdocs/core/boxes/box_commandes.php +++ b/htdocs/core/boxes/box_commandes.php @@ -58,22 +58,25 @@ class box_commandes extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $commandestatic=new Commande($db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLastCustomerOrders",$max)); + $userstatic = new User($db); + + $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE?"":"Modified")."CustomerOrders",$max)); if ($user->rights->commande->lire) { - - $sql = "SELECT s.nom, s.rowid as socid,"; - $sql.= " c.ref, c.tms, c.rowid,"; - $sql.= " c.fk_statut, c.facture"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; + $sql.= " c.ref, c.tms, c.rowid, c.date_commande,"; + $sql.= " c.fk_statut, c.fk_user_valid, c.facture, c.total_ht"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."commande as c"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE c.fk_soc = s.rowid"; $sql.= " AND c.entity = ".$conf->entity; + if (! empty($conf->global->ORDER_BOX_LAST_ORDERS_VALIDATED_ONLY)) $sql.=" AND c.fk_statut = 1"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY c.date_commande DESC, c.ref DESC "; + if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql.= " ORDER BY c.date_commande DESC, c.ref DESC "; + else $sql.= " ORDER BY c.tms DESC, c.ref DESC "; $sql.= $db->plimit($max, 0); $result = $db->query($sql); @@ -86,29 +89,43 @@ class box_commandes extends ModeleBoxes while ($i < $num) { $objp = $db->fetch_object($result); + $date=$db->jdate($objp->date_commande); $datem=$db->jdate($objp->tms); - $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', + $this->info_box_contents[$i][] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/commande/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/commande/card.php?id=".$objp->rowid); - $this->info_box_contents[$i][1] = array('td' => 'align="left"', + $this->info_box_contents[$i][] = array('td' => 'align="left"', 'text' => $objp->ref, - 'url' => DOL_URL_ROOT."/commande/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/commande/card.php?id=".$objp->rowid); - $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', + $this->info_box_contents[$i][] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); - $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => $objp->nom, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + $this->info_box_contents[$i][] = array('td' => 'align="left"', + 'text' => $objp->name, + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); - $this->info_box_contents[$i][4] = array('td' => 'align="right"', - 'text' => dol_print_date($datem,'day'), + $this->info_box_contents[$i][] = array('td' => 'align="right"', + 'text' => price($objp->total_ht), + ); + + if (! empty($conf->global->ORDER_BOX_LAST_ORDERS_SHOW_VALIDATE_USER)) + { + if ($objp->fk_user_valid > 0) $userstatic->fetch($objp->fk_user_valid); + $this->info_box_contents[$i][] = array('td' => 'align="right"', + 'text' => (($objp->fk_user_valid > 0)?$userstatic->getNomUrl(1):''), + 'url' => (($objp->fk_user_valid > 0)?DOL_URL_ROOT.'/user/card.php?id='.$objp->fk_user_valid:'') + ); + } + + $this->info_box_contents[$i][] = array('td' => 'align="right"', + 'text' => dol_print_date($date,'day'), ); - $this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"', + $this->info_box_contents[$i][] = array('td' => 'align="right" width="18"', 'text' => $commandestatic->LibStatut($objp->fk_statut,$objp->facture,3)); $i++; diff --git a/htdocs/core/boxes/box_comptes.php b/htdocs/core/boxes/box_comptes.php index 8fdc4aff39e..45c8f1a4819 100644 --- a/htdocs/core/boxes/box_comptes.php +++ b/htdocs/core/boxes/box_comptes.php @@ -79,7 +79,7 @@ class box_comptes extends ModeleBoxes if ($user->rights->banque->lire) { $sql = "SELECT rowid, ref, label, bank, number, courant, clos, rappro, url,"; - $sql.= " code_banque, code_guichet, cle_rib, bic, iban_prefix,"; + $sql.= " code_banque, code_guichet, cle_rib, bic, iban_prefix as iban,"; $sql.= " domiciliation, proprio, owner_address,"; $sql.= " account_number, currency_code,"; $sql.= " min_allowed, min_desired, comment"; @@ -90,7 +90,7 @@ class box_comptes extends ModeleBoxes $sql.= " ORDER BY label"; $sql.= $db->plimit($max, 0); - dol_syslog(get_class($this)."::loadBox sql=".$sql); + dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); $result = $db->query($sql); if ($result) { diff --git a/htdocs/core/boxes/box_contacts.php b/htdocs/core/boxes/box_contacts.php index 1afc0d09e41..e10c9ae7ed9 100644 --- a/htdocs/core/boxes/box_contacts.php +++ b/htdocs/core/boxes/box_contacts.php @@ -61,7 +61,7 @@ class box_contacts extends ModeleBoxes if ($user->rights->societe->lire) { - $sql = "SELECT sp.rowid, sp.lastname, sp.firstname, sp.civilite as civility_id, sp.datec, sp.tms, sp.fk_soc,"; + $sql = "SELECT sp.rowid, sp.lastname, sp.firstname, sp.civility as civility_id, sp.datec, sp.tms, sp.fk_soc,"; $sql.= " s.nom as socname"; $sql.= " FROM ".MAIN_DB_PREFIX."socpeople as sp"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON sp.fk_soc = s.rowid"; @@ -96,11 +96,11 @@ class box_contacts extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/contact/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contact/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => $contactstatic->getFullName($langs,0), - 'url' => DOL_URL_ROOT."/contact/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contact/card.php?id=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => ($objp->fk_soc > 0?'company':''), diff --git a/htdocs/core/boxes/box_contracts.php b/htdocs/core/boxes/box_contracts.php index 26c3f269f3d..dc0ff8e5382 100644 --- a/htdocs/core/boxes/box_contracts.php +++ b/htdocs/core/boxes/box_contracts.php @@ -60,7 +60,7 @@ class box_contracts extends ModeleBoxes if ($user->rights->contrat->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; $sql.= " c.rowid, c.ref, c.statut as fk_statut, c.date_contrat, c.datec, c.fin_validite, c.date_cloture"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as c"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -96,20 +96,20 @@ class box_contracts extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => ($objp->ref?$objp->ref:$objp->rowid), // Some contracts have no ref 'text2'=> $late, - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => dol_trunc($objp->nom,40), - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'text' => dol_trunc($objp->name,40), + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => dol_print_date($datec,'day')); diff --git a/htdocs/core/boxes/box_factures.php b/htdocs/core/boxes/box_factures.php index 18d276b0130..b0fdd6d9d09 100644 --- a/htdocs/core/boxes/box_factures.php +++ b/htdocs/core/boxes/box_factures.php @@ -24,7 +24,6 @@ */ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; - /** * Class to manage the box to show last invoices */ @@ -57,7 +56,7 @@ class box_factures extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $facturestatic=new Facture($db); - $text = $langs->trans("BoxTitleLastCustomerBills",$max); + $text = $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE?"":"Modified")."CustomerBills",$max); $this->info_box_head = array( 'text' => $text, 'limit'=> dol_strlen($text) @@ -65,9 +64,9 @@ class box_factures extends ModeleBoxes if ($user->rights->facture->lire) { - $sql = "SELECT f.rowid as facid, f.facnumber, f.type, f.amount, f.datef as df"; + $sql = "SELECT f.rowid as facid, f.facnumber, f.type, f.total as total_ht, f.datef as df"; $sql.= ", f.paye, f.fk_statut, f.datec, f.tms"; - $sql.= ", s.nom, s.rowid as socid"; + $sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", f.date_lim_reglement as datelimite"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -76,7 +75,8 @@ class box_factures extends ModeleBoxes $sql.= " AND f.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY f.tms DESC"; + if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql.= " ORDER BY f.datef DESC, f.facnumber DESC "; + else $sql.= " ORDER BY f.tms DESC, f.facnumber DESC "; $sql.= $db->plimit($max, 0); $result = $db->query($sql); @@ -92,7 +92,8 @@ class box_factures extends ModeleBoxes { $objp = $db->fetch_object($result); $datelimite=$db->jdate($objp->datelimite); - $datec=$db->jdate($objp->datec); + $date=$db->jdate($objp->df); + $datem=$db->jdate($objp->tms); $picto='bill'; if ($objp->type == 1) $picto.='r'; @@ -111,18 +112,22 @@ class box_factures extends ModeleBoxes $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => $objp->nom, + 'text' => $objp->name, 'maxlength'=>40, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="right"', - 'text' => dol_print_date($datec,'day'), + 'text' => price($objp->total_ht), ); - $this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"', + $this->info_box_contents[$i][5] = array('td' => 'align="right"', + 'text' => dol_print_date($date,'day'), + ); + + $this->info_box_contents[$i][6] = array('td' => 'align="right" width="18"', 'text' => $facturestatic->LibStatut($objp->paye,$objp->fk_statut,3)); $i++; @@ -159,4 +164,3 @@ class box_factures extends ModeleBoxes } } - diff --git a/htdocs/core/boxes/box_factures_fourn.php b/htdocs/core/boxes/box_factures_fourn.php index d9cfa9bf5cd..914f442bea4 100644 --- a/htdocs/core/boxes/box_factures_fourn.php +++ b/htdocs/core/boxes/box_factures_fourn.php @@ -58,13 +58,13 @@ class box_factures_fourn extends ModeleBoxes $facturestatic=new FactureFournisseur($db); $this->info_box_head = array( - 'text' => $langs->trans("BoxTitleLastSupplierBills",$max) + 'text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE?"":"Modified")."SupplierBills",$max) ); if ($user->rights->fournisseur->facture->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; - $sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.amount,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; + $sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.total_ht,"; $sql.= " f.paye, f.fk_statut,"; $sql.= ' f.datef as df,'; $sql.= ' f.datec as datec,'; @@ -76,7 +76,8 @@ class box_factures_fourn extends ModeleBoxes $sql.= " AND f.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY f.tms DESC"; + if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql.= " ORDER BY f.datef DESC, f.ref DESC "; + else $sql.= " ORDER BY f.tms DESC, f.ref DESC "; $sql.= $db->plimit($max, 0); $result = $db->query($sql); @@ -92,34 +93,35 @@ class box_factures_fourn extends ModeleBoxes { $objp = $db->fetch_object($result); $datelimite=$db->jdate($objp->datelimite); - $datec=$db->jdate($objp->datec); + $date=$db->jdate($objp->df); + $datem=$db->jdate($objp->tms); $late = ''; if ($objp->paye == 0 && $datelimite && $datelimite < ($now - $conf->facture->fournisseur->warning_delay)) $late=img_warning(sprintf($l_due_date, dol_print_date($datelimite,'day'))); $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => ($objp->ref?$objp->ref:$objp->facid), 'text2'=> $late, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][2] = array('td' => 'align="left"', 'text' => $objp->ref_supplier, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][3] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="left"', - 'text' => $objp->nom, - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'text' => $objp->name, + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][5] = array('td' => 'align="right"', - 'text' => dol_print_date($datec,'day')); + 'text' => dol_print_date($date,'day')); $fac = new FactureFournisseur($db); $fac->fetch($objp->facid); diff --git a/htdocs/core/boxes/box_factures_fourn_imp.php b/htdocs/core/boxes/box_factures_fourn_imp.php index 742bd04cf82..aa217f1c436 100644 --- a/htdocs/core/boxes/box_factures_fourn_imp.php +++ b/htdocs/core/boxes/box_factures_fourn_imp.php @@ -60,7 +60,7 @@ class box_factures_fourn_imp extends ModeleBoxes if ($user->rights->fournisseur->facture->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; $sql.= " f.rowid as facid, f.ref, f.ref_supplier, f.date_lim_reglement as datelimite,"; $sql.= " f.amount, f.datef as df,"; $sql.= " f.paye, f.fk_statut, f.type"; @@ -95,24 +95,24 @@ class box_factures_fourn_imp extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => ($objp->ref?$objp->ref:$objp->facid), 'text2'=> $late, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][2] = array('td' => 'align="left"', 'text' => $objp->ref_supplier, - 'url' => DOL_URL_ROOT."/fourn/facture/fiche.php?facid=".$objp->facid); + 'url' => DOL_URL_ROOT."/fourn/facture/card.php?facid=".$objp->facid); $this->info_box_contents[$i][3] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="left"', - 'text' => $objp->nom, - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'text' => $objp->name, + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][5] = array('td' => 'align="right"', 'text' => dol_print_date($datelimite,'day')); diff --git a/htdocs/core/boxes/box_factures_imp.php b/htdocs/core/boxes/box_factures_imp.php index 72c34dee559..e6df1530f8d 100644 --- a/htdocs/core/boxes/box_factures_imp.php +++ b/htdocs/core/boxes/box_factures_imp.php @@ -63,7 +63,7 @@ class box_factures_imp extends ModeleBoxes if ($user->rights->facture->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; $sql.= " f.facnumber, f.date_lim_reglement as datelimite,"; $sql.= " f.amount, f.datef as df,"; $sql.= " f.paye, f.fk_statut, f.rowid as facid"; @@ -107,12 +107,12 @@ class box_factures_imp extends ModeleBoxes $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => $objp->nom, + 'text' => $objp->name, 'maxlength'=>44, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => dol_print_date($datelimite,'day'), diff --git a/htdocs/core/boxes/box_ficheinter.php b/htdocs/core/boxes/box_ficheinter.php index 3413548c1fd..9cce737eb9a 100644 --- a/htdocs/core/boxes/box_ficheinter.php +++ b/htdocs/core/boxes/box_ficheinter.php @@ -65,21 +65,18 @@ class box_ficheinter extends ModeleBoxes $sql.= " f.datec,"; $sql.= " f.date_valid as datev,"; $sql.= " f.tms as datem,"; - $sql.= " s.nom, s.rowid as socid, s.client"; + $sql.= " s.nom as name, s.rowid as socid, s.client"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (! $user->rights->societe->client->voir) - $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (! $user->rights->societe->client->voir) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ", ".MAIN_DB_PREFIX."fichinter as f"; $sql.= " WHERE f.fk_soc = s.rowid "; $sql.= " AND f.entity = ".$conf->entity; - if (! $user->rights->societe->client->voir && !$user->societe_id) - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if (! $user->rights->societe->client->voir && !$user->societe_id) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY f.tms DESC"; $sql.= $db->plimit($max, 0); - dol_syslog(get_class($this).'::loadBox sql='.$sql,LOG_DEBUG); + dol_syslog(get_class($this).'::loadBox', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -98,19 +95,19 @@ class box_ficheinter extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/fichinter/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/fichinter/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => ($objp->ref?$objp->ref:$objp->rowid), // Some interventions have no ref - 'url' => DOL_URL_ROOT."/fichinter/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/fichinter/card.php?id=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => dol_trunc($objp->nom,40), - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'text' => dol_trunc($objp->name,40), + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => dol_print_date($datec,'day')); diff --git a/htdocs/core/boxes/box_fournisseurs.php b/htdocs/core/boxes/box_fournisseurs.php index 0157e5acada..f233221ccaa 100644 --- a/htdocs/core/boxes/box_fournisseurs.php +++ b/htdocs/core/boxes/box_fournisseurs.php @@ -62,7 +62,7 @@ class box_fournisseurs extends ModeleBoxes if ($user->rights->societe->lire) { - $sql = "SELECT s.nom, s.rowid as socid, s.datec, s.tms, s.status"; + $sql = "SELECT s.nom as name, s.rowid as socid, s.datec, s.tms, s.status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.fournisseur = 1"; @@ -86,11 +86,11 @@ class box_fournisseurs extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', - 'text' => $objp->nom, - 'url' => DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid); + 'text' => $objp->name, + 'url' => DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid); $this->info_box_contents[$i][2] = array('td' => 'align="right"', 'text' => dol_print_date($datem, "day")); diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index ad7cbc0e29c..9b2a5437b8a 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -104,8 +104,7 @@ class box_graph_invoices_permonth extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $endyear=$tmparray['year']; $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; @@ -115,11 +114,10 @@ class box_graph_invoices_permonth extends ModeleBoxes if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; $mode='customer'; - $userid=0; $WIDTH=(($shownb && $showtot) || ! empty($conf->dol_optimize_smallscreen))?'256':'320'; $HEIGHT='192'; - $stats = new FactureStats($this->db, 0, $mode, ($userid>0?$userid:0)); + $stats = new FactureStats($this->db, $socid, $mode, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) if ($shownb) @@ -217,12 +215,12 @@ class box_graph_invoices_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; $stringtoshow.=''; - $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); + $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); $stringtoshow.='   '; - $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); + $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.=''; if ($shownb && $showtot) diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index 58d3a27f834..7c2aa53da97 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -103,8 +103,7 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $endyear=$tmparray['year']; $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; @@ -114,11 +113,10 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; $mode='supplier'; - $userid=0; $WIDTH=(($shownb && $showtot) || ! empty($conf->dol_optimize_smallscreen))?'256':'320'; $HEIGHT='192'; - $stats = new FactureStats($this->db, 0, $mode, ($userid>0?$userid:0)); + $stats = new FactureStats($this->db, $socid, $mode, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) if ($shownb) @@ -216,12 +214,12 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; $stringtoshow.=''; - $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); + $stringtoshow.=' '.$langs->trans("NumberOfBillsByMonth"); $stringtoshow.='   '; - $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); + $stringtoshow.=' '.$langs->trans("AmountOfBillsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.=''; if ($shownb && $showtot) diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index 81c9185c68f..75f0f60660f 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -104,8 +104,7 @@ class box_graph_orders_permonth extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $endyear=$tmparray['year']; $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; @@ -115,11 +114,10 @@ class box_graph_orders_permonth extends ModeleBoxes if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; $mode='customer'; - $userid=0; $WIDTH=(($shownb && $showtot) || ! empty($conf->dol_optimize_smallscreen))?'256':'320'; $HEIGHT='192'; - $stats = new CommandeStats($this->db, 0, $mode, ($userid>0?$userid:0)); + $stats = new CommandeStats($this->db, $socid, $mode, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) if ($shownb) @@ -217,12 +215,12 @@ class box_graph_orders_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; $stringtoshow.=''; - $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); + $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); $stringtoshow.='   '; - $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); + $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.=''; if ($shownb && $showtot) diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 98779836576..70d62cac348 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -103,8 +103,7 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $endyear=$tmparray['year']; $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; @@ -114,11 +113,10 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; $mode='supplier'; - $userid=0; $WIDTH=(($shownb && $showtot) || ! empty($conf->dol_optimize_smallscreen))?'256':'320'; $HEIGHT='192'; - $stats = new CommandeStats($this->db, 0, $mode, ($userid>0?$userid:0)); + $stats = new CommandeStats($this->db, $socid, $mode, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) if ($shownb) @@ -216,12 +214,12 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; $stringtoshow.=''; - $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); + $stringtoshow.=' '.$langs->trans("NumberOfOrdersByMonth"); $stringtoshow.='   '; - $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); + $stringtoshow.=' '.$langs->trans("AmountOfOrdersByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.=''; if ($shownb && $showtot) diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index 0029866b75a..74d106b7f69 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -96,8 +96,7 @@ class box_graph_product_distribution extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $year=$tmparray['year']; $showinvoicenb=$tmparray['showinvoicenb']; $showpropalnb=$tmparray['showpropalnb']; @@ -337,7 +336,7 @@ class box_graph_product_distribution extends ModeleBoxes } $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.=''; $stringtoshow.=''; diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index 61e83f3cd60..fd866f5df89 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -104,8 +104,7 @@ class box_graph_propales_permonth extends ModeleBoxes } else { - include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php'; - $tmparray=dol_json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); + $tmparray=json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode],true); $endyear=$tmparray['year']; $shownb=$tmparray['shownb']; $showtot=$tmparray['showtot']; @@ -114,12 +113,10 @@ class box_graph_propales_permonth extends ModeleBoxes $nowarray=dol_getdate(dol_now(),true); if (empty($endyear)) $endyear=$nowarray['year']; $startyear=$endyear-1; - $mode='customer'; - $userid=0; $WIDTH=(($shownb && $showtot) || ! empty($conf->dol_optimize_smallscreen))?'256':'320'; $HEIGHT='192'; - $stats = new PropaleStats($this->db, 0, $mode, ($userid>0?$userid:0)); + $stats = new PropaleStats($this->db, $socid, 0); // Build graphic number of object. $data = array(array('Lib',val1,val2,val3),...) if ($shownb) @@ -128,8 +125,7 @@ class box_graph_propales_permonth extends ModeleBoxes $datatype1 = array_pad(array(), ($endyear-$startyear+1), 'bars'); $filenamenb = $dir."/".$prefix."propalsnbinyear-".$endyear.".png"; - if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=propalsnbinyear-'.$endyear.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstatssupplier&file=propalsnbinyear-'.$endyear.'.png'; + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=propalsnbinyear-'.$endyear.'.png'; $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); @@ -222,12 +218,12 @@ class box_graph_propales_permonth extends ModeleBoxes $stringtoshow.='
'; $stringtoshow.=''; $stringtoshow.=''; - $stringtoshow.=' '.$langs->trans("NumberOfProposalsByMonth"); + $stringtoshow.=' '.$langs->trans("NumberOfProposalsByMonth"); $stringtoshow.='   '; - $stringtoshow.=' '.$langs->trans("AmountOfProposalsByMonthHT"); + $stringtoshow.=' '.$langs->trans("AmountOfProposalsByMonthHT"); $stringtoshow.='
'; $stringtoshow.=$langs->trans("Year").' '; - $stringtoshow.=''; + $stringtoshow.=''; $stringtoshow.='
'; $stringtoshow.=''; if ($shownb && $showtot) diff --git a/htdocs/core/boxes/box_members.php b/htdocs/core/boxes/box_members.php index 966a8ab7d10..4760a3aaf89 100644 --- a/htdocs/core/boxes/box_members.php +++ b/htdocs/core/boxes/box_members.php @@ -115,11 +115,11 @@ class box_members extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/adherents/fiche.php?rowid=".$objp->rowid); + 'url' => DOL_URL_ROOT."/adherents/card.php?rowid=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => $memberstatic->getFullName($langs), - 'url' => DOL_URL_ROOT."/adherents/fiche.php?rowid=".$objp->rowid); + 'url' => DOL_URL_ROOT."/adherents/card.php?rowid=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="right"', 'text' => dol_print_date($datem, "day")); diff --git a/htdocs/core/boxes/box_osc_client.php b/htdocs/core/boxes/box_osc_client.php deleted file mode 100644 index 956811ea4e3..00000000000 --- a/htdocs/core/boxes/box_osc_client.php +++ /dev/null @@ -1,112 +0,0 @@ - - * Copyright (C) 2005-2008 Laurent Destailleur - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -/** - * \file htdocs/core/boxes/box_osc_client.php - * \ingroup osc - * \brief Module to generate box of shop customers - */ - -include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; - - -/** - * Class to manage the box to show last customers of shop - */ -class box_osc_clients extends ModeleBoxes -{ - var $boxcode="nbofcustomers"; - var $boximg="object_company"; - var $boxlabel="BoxNbOfCustomers"; - var $depends = array("boutique"); - - var $db; - var $param; - - var $info_box_head = array(); - var $info_box_contents = array(); - - - /** - * Load data into info_box_contents array to show array later. - * - * @param int $max Maximum number of records to load - * @return void - */ - function loadBox($max=5) - { - global $conf, $user, $langs, $db; - $langs->load("boxes"); - - $this->max=$max; - - $this->info_box_head = array('text' => $langs->trans("BoxTitleNbOfCustomers",$max)); - - if ($user->rights->boutique->lire) - { - $sql = "SELECT count(*) as cus FROM ".$conf->global->OSC_DB_NAME.".".$conf->global->OSC_DB_TABLE_PREFIX."customers"; - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - - $i = 0; - - while ($i < $num) - { - $objp = $db->fetch_object($resql); - - $this->info_box_contents[$i][0] = array('td' => 'align="center" width="16"', - 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/boutique/client/index.php"); - $this->info_box_contents[$i][1] = array('td' => 'align="center"', - 'text' => $objp->cus, - 'url' => DOL_URL_ROOT."/boutique/client/index.php"); - $i++; - } - - $db->free($resql); - } - else { - $this->info_box_contents[0][0] = array( 'td' => 'align="left"', - 'maxlength'=>500, - 'text' => ($db->error().' sql='.$sql)); - } - } - else { - $this->info_box_contents[0][0] = array('td' => 'align="left"', - 'text' => $langs->trans("ReadPermissionNotAllowed")); - } - - } - - /** - * Method to show box - * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * @return void - */ - function showBox($head = null, $contents = null) - { - parent::showBox($this->info_box_head, $this->info_box_contents); - } - -} - diff --git a/htdocs/core/boxes/box_produits.php b/htdocs/core/boxes/box_produits.php index 30669c4f392..d3772ff65f1 100644 --- a/htdocs/core/boxes/box_produits.php +++ b/htdocs/core/boxes/box_produits.php @@ -101,11 +101,11 @@ class box_produits extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => ($objp->fk_product_type==1?'object_service':'object_product'), - 'url' => DOL_URL_ROOT."/product/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => $objp->label, - 'url' => DOL_URL_ROOT."/product/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); if ($objp->price_base_type == 'HT') { diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php index ec526a76492..1079f623492 100644 --- a/htdocs/core/boxes/box_produits_alerte_stock.php +++ b/htdocs/core/boxes/box_produits_alerte_stock.php @@ -108,11 +108,11 @@ class box_produits_alerte_stock extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => ($objp->fk_product_type==1?'object_service':'object_product'), - 'url' => DOL_URL_ROOT."/product/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => $objp->label, - 'url' => DOL_URL_ROOT."/product/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); if ($objp->price_base_type == 'HT') { diff --git a/htdocs/core/boxes/box_project.php b/htdocs/core/boxes/box_project.php new file mode 100644 index 00000000000..62ed89dd65b --- /dev/null +++ b/htdocs/core/boxes/box_project.php @@ -0,0 +1,155 @@ + + * 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/boxes/box_activite.php + * \ingroup projet + * \brief Module to show Projet activity of the current Year + */ +include_once(DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"); + +/** + * Class to manage the box to show last projet + */ +class box_project extends ModeleBoxes +{ + var $boxcode="project"; + var $boximg="object_projectpub"; + var $boxlabel; + //var $depends = array("projet"); + var $db; + var $param; + + var $info_box_head = array(); + var $info_box_contents = array(); + + /** + * \brief Constructeur de la classe + */ + function box_project() + { + global $langs; + $langs->load("boxes"); + $langs->load("projects"); + + $this->boxlabel="Projet"; + } + + /** + * Load data for box to show them later + * + * @param int $max Maximum number of records to load + * @return void + */ + function loadBox($max=5) + { + global $conf, $user, $langs, $db; + + $this->max=$max; + + $totalMnt = 0; + $totalnb = 0; + $totalnbTask=0; + include_once(DOL_DOCUMENT_ROOT."/projet/class/project.class.php"); + require_once(DOL_DOCUMENT_ROOT."/core/lib/project.lib.php"); + $projectstatic=new Project($db); + + + + $textHead = $langs->trans("Projet"); + $this->info_box_head = array('text' => $textHead, 'limit'=> dol_strlen($textHead)); + + // list the summary of the orders + if ($user->rights->projet->lire) + { + + $sql = "SELECT p.rowid, p.ref, p.title, p.fk_statut "; + $sql.= " FROM ".MAIN_DB_PREFIX."projet as p"; + $sql.= " WHERE p.entity = ".$conf->entity; + $sql.= " AND p.fk_statut = 1"; // Seulement les projets ouverts + $sql.= " ORDER BY p.datec DESC"; + $sql.= $db->plimit($max, 0); + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + while ($i < $num) + { + $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"','logo' => 'object_projectpub'); + + $objp = $db->fetch_object($result); + $projectstatic->fetch($objp->rowid); + + $this->info_box_contents[$i][1] = array('td' => 'align="left"', + 'text' =>$projectstatic->getNomUrl(1) + ); + + $this->info_box_contents[$i][2] = array('td' => 'align="left"', + 'text' => $objp->title + ); + + $sql ="SELECT count(*) as nb, sum(progress) as totprogress"; + $sql.=" FROM ".MAIN_DB_PREFIX."projet as p LEFT JOIN ".MAIN_DB_PREFIX."projet_task as pt on pt.fk_projet = p.rowid"; + $sql.=" WHERE p.entity = ".$conf->entity; + + $resultTask = $db->query($sql); + if ($resultTask) + { + $objTask = $db->fetch_object($resultTask); + $this->info_box_contents[$i][3] = array('td' => 'align="right"', 'text' => number_format($objTask->nb, 0, ',', ' ')." ".$langs->trans("Tasks")); + if ($objTask->nb > 0 ) + $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => number_format(($objTask->totprogress/$objTask->nb), 0, ',', ' ')."%"); + else + $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => "N/A "); + $totalnbTask += $objTask->nb; + } + else + { + $this->info_box_contents[$i][3] = array('td' => 'align="right"', 'text' => number_format(0, 0, ',', ' ')); + $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => "N/A "); + } + + $i++; + } + } + } + + + // Add the sum à the bottom of the boxes + $this->info_box_contents[$i][0] = array('tr' => 'class="liste_total"', 'td' => 'align="left" ', 'text' => $langs->trans("Total")." ".$textHead); + $this->info_box_contents[$i][1] = array('td' => '', 'text' => ""); + $this->info_box_contents[$i][2] = array('td' => 'align="right" ', 'text' => number_format($num, 0, ',', ' ')." ".$langs->trans("Projects")); + $this->info_box_contents[$i][3] = array('td' => 'align="right" ', 'text' => number_format($totalnbTask, 0, ',', ' ')." ".$langs->trans("Tasks")); + $this->info_box_contents[$i][4] = array('td' => '', 'text' => ""); + + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @return void + */ + function showBox($head = null, $contents = null) + { + parent::showBox($this->info_box_head, $this->info_box_contents); + } +} + diff --git a/htdocs/core/boxes/box_propales.php b/htdocs/core/boxes/box_propales.php index 73e554de2b6..e9bd47b2a9e 100644 --- a/htdocs/core/boxes/box_propales.php +++ b/htdocs/core/boxes/box_propales.php @@ -56,84 +56,93 @@ class box_propales extends ModeleBoxes $this->max=$max; include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $propalstatic=new Propal($db); + $propalstatic=new Propal($db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLastPropals",$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, s.rowid as socid,"; - $sql.= " p.rowid, p.ref, p.fk_statut, p.datep as dp, p.datec, p.fin_validite, p.date_cloture"; - $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql.= ", ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->societe_id) $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->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - if($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY p.datep DESC, p.ref DESC "; - $sql.= $db->plimit($max, 0); + if ($user->rights->propale->lire) + { + $sql = "SELECT s.nom as name, s.rowid as socid,"; + $sql.= " p.rowid, p.ref, p.fk_statut, p.datep as dp, p.datec, p.fin_validite, p.date_cloture, p.total_ht, p.tms"; + $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql.= ", ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->societe_id) $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->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + if($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; + 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.= $db->plimit($max, 0); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $now=dol_now(); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $now=dol_now(); - $i = 0; + $i = 0; - while ($i < $num) - { - $objp = $db->fetch_object($result); - $datec=$db->jdate($objp->datec); - $dateterm=$db->jdate($objp->fin_validite); - $dateclose=$db->jdate($objp->date_cloture); + while ($i < $num) + { + $objp = $db->fetch_object($result); + $date=$db->jdate($objp->dp); + $datec=$db->jdate($objp->datec); + $datem=$db->jdate($objp->tms); + $dateterm=$db->jdate($objp->fin_validite); + $dateclose=$db->jdate($objp->date_cloture); - $late = ''; - if ($objp->fk_statut == 1 && $dateterm < ($now - $conf->propal->cloture->warning_delay)) { $late = img_warning($langs->trans("Late")); } + $late = ''; + if ($objp->fk_statut == 1 && $dateterm < ($now - $conf->propal->cloture->warning_delay)) { + $late = img_warning($langs->trans("Late")); + } - $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', - 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/comm/propal.php?id=".$objp->rowid); + $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', + 'logo' => $this->boximg, + 'url' => DOL_URL_ROOT."/comm/propal.php?id=".$objp->rowid); - $this->info_box_contents[$i][1] = array('td' => 'align="left"', - 'text' => $objp->ref, - 'text2'=> $late, - 'url' => DOL_URL_ROOT."/comm/propal.php?id=".$objp->rowid); + $this->info_box_contents[$i][1] = array('td' => 'align="left"', + 'text' => $objp->ref, + 'text2'=> $late, + 'url' => DOL_URL_ROOT."/comm/propal.php?id=".$objp->rowid); - $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', - 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', + 'logo' => 'company', + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); - $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => dol_trunc($objp->nom,40), - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + $this->info_box_contents[$i][3] = array('td' => 'align="left"', + 'text' => dol_trunc($objp->name,40), + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); - $this->info_box_contents[$i][4] = array('td' => 'align="right"', - 'text' => dol_print_date($datec,'day')); + $this->info_box_contents[$i][4] = array('td' => 'align="right"', + 'text' => price($objp->total_ht), + ); - $this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"', - 'text' => $propalstatic->LibStatut($objp->fk_statut,3)); + $this->info_box_contents[$i][5] = array('td' => 'align="right"', + 'text' => dol_print_date($date,'day')); - $i++; - } + $this->info_box_contents[$i][6] = array('td' => 'align="right" width="18"', + 'text' => $propalstatic->LibStatut($objp->fk_statut,3)); - if ($num==0) $this->info_box_contents[$i][0] = array('td' => 'align="center"','text'=>$langs->trans("NoRecordedProposals")); + $i++; + } - $db->free($result); - } - else - { - $this->info_box_contents[0][0] = array( 'td' => 'align="left"', - 'maxlength'=>500, - 'text' => ($db->error().' sql='.$sql)); - } - } - else - { - $this->info_box_contents[0][0] = array('td' => 'align="left"', - 'text' => $langs->trans("ReadPermissionNotAllowed")); - } + if ($num==0) $this->info_box_contents[$i][0] = array('td' => 'align="center"','text'=>$langs->trans("NoRecordedProposals")); + + $db->free($result); + } + else + { + $this->info_box_contents[0][0] = array( 'td' => 'align="left"', + 'maxlength'=>500, + 'text' => ($db->error().' sql='.$sql)); + } + } + else + { + $this->info_box_contents[0][0] = array('td' => 'align="left"', + 'text' => $langs->trans("ReadPermissionNotAllowed")); + } } /** diff --git a/htdocs/core/boxes/box_prospect.php b/htdocs/core/boxes/box_prospect.php index 6d62989727b..3020f12f0c4 100644 --- a/htdocs/core/boxes/box_prospect.php +++ b/htdocs/core/boxes/box_prospect.php @@ -80,7 +80,7 @@ class box_prospect extends ModeleBoxes if ($user->rights->societe->lire) { - $sql = "SELECT s.nom, s.rowid as socid, s.fk_stcomm, s.datec, s.tms, s.status"; + $sql = "SELECT s.nom as name, s.rowid as socid, s.fk_stcomm, s.datec, s.tms, s.status"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.client IN (2, 3)"; @@ -90,7 +90,7 @@ class box_prospect extends ModeleBoxes $sql.= " ORDER BY s.tms DESC"; $sql.= $db->plimit($max, 0); - dol_syslog(get_class($this)."::loadBox sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -106,11 +106,11 @@ class box_prospect extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', - 'text' => $objp->nom, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'text' => $objp->name, + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][2] = array('td' => 'align="right"', 'text' => dol_print_date($datem, "day")); diff --git a/htdocs/core/boxes/box_services_contracts.php b/htdocs/core/boxes/box_services_contracts.php index 264178cc3ea..eb48fc83d2b 100644 --- a/htdocs/core/boxes/box_services_contracts.php +++ b/htdocs/core/boxes/box_services_contracts.php @@ -62,7 +62,7 @@ class box_services_contracts extends ModeleBoxes if ($user->rights->service->lire && $user->rights->contrat->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; $sql.= " c.rowid,"; $sql.= " cd.rowid as cdid, cd.tms as datem, cd.statut,"; $sql.= " p.rowid as pid, p.label, p.fk_product_type"; @@ -113,21 +113,21 @@ class box_services_contracts extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => ($objp->fk_product_type==1?'object_service':'object_product'), - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => $objp->label, 'maxlength' => 16, - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => $objp->nom, + 'text' => $objp->name, 'maxlength' => 28, - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => dol_print_date($datem,'day')); diff --git a/htdocs/core/boxes/box_services_expired.php b/htdocs/core/boxes/box_services_expired.php index 5e488b3c6db..52f3777e2af 100644 --- a/htdocs/core/boxes/box_services_expired.php +++ b/htdocs/core/boxes/box_services_expired.php @@ -63,7 +63,7 @@ class box_services_expired extends ModeleBoxes // Select contracts with at least one expired service $sql = "SELECT "; $sql.= " c.rowid, c.ref, c.statut as fk_statut, c.date_contrat,"; - $sql.= " s.nom, s.rowid as socid,"; + $sql.= " s.nom as name, s.rowid as socid,"; $sql.= " MIN(cd.date_fin_validite) as date_line, COUNT(cd.rowid) as nb_services"; $sql.= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe s, ".MAIN_DB_PREFIX."contratdet as cd"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -93,19 +93,19 @@ class box_services_expired extends ModeleBoxes $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][1] = array('td' => 'align="left"', 'text' => ($objp->ref?$objp->ref:$objp->rowid), // Some contracts have no ref - 'url' => DOL_URL_ROOT."/contrat/fiche.php?id=".$objp->rowid); + 'url' => DOL_URL_ROOT."/contrat/card.php?id=".$objp->rowid); $this->info_box_contents[$i][2] = array('td' => 'align="left" width="16"', 'logo' => 'company', - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => dol_trunc($objp->nom,40), - 'url' => DOL_URL_ROOT."/comm/fiche.php?socid=".$objp->socid); + 'text' => dol_trunc($objp->name,40), + 'url' => DOL_URL_ROOT."/comm/card.php?socid=".$objp->socid); $this->info_box_contents[$i][4] = array('td' => 'align="center"', 'text' => dol_print_date($dateline,'day'), diff --git a/htdocs/core/boxes/box_supplier_orders.php b/htdocs/core/boxes/box_supplier_orders.php index a976112c1ad..d14bf1a539f 100644 --- a/htdocs/core/boxes/box_supplier_orders.php +++ b/htdocs/core/boxes/box_supplier_orders.php @@ -58,12 +58,12 @@ class box_supplier_orders extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $supplierorderstatic=new CommandeFournisseur($db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLatestSupplierOrders", $max)); + $this->info_box_head = array('text' => $langs->trans("BoxTitleLatest".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE?"":"Modified")."SupplierOrders", $max)); if ($user->rights->fournisseur->commande->lire) { - $sql = "SELECT s.nom, s.rowid as socid,"; - $sql.= " c.ref, c.tms, c.rowid,"; + $sql = "SELECT s.nom as name, s.rowid as socid,"; + $sql.= " c.ref, c.tms, c.rowid, c.date_commande,"; $sql.= " c.fk_statut"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."commande_fournisseur as c"; @@ -72,7 +72,8 @@ class box_supplier_orders extends ModeleBoxes $sql.= " AND c.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($user->societe_id) $sql.= " AND s.rowid = ".$user->societe_id; - $sql.= " ORDER BY c.date_commande DESC, c.ref DESC "; + if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql.= " ORDER BY c.date_commande DESC, c.ref DESC "; + else $sql.= " ORDER BY c.tms DESC, c.ref DESC "; $sql.= $db->plimit($max, 0); $result = $db->query($sql); @@ -84,10 +85,11 @@ class box_supplier_orders extends ModeleBoxes while ($i < $num) { $objp = $db->fetch_object($result); - $datem=$db->jdate($objp->tms); + $date=$db->jdate($objp->date_commande); + $datem=$db->jdate($objp->tms); - $urlo = DOL_URL_ROOT."/fourn/commande/fiche.php?id=".$objp->rowid; - $urls = DOL_URL_ROOT."/fourn/fiche.php?socid=".$objp->socid; + $urlo = DOL_URL_ROOT."/fourn/commande/card.php?id=".$objp->rowid; + $urls = DOL_URL_ROOT."/fourn/card.php?socid=".$objp->socid; $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"', 'logo' => $this->boximg, @@ -102,11 +104,11 @@ class box_supplier_orders extends ModeleBoxes 'url' => $urls); $this->info_box_contents[$i][3] = array('td' => 'align="left"', - 'text' => $objp->nom, + 'text' => $objp->name, 'url' => $urls); $this->info_box_contents[$i][4] = array('td' => 'align="right"', - 'text' => dol_print_date($datem,'day'), + 'text' => dol_print_date($date,'day'), ); $this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"', diff --git a/htdocs/core/boxes/box_task.php b/htdocs/core/boxes/box_task.php new file mode 100644 index 00000000000..c15bc9831ce --- /dev/null +++ b/htdocs/core/boxes/box_task.php @@ -0,0 +1,143 @@ + + * 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/boxes/box_task.php + * \ingroup Projet + * \brief Module to Task activity of the current year + * \version $Id: box_task.php,v 1.1 2012/09/11 Charles-François BENKE + */ + +include_once(DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"); +require_once(DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"); + +/** + * Class to manage the box to show last task + */ +class box_task extends ModeleBoxes +{ + var $boxcode="projet"; + var $boximg="object_projecttask"; + var $boxlabel; + //var $depends = array("projet"); + var $db; + var $param; + + var $info_box_head = array(); + var $info_box_contents = array(); + + /** + * \brief Constructeur de la classe + * + * @return void + */ + function box_task() + { + global $langs; + $langs->load("boxes"); + $langs->load("projects"); + $this->boxlabel="Tasks"; + } + + /** + * Load data for box to show them later + * + * @param int $max Maximum number of records to load + * @return void + */ + function loadBox($max=5) + { + global $conf, $user, $langs, $db; + + $this->max=$max; + + $totalMnt = 0; + $totalnb = 0; + $totalDuree=0; + include_once(DOL_DOCUMENT_ROOT."/projet/class/task.class.php"); + $taskstatic=new Task($db); + + + $textHead = $langs->trans("Tasks")." ".date("Y"); + $this->info_box_head = array('text' => $textHead, 'limit'=> dol_strlen($textHead)); + + // list the summary of the orders + if ($user->rights->projet->lire) + { + + $sql = "SELECT pt.fk_statut, count(pt.rowid) as nb, sum(ptt.task_duration) as durationtot, sum(pt.planned_workload) as plannedtot"; + $sql.= " FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt"; + $sql.= " WHERE DATE_FORMAT(pt.datec,'%Y') = ".date("Y")." "; + $sql.= " AND pt.rowid = ptt.fk_task"; + $sql.= " GROUP BY pt.fk_statut "; + $sql.= " ORDER BY pt.fk_statut DESC"; + $sql.= $db->plimit($max, 0); + + $result = $db->query($sql); + + if ($result) + { + $num = $db->num_rows($result); + $i = 0; + while ($i < $num) + { + $this->info_box_contents[$i][0] = array('td' => 'align="left" width="16"','logo' => 'object_projecttask'); + + $objp = $db->fetch_object($result); + $this->info_box_contents[$i][1] = array('td' => 'align="left"', + 'text' =>$langs->trans("Task")." ".$taskstatic->LibStatut($objp->fk_statut,0) + ); + + $this->info_box_contents[$i][2] = array('td' => 'align="right"', + 'text' => $objp->nb." ".$langs->trans("Tasks"), + 'url' => DOL_URL_ROOT."/projet/tasks/index.php?leftmenu=projects&viewstatut=".$objp->fk_statut + ); + $totalnb += $objp->nb; + $this->info_box_contents[$i][3] = array('td' => 'align="right"', 'text' => ConvertSecondToTime($objp->plannedtot,'all',25200,5)); + $totalplannedtot += $objp->plannedtot; + $this->info_box_contents[$i][4] = array('td' => 'align="right"', 'text' => ConvertSecondToTime($objp->durationtot,'all',25200,5)); + $totaldurationtot += $objp->durationtot; + + $this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"', 'text' => $taskstatic->LibStatut($objp->fk_statut,3)); + + $i++; + } + } + } + + + // Add the sum à the bottom of the boxes + $this->info_box_contents[$i][0] = array('tr' => 'class="liste_total"', 'td' => 'align="left" ', 'text' => $langs->trans("Total")." ".$textHead); + $this->info_box_contents[$i][1] = array('td' => '', 'text' => ""); + $this->info_box_contents[$i][2] = array('td' => 'align="right" ', 'text' => number_format($totalnb, 0, ',', ' ')." ".$langs->trans("Tasks")); + $this->info_box_contents[$i][3] = array('td' => 'align="right" ', 'text' => ConvertSecondToTime($totalplannedtot,'all',25200,5)); + $this->info_box_contents[$i][4] = array('td' => 'align="right" ', 'text' => ConvertSecondToTime($totaldurationtot,'all',25200,5)); + $this->info_box_contents[$i][5] = array('td' => '', 'text' => ""); + + } + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @return void + */ + function showBox($head = null, $contents = null) + { + parent::showBox($this->info_box_head, $this->info_box_contents); + } +} diff --git a/htdocs/core/boxes/index.html b/htdocs/core/boxes/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/core/boxes/index.php b/htdocs/core/boxes/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/core/boxes/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 7b54f0440a0..c6b6dad7acb 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -1,6 +1,7 @@ - * Copyright (C) 2005-2012 Regis Houssin +/* Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Raphaël Doursenaud * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -25,31 +26,88 @@ /** - * Parent class of boxes + * Class ModeleBoxes + * + * Boxes parent class */ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" boxes { - var $db; - var $error=''; - var $max=5; - var $enabled=1; - - var $rowid; - var $id; - var $position; - var $box_order; - var $fk_user; - var $sourcefile; - var $class; - var $box_id; - var $note; - + /** + * @var DoliDB Database handler + */ + public $db; /** - * Constructor + * @var string Error message + */ + public $error = ''; + + /** + * @var int Maximum lines + */ + public $max = 5; + + /** + * @var int Status + */ + public $enabled=1; + + /** + * @var int Box definition database ID + */ + public $rowid; + + /** + * @var int ID + * @deprecated Same as box_id? + */ + public $id; + + /** + * @var int Position? + */ + public $position; + + /** + * @var string Display order + */ + public $box_order; + + /** + * @var int User ID + */ + public $fk_user; + + /** + * @var string Source file + */ + public $sourcefile; + + /** + * @var string Class name + */ + public $class; + + /** + * @var string ID + */ + public $box_id; + + /** + * @var string Alphanumeric ID + */ + public $boxcode; + + /** + * @var string Note + */ + public $note; + + /** + * Constructor * - * @param DoliDB $db Database handler - * @param string $param More parameters + * @param DoliDB $db Database handler + * @param string $param More parameters */ function __construct($db,$param='') { @@ -57,9 +115,9 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" } /** - * Return last error message + * Return last error message * - * @return string Error message + * @return string Error message */ function error() { @@ -68,10 +126,11 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" /** - * Load a box line from its rowid + * Load a box line from its rowid * - * @param int $rowid Row id to load - * @return int <0 if KO, >0 if OK + * @param int $rowid Row id to load + * + * @return int <0 if KO, >0 if OK */ function fetch($rowid) { @@ -110,17 +169,19 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" /** - * Standard method to show a box (usage by boxes not mandatory, a box can still use its own showBox function) + *Standard method to show a box (usage by boxes not mandatory, a box can still use its own showBox function) * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * @return void + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * + * @return void */ function showBox($head, $contents) { global $langs,$conf; $MAXLENGTHBOX=60; // Mettre 0 pour pas de limite + $bcx=array(); $bcx[0] = 'class="box_pair"'; $bcx[1] = 'class="box_impair"'; $var = false; @@ -162,12 +223,12 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" if (! empty($head['sublink'])) print ''; if (! empty($head['subpicto'])) print img_picto($head['subtext'], $head['subpicto'], 'class="'.(empty($head['subclass'])?'':$head['subclass']).'" id="idsubimg'.$this->boxcode.'"'); if (! empty($head['sublink'])) ''; - if ($conf->use_javascript_ajax) + if (! empty($conf->use_javascript_ajax)) { print '
'; // The image must have the class 'boxhandle' beause it's value used in DOM draggable objects to define the area used to catch the full object print img_picto($langs->trans("MoveBox",$this->box_id),'grip_title','class="boxhandle hideonsmartphone" style="cursor:move;"'); - print img_picto($langs->trans("Close",$this->box_id),'close_title','class="boxclose" rel="x:y" style="cursor:pointer;" id="imgclose'.$this->box_id.'"'); + print img_picto($langs->trans("Close2",$this->box_id),'close_title','class="boxclose" rel="x:y" style="cursor:pointer;" id="imgclose'.$this->box_id.'"'); $label=$head['text']; if (! empty($head['graph'])) $label.=' ('.$langs->trans("Graph").')'; print ''; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 322d7f7ddcb..5288dc635cb 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -118,10 +118,10 @@ class CMailFile $this->mixed_boundary = "multipart_x." . time() . ".x_boundary"; // On defini related_boundary - $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2")); + $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars) // On defini alternative_boundary - $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3")); + $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars) // If ending method not defined if (empty($conf->global->MAIN_MAIL_SENDMODE)) $conf->global->MAIN_MAIL_SENDMODE='mail'; @@ -170,7 +170,7 @@ class CMailFile } } - // Add autocopy to + // 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; // Action according to choosed sending method @@ -657,6 +657,7 @@ class CMailFile { $out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2; } + // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that. $out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2; if (isset($this->reply_to) && $this->reply_to) $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2; if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2; @@ -970,7 +971,7 @@ class CMailFile } // cid - $this->html_images[$i]["cid"] = dol_hash(uniqid(time())); + $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars) $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html); } $i++; diff --git a/htdocs/core/class/cpays.class.php b/htdocs/core/class/ccountry.class.php similarity index 84% rename from htdocs/core/class/cpays.class.php rename to htdocs/core/class/ccountry.class.php index e6db8e4b2e9..59980cea7a9 100644 --- a/htdocs/core/class/cpays.class.php +++ b/htdocs/core/class/ccountry.class.php @@ -16,9 +16,9 @@ */ /** - * \file htdocs/core/class/cpays.class.php + * \file htdocs/core/class/ccountry.class.php * \ingroup core - * \brief This file is a CRUD class file (Create/Read/Update/Delete) for c_pays dictionary + * \brief This file is a CRUD class file (Create/Read/Update/Delete) for c_country dictionary */ // Put here all includes required by your class file @@ -30,18 +30,18 @@ /** * Class to manage dictionary Countries (used by imports) */ -class Cpays // extends CommonObject +class Ccountry // extends CommonObject { var $db; //!< To store db handler var $error; //!< To return error code (or message) var $errors=array(); //!< To return several error codes (or messages) - //var $element='cpays'; //!< Id that identify managed objects - //var $table_element='cpays'; //!< Name of table without prefix where object is stored + //var $element='ccountry'; //!< Id that identify managed objects + //var $table_element='ccountry'; //!< Name of table without prefix where object is stored var $id; var $code; var $code_iso; - var $libelle; + var $label; var $active; @@ -74,36 +74,36 @@ class Cpays // extends CommonObject // Clean parameters if (isset($this->code)) $this->code=trim($this->code); if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso); - if (isset($this->libelle)) $this->libelle=trim($this->libelle); + if (isset($this->label)) $this->label=trim($this->label); if (isset($this->active)) $this->active=trim($this->active); // Check parameters // Put here code to add control on parameters values // Insert request - $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_pays("; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country("; $sql.= "rowid,"; $sql.= "code,"; $sql.= "code_iso,"; - $sql.= "libelle,"; + $sql.= "label,"; $sql.= "active"; $sql.= ") VALUES ("; $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->rowid."'").","; $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").","; $sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").","; - $sql.= " ".(! isset($this->libelle)?'NULL':"'".$this->db->escape($this->libelle)."'").","; + $sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").","; $sql.= " ".(! isset($this->active)?'NULL':"'".$this->active."'").""; $sql.= ")"; $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } if (! $error) { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_pays"); + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country"); if (! $notrigger) { @@ -152,13 +152,13 @@ class Cpays // extends CommonObject $sql.= " t.rowid,"; $sql.= " t.code,"; $sql.= " t.code_iso,"; - $sql.= " t.libelle,"; + $sql.= " t.label,"; $sql.= " t.active"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_pays as t"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_country as t"; if ($id) $sql.= " WHERE t.rowid = ".$id; elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -169,7 +169,7 @@ class Cpays // extends CommonObject $this->id = $obj->rowid; $this->code = $obj->code; $this->code_iso = $obj->code_iso; - $this->libelle = $obj->libelle; + $this->label = $obj->label; $this->active = $obj->active; } $this->db->free($resql); @@ -179,7 +179,6 @@ class Cpays // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -192,7 +191,7 @@ class Cpays // extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -200,7 +199,7 @@ class Cpays // extends CommonObject // Clean parameters if (isset($this->code)) $this->code=trim($this->code); if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso); - if (isset($this->libelle)) $this->libelle=trim($this->libelle); + if (isset($this->label)) $this->label=trim($this->label); if (isset($this->active)) $this->active=trim($this->active); @@ -208,16 +207,16 @@ class Cpays // extends CommonObject // Put here code to add control on parameters values // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."c_pays SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET"; $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").","; $sql.= " code_iso=".(isset($this->code_iso)?"'".$this->db->escape($this->code_iso)."'":"null").","; - $sql.= " libelle=".(isset($this->libelle)?"'".$this->db->escape($this->libelle)."'":"null").","; + $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").","; $sql.= " active=".(isset($this->active)?$this->active:"null").""; $sql.= " WHERE rowid=".$this->id; $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -257,10 +256,10 @@ class Cpays // extends CommonObject /** - * Delete object in database + * Delete object in database * - * @param User $user User that delete - * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ function delete($user, $notrigger=0) @@ -268,12 +267,12 @@ class Cpays // extends CommonObject global $conf, $langs; $error=0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_pays"; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country"; $sql.= " WHERE rowid=".$this->id; $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 882e0780ed4..26f209ed107 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -27,8 +27,7 @@ /** - * \class CommonDocGenerator - * \brief Parent class for documents generators + * Parent class for documents generators */ abstract class CommonDocGenerator { @@ -119,10 +118,9 @@ abstract class CommonDocGenerator 'mycompany_idprof5'=>$mysoc->idprof5, 'mycompany_idprof6'=>$mysoc->idprof6, 'mycompany_vatnumber'=>$mysoc->tva_intra, - // Only private not exists for "mysoc" - 'mycompany_note'=>$mysoc->note_private - //'mycompany_note_private'=>$mysoc->note_private, - //'mycompany_note_public'=>$mysoc->note_public, + // Only private not exists for "mysoc" + 'mycompany_note_private'=>$mysoc->note_private, + ); } @@ -167,6 +165,7 @@ abstract class CommonDocGenerator 'company_customeraccountancycode'=>$object->code_compta, 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, 'company_juridicalstatus'=>$object->forme_juridique, + 'company_outstanding_limit'=>$object->outstanding_limit, 'company_capital'=>$object->capital, 'company_idprof1'=>$object->idprof1, 'company_idprof2'=>$object->idprof2, @@ -291,6 +290,10 @@ abstract class CommonDocGenerator 'current_datehour'=>dol_print_date($now,'dayhour','tzuser'), 'current_server_date'=>dol_print_date($now,'day','tzserver'), 'current_server_datehour'=>dol_print_date($now,'dayhour','tzserver'), + 'current_date_locale'=>dol_print_date($now,'day','tzuser',$outputlangs), + 'current_datehour_locale'=>dol_print_date($now,'dayhour','tzuser',$outputlangs), + 'current_server_date_locale'=>dol_print_date($now,'day','tzserver',$outputlangs), + 'current_server_datehour_locale'=>dol_print_date($now,'dayhour','tzserver',$outputlangs), ); return $array_other; @@ -358,7 +361,8 @@ abstract class CommonDocGenerator $array_key.'_total_discount_ht' => price2num($object->getTotalDiscount()), $array_key.'_note_private'=>$object->note, - $array_key.'_note'=>$object->note_public, + $array_key.'_note_public'=>$object->note_public, + $array_key.'_note'=>$object->note_public, // For backward compatibility // Payments $array_key.'_already_payed_locale'=>price($alreadypayed, 0, $outputlangs), $array_key.'_remain_to_pay_locale'=>price($object->total_ttc - $sumpayed, 0, $outputlangs), diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 6d657f0c36c..90ad3e196e3 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -47,7 +47,7 @@ abstract class CommonInvoice extends CommonObject $sql.= ' FROM '.MAIN_DB_PREFIX.$table; $sql.= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -154,9 +154,9 @@ abstract class CommonInvoice extends CommonObject /** * Return label of object status * - * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto - * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) - * @return string Label + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto + * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise) + * @return string Label */ function getLibStatut($mode=0,$alreadypaid=-1) { @@ -308,7 +308,7 @@ abstract class CommonInvoice extends CommonObject if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement; else $sqltemp.= " WHERE c.code='".$this->db->escape($cond_reglement)."'"; - dol_syslog(get_class($this).'::calculate_date_lim_reglement sql='.$sqltemp); + dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG); $resqltemp=$this->db->query($sqltemp); if ($resqltemp) { @@ -358,10 +358,14 @@ abstract class CommonInvoice extends CommonObject } } + + +require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php'; + /** * Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...) */ -abstract class CommonInvoiceLine extends CommonObject +abstract class CommonInvoiceLine extends CommonObjectLine { } diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index e0bab998982..1a9195e069d 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -34,7 +34,7 @@ */ abstract class CommonObject { - protected $db; + public $db; public $error; public $errors; public $canvas; // Contains canvas name if it is @@ -47,6 +47,8 @@ abstract class CommonObject public $array_options=array(); + public $thirdparty; + public $linkedObjectsIds; // Loaded by ->fetchObjectLinked public $linkedObjects; // Loaded by ->fetchObjectLinked @@ -78,7 +80,7 @@ abstract class CommonObject return -1; } - dol_syslog(get_class()."::isExistingObject sql=".$sql); + dol_syslog(get_class()."::isExistingObject", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -116,7 +118,6 @@ abstract class CommonObject $lastname=$this->lastname; $firstname=$this->firstname; if (empty($lastname)) $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:''))); - if (empty($firstname)) $firstname=$this->firstname; $ret=''; if ($option && $this->civility_id) @@ -155,7 +156,7 @@ abstract class CommonObject * Add a link between element $this->element and a contact * * @param int $fk_socpeople Id of contact to link - * @param int $type_contact Type of contact (code or id) + * @param int $type_contact Type of contact (code or id). For example: SALESREPFOLL * @param int $source external=Contact extern (llx_socpeople), internal=Contact intern (llx_user) * @param int $notrigger Disable all triggers * @return int <0 if KO, >0 if OK @@ -164,7 +165,6 @@ abstract class CommonObject { global $user,$conf,$langs; - $error=0; dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source"); @@ -192,9 +192,10 @@ abstract class CommonObject // On recherche id type_contact $sql = "SELECT tc.rowid"; $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql.= " WHERE element='".$this->element."'"; - $sql.= " AND source='".$source."'"; - $sql.= " AND code='".$type_contact."' AND active=1"; + $sql.= " WHERE tc.element='".$this->element."'"; + $sql.= " AND tc.source='".$source."'"; + $sql.= " AND tc.code='".$type_contact."' AND tc.active=1"; + //print $sql; $resql=$this->db->query($sql); if ($resql) { @@ -205,6 +206,8 @@ abstract class CommonObject $datecreate = dol_now(); + $this->db->begin(); + // Insertion dans la base $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact"; $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) "; @@ -212,23 +215,18 @@ abstract class CommonObject $sql.= "'".$this->db->idate($datecreate)."'"; $sql.= ", 4, '". $id_type_contact . "' "; $sql.= ")"; - dol_syslog(get_class($this)."::add_contact sql=".$sql); + dol_syslog(get_class($this)."::add_contact", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers(strtoupper($this->element).'_ADD_CONTACT',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End call triggers + $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user); + if ($result < 0) { $this->db->rollback(); return -1; } } + $this->db->commit(); return 1; } else @@ -236,12 +234,13 @@ abstract class CommonObject if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error=$this->db->errno(); + $this->db->rollback(); return -2; } else { $this->error=$this->db->error(); - dol_syslog($this->error,LOG_ERR); + $this->db->rollback(); return -1; } } @@ -264,7 +263,6 @@ abstract class CommonObject if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::copy_contact error=".$this->error, LOG_ERR); return -1; } } @@ -311,32 +309,28 @@ abstract class CommonObject { global $user,$langs,$conf; - $error=0; + + $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; $sql.= " WHERE rowid =".$rowid; - dol_syslog(get_class($this)."::delete_contact sql=".$sql); + dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG); if ($this->db->query($sql)) { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers(strtoupper($this->element).'_DELETE_CONTACT',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End call triggers + $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user); + if ($result < 0) { $this->db->rollback(); return -1; } } + $this->db->commit(); return 1; } else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete_contact error=".$this->error, LOG_ERR); + $this->db->rollback(); return -1; } } @@ -344,12 +338,14 @@ abstract class CommonObject /** * Delete all links between an object $this and all its contacts * - * @return int >0 if OK, <0 if KO + * @param string $source '' or 'internal' or 'external' + * @param string $code Type of contact (code or id) + * @return int >0 if OK, <0 if KO */ - function delete_linked_contact() + function delete_linked_contact($source='',$code='') { $temp = array(); - $typeContact = $this->liste_type_contact(''); + $typeContact = $this->liste_type_contact($source,'',0,0,$code); foreach($typeContact as $key => $value) { @@ -358,18 +354,17 @@ abstract class CommonObject $listId = implode(",", $temp); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; - $sql.= " WHERE element_id =".$this->id; + $sql.= " WHERE element_id = ".$this->id; $sql.= " AND fk_c_type_contact IN (".$listId.")"; - dol_syslog(get_class($this)."::delete_linked_contact sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG); if ($this->db->query($sql)) { return 1; } else - { + { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete_linked_contact error=".$this->error, LOG_ERR); return -1; } } @@ -391,7 +386,7 @@ abstract class CommonObject $sql = "SELECT ec.rowid, ec.statut, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user if ($source == 'internal') $sql.=", '-1' as socid"; if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid"; - $sql.= ", t.civilite as civility, t.lastname as lastname, t.firstname, t.email"; + $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email"; $sql.= ", tc.source, tc.element, tc.code, tc.libelle"; $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc"; $sql.= ", ".MAIN_DB_PREFIX."element_contact ec"; @@ -406,7 +401,7 @@ abstract class CommonObject if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'"; $sql.=" ORDER BY t.lastname ASC"; - dol_syslog(get_class($this)."::liste_contact sql=".$sql); + dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -461,7 +456,7 @@ abstract class CommonObject $sql.= " AND ec.fk_c_type_contact=tc.rowid"; $sql.= " AND tc.element = '".$this->element."'"; - dol_syslog(get_class($this)."::swapContactStatus sql=".$sql); + dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -486,21 +481,23 @@ abstract class CommonObject * @param string $source 'internal', 'external' or 'all' * @param string $order Sort order by : 'code' or 'rowid' * @param string $option 0=Return array id->label, 1=Return array code->label - * @param string $activeonly 0=all type of contact, 1=only the active + * @param string $activeonly 0=all status of contact, 1=only the active + * @param string $code Type of contact (Example: 'CUSTOMER', 'SERVICE') * @return array Array list of type of contacts (id->label if option=0, code->label if option=1) */ - function liste_type_contact($source='internal', $order='code', $option=0, $activeonly=0) + function liste_type_contact($source='internal', $order='', $option=0, $activeonly=0, $code='') { global $langs; + if (empty($order)) $order='code'; + $tab = array(); $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle"; $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc"; $sql.= " WHERE tc.element='".$this->element."'"; - if ($activeonly == 1) - $sql.= " AND tc.active=1"; // only the active type - - if (! empty($source)) $sql.= " AND tc.source='".$source."'"; + if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active type + if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$source."'"; + if (! empty($code)) $sql.= " AND tc.code='".$code."'"; $sql.= " ORDER by tc.".$order; //print "sql=".$sql; @@ -563,7 +560,7 @@ abstract class CommonObject $sql.= " AND tc.active = 1"; if ($status) $sql.= " AND ec.statut = ".$status; - dol_syslog(get_class($this)."::getIdContact sql=".$sql); + dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -576,7 +573,6 @@ abstract class CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::getIdContact ".$this->error, LOG_ERR); return null; } @@ -586,11 +582,15 @@ abstract class CommonObject /** * Charge le contact d'id $id dans this->contact * - * @param int $contactid Id du contact + * @param int $contactid Id du contact. Use this->contactid if empty. * @return int <0 if KO, >0 if OK */ - function fetch_contact($contactid) + function fetch_contact($contactid='') { + if (empty($contactid)) $contactid=$this->contactid; + + if (empty($contactid)) return 0; + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; $contact = new Contact($this->db); $result=$contact->fetch($contactid); @@ -599,20 +599,24 @@ abstract class CommonObject } /** - * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdpary + * Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty * - * @return int <0 if KO, >0 if OK + * @param int $force_thirdparty_id Force thirdparty id + * @return int <0 if KO, >0 if OK */ - function fetch_thirdparty() + function fetch_thirdparty($force_thirdparty_id=0) { global $conf; - if (empty($this->socid) && empty($this->fk_soc)) return 0; + if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) return 0; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $idtofetch=isset($this->socid)?$this->socid:(isset($this->fk_soc)?$this->fk_soc:$this->fk_thirdparty); + if ($force_thirdparty_id) $idtofetch=$force_thirdparty_id; + $thirdparty = new Societe($this->db); - $result=$thirdparty->fetch(isset($this->socid)?$this->socid:$this->fk_soc); + $result=$thirdparty->fetch($idtofetch); $this->client = $thirdparty; // deprecated $this->thirdparty = $thirdparty; @@ -629,7 +633,7 @@ abstract class CommonObject /** * Load data for barcode into properties ->barcode_type* - * Properties ->barcode_type that is id of barcode type is used to find other properties, but + * Properties ->barcode_type that is id of barcode. Type is used to find other properties, but * if it is not defined, ->element must be defined to know default barcode type. * * @return int <0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded) @@ -655,7 +659,7 @@ abstract class CommonObject $sql = "SELECT rowid, code, libelle as label, coder"; $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type"; $sql.= " WHERE rowid = ".$idtype; - dol_syslog(get_class($this).'::fetch_barcode sql='.$sql); + dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -741,7 +745,7 @@ abstract class CommonObject $sql.= " WHERE ".$field." = '".$key."'"; $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this).'::fetchObjectFrom sql='.$sql); + dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -767,7 +771,7 @@ abstract class CommonObject $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table; $sql.= " WHERE rowid = ".$id; - dol_syslog(get_class($this).'::getValueFrom sql='.$sql); + dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -807,7 +811,7 @@ abstract class CommonObject if (is_object($user)) $sql.=", fk_user_modif = ".$user->id; $sql.= " WHERE ".$id_field." = ".$id; - dol_syslog(get_class($this)."::".__FUNCTION__." sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -933,7 +937,7 @@ abstract class CommonObject else $sql.= ' SET fk_projet = NULL'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setProject sql=".$sql); + dol_syslog(get_class($this)."::setProject", LOG_DEBUG); if ($this->db->query($sql)) { $this->fk_project = $projectid; @@ -1054,6 +1058,37 @@ abstract class CommonObject } } + + /** + * Change the shipping method + * + * @param int $shipping_method_id Id of shipping method + * @return int 1 if OK, 0 if KO + */ + function setShippingMethod($shipping_method_id) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($shipping_method_id<0) $shipping_method_id='NULL'; + dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')'); + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_shipping_method = ".$shipping_method_id; + $sql.= " WHERE rowid=".$this->id; + + if ($this->db->query($sql)) { + $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id; + return 1; + } else { + dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG); + $this->error=$this->db->error(); + return 0; + } + } + + /** * Set last model used by doc generator * @@ -1077,7 +1112,7 @@ abstract class CommonObject // if ($this->element == 'facture') $sql.= " AND fk_statut < 2"; // if ($this->element == 'propal') $sql.= " AND fk_statut = 0"; - dol_syslog(get_class($this)."::setDocModel sql=".$sql); + dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1091,6 +1126,36 @@ abstract class CommonObject } } + + /** + * Change the bank account + * + * @param int $fk_account Id of bank account + * @return int 1 if OK, 0 if KO + */ + function setBankAccount($fk_account) + { + if (! $this->table_element) { + dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR); + return -1; + } + if ($fk_account<0) $fk_account='NULL'; + dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')'); + + $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element; + $sql.= " SET fk_account = ".$fk_account; + $sql.= " WHERE rowid=".$this->id; + + if ($this->db->query($sql)) { + $this->fk_account = ($fk_account=='NULL')?null:$fk_account; + return 1; + } else { + dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error()); + $this->error=$this->db->error(); + return 0; + } + } + /** * Save a new position (field rang) for details lines. * You can choose to set position for lines with already a position or lines without any position defined. @@ -1120,7 +1185,7 @@ abstract class CommonObject if (! $renum) $sql.= ' AND rang = 0'; if ($renum) $sql.= ' AND rang <> 0'; - dol_syslog(get_class($this)."::line_order sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::line_order", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1140,7 +1205,7 @@ abstract class CommonObject if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL'; $sql.= ' ORDER BY rang ASC, rowid '.$rowidorder; - dol_syslog(get_class($this)."::line_order search all parent lines sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1192,7 +1257,7 @@ abstract class CommonObject $sql.= ' AND fk_parent_line = '.$id; $sql.= ' ORDER BY rang ASC'; - dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id." sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1260,7 +1325,7 @@ abstract class CommonObject $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET rang = '.$rang; $sql.= ' WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::updateRangOfLine sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG); if (! $this->db->query($sql)) { dol_print_error($this->db); @@ -1354,7 +1419,7 @@ abstract class CommonObject $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql.= ' WHERE rowid ='.$rowid; - dol_syslog(get_class($this)."::getRangOfLine sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1397,7 +1462,7 @@ abstract class CommonObject $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; $sql.= ' AND fk_parent_line = '.$fk_parent_line; - dol_syslog(get_class($this)."::line_max sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1418,7 +1483,7 @@ abstract class CommonObject $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line; $sql.= ' WHERE '.$this->fk_element.' = '.$this->id; - dol_syslog(get_class($this)."::line_max sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::line_max", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1446,7 +1511,7 @@ abstract class CommonObject $sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'"; $sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id; - dol_syslog(get_class($this)."::update_ref_ext sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG); if ($this->db->query($sql)) { $this->ref_ext = $ref_ext; @@ -1455,7 +1520,6 @@ abstract class CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update_ref_ext error=".$this->error, LOG_ERR); return -1; } } @@ -1484,7 +1548,7 @@ abstract class CommonObject $sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL"); $sql.= " WHERE rowid =". $this->id; - dol_syslog(get_class($this)."::update_note sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update_note", LOG_DEBUG); if ($this->db->query($sql)) { if ($suffix == '_public') $this->note_public = $note; @@ -1495,7 +1559,6 @@ abstract class CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::update_note error=".$this->error, LOG_ERR); return -1; } } @@ -1559,7 +1622,7 @@ abstract class CommonObject } $sql.= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used - dol_syslog(get_class($this)."::update_price sql=".$sql); + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1659,13 +1722,12 @@ abstract class CommonObject $sql .= ' WHERE rowid = '.$this->id; //print "xx".$sql; - dol_syslog(get_class($this)."::update_price sql=".$sql); + dol_syslog(get_class($this)."::update_price", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update_price error=".$this->error,LOG_ERR); } } @@ -1691,6 +1753,7 @@ abstract class CommonObject * @param string $origin Linked element type * @param int $origin_id Linked element id * @return int <=0 if KO, >0 if OK + * @see fetchObjectLinked, updateObjectLinked, deleteObjectLinked */ function add_object_linked($origin=null, $origin_id=null) { @@ -1711,7 +1774,7 @@ abstract class CommonObject $sql.= ", '".$this->element."'"; $sql.= ")"; - dol_syslog(get_class($this)."::add_object_linked sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); if ($this->db->query($sql)) { $this->db->commit(); @@ -1734,6 +1797,7 @@ abstract class CommonObject * @param string $targettype Object target type * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided * @return void + * @see add_object_linked, updateObjectLinked, deleteObjectLinked */ function fetchObjectLinked($sourceid='',$sourcetype='',$targetid='',$targettype='',$clause='OR') { @@ -1763,6 +1827,12 @@ abstract class CommonObject $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element); $targettype = (! empty($targettype) ? $targettype : $this->element); + if (empty($sourceid) && empty($targetid)) + { + dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERROR); + return -1; + } + // Links beetween objects are stored in this table $sql = 'SELECT fk_source, sourcetype, fk_target, targettype'; $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element'; @@ -1788,7 +1858,7 @@ abstract class CommonObject $sql .= ' ORDER BY sourcetype'; //print $sql; - dol_syslog(get_class($this)."::fetchObjectLink sql=".$sql); + dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1888,6 +1958,7 @@ abstract class CommonObject * @param int $targetid Object target id * @param string $targettype Object target type * @return int >0 if OK, <0 if KO + * @see add_object_linked, fetObjectLinked, deleteObjectLinked */ function updateObjectLinked($sourceid='', $sourcetype='', $targetid='', $targettype='') { @@ -1913,7 +1984,7 @@ abstract class CommonObject $sql.= " AND sourcetype = '".$this->element."'"; } - dol_syslog(get_class($this)."::updateObjectLinked sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); if ($this->db->query($sql)) { return 1; @@ -1921,7 +1992,6 @@ abstract class CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::updateObjectLinked error=".$this->error, LOG_ERR); return -1; } } @@ -1934,6 +2004,7 @@ abstract class CommonObject * @param int $targetid Object target id * @param string $targettype Object target type * @return int >0 if OK, <0 if KO + * @see add_object_linked, updateObjectLinked, fetchObjectLinked */ function deleteObjectLinked($sourceid='', $sourcetype='', $targetid='', $targettype='') { @@ -1967,7 +2038,7 @@ abstract class CommonObject $sql.= " (fk_target = ".$this->id." AND targettype = '".$this->element."')"; } - dol_syslog(get_class($this)."::deleteObjectLinked sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG); if ($this->db->query($sql)) { return 1; @@ -1975,7 +2046,6 @@ abstract class CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::deleteObjectLinked error=".$this->error, LOG_ERR); return -1; } } @@ -1990,6 +2060,8 @@ abstract class CommonObject */ function setStatut($status,$elementId='',$elementType='') { + global $user,$langs,$conf; + $elementId = (!empty($elementId)?$elementId:$this->id); $elementTable = (!empty($elementType)?$elementType:$this->table_element); @@ -2002,17 +2074,44 @@ abstract class CommonObject $sql.= " SET ".$fieldstatus." = ".$status; $sql.= " WHERE rowid=".$elementId; - dol_syslog(get_class($this)."::setStatut sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::setStatut", LOG_DEBUG); if ($this->db->query($sql)) { - $this->db->commit(); - $this->statut = $status; - return 1; + if (! $error) + { + $trigkey=''; + if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED'; + if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED'; + + if ($trigkey) + { + // Appel des triggers + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf); + if ($result < 0) { + $error++; $this->errors=$interface->errors; + } + // Fin appel triggers + } + } + + if (! $error) + { + $this->db->commit(); + $this->statut = $status; + return 1; + } + else + { + $this->db->rollback(); + dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR); + return -1; + } } else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::setStatut ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -2080,328 +2179,6 @@ abstract class CommonObject } } - - /** - * Function to get extra fields of a member into $this->array_options - * This method is in most cases called by method fetch of objects but you can call it separately. - * - * @param int $rowid Id of line - * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label() - * @return int <0 if error, 0 if no optionals to find nor found, 1 if a line is found and optional loaded - */ - function fetch_optionals($rowid,$optionsArray='') - { - if (! is_array($optionsArray)) - { - // optionsArray not already loaded, so we load it - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $optionsArray = $extrafields->fetch_name_optionals_label($this->table_element); - } - - - // Request to get complementary values - if (count($optionsArray) > 0) - { - $sql = "SELECT rowid"; - foreach ($optionsArray as $name => $label) - { - $sql.= ", ".$name; - } - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields"; - $sql.= " WHERE fk_object = ".$rowid; - - dol_syslog(get_class($this)."::fetch_optionals sql=".$sql, LOG_DEBUG); - $resql=$this->db->query($sql); - if ($resql) - { - $numrows=$this->db->num_rows($resql); - if ($numrows) - { - $tab = $this->db->fetch_array($resql); - - foreach ($tab as $key => $value) - { - // Test fetch_array ! is_int($key) because fetch_array result is a mix table with some key as alpha and some key as int (depend db engine) - if ($key != 'rowid' && $key != 'tms' && ! is_int($key)) - { - // we can add this attribute to object properties - $this->array_options["options_".$key]=$value; - } - } - } - - $this->db->free($resql); - - if ($numrows) return $numrows; - else return 0; - } - else - { - dol_print_error($this->db); - return -1; - } - } - return 0; - } - - /** - * Delete all extra fields values for the current object. - * - * @return int <0 if KO, >0 if OK - */ - function deleteExtraFields() - { - global $langs; - - $error=0; - - $this->db->begin(); - - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::deleteExtraFields delete sql=".$sql_del); - $resql=$this->db->query($sql_del); - if (! $resql) - { - $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::deleteExtraFields ".$this->error,LOG_ERR); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - - /** - * Add/Update all extra fields values for the current object. - * All data to describe values to insert are stored into $this->array_options=array('keyextrafield'=>'valueextrafieldtoadd') - * - * @return int -1=error, O=did nothing, 1=OK - */ - function insertExtraFields() - { - global $conf,$langs; - - $error=0; - - if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used - - if (! empty($this->array_options)) - { - // Check parameters - $langs->load('admin'); - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $optionsArray = $extrafields->fetch_name_optionals_label($this->table_element); - - foreach($this->array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - $attributeType = $extrafields->attribute_type[$attributeKey]; - $attributeSize = $extrafields->attribute_size[$attributeKey]; - $attributeLabel = $extrafields->attribute_label[$attributeKey]; - switch ($attributeType) - { - case 'int': - if (!is_numeric($value) && $value!='') - { - $error++; $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); - return -1; - } - elseif ($value=='') - { - $this->array_options[$key] = null; - } - break; - case 'price': - $this->array_options[$key] = price2num($this->array_options[$key]); - break; - case 'date': - if (is_numeric($this->array_options[$key])) $this->array_options[$key]=$this->db->idate($this->array_options[$key]); - break; - case 'datetime': - if (is_numeric($this->array_options[$key])) $this->array_options[$key]=$this->db->idate($this->array_options[$key]); - break; - } - } - $this->db->begin(); - - $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id; - dol_syslog(get_class($this)."::insertExtraFields delete sql=".$sql_del); - $this->db->query($sql_del); - $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."_extrafields (fk_object"; - foreach($this->array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field of attribut - if (isset($extrafields->attribute_type[$attributeKey]) && $extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate - $sql.=",".$attributeKey; - } - $sql .= ") VALUES (".$this->id; - foreach($this->array_options as $key => $value) - { - $attributeKey = substr($key,8); // Remove 'options_' prefix - // Add field o fattribut - if(isset($extrafields->attribute_type[$attributeKey]) && $extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) - { - if ($this->array_options[$key] != '') - { - $sql.=",'".$this->db->escape($this->array_options[$key])."'"; - } - else - { - $sql.=",null"; - } - } - } - $sql.=")"; - - dol_syslog(get_class($this)."::insertExtraFields insert sql=".$sql); - $resql = $this->db->query($sql); - if (! $resql) - { - $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR); - $this->db->rollback(); - return -1; - } - else - { - $this->db->commit(); - return 1; - } - } - else return 0; - } - - /** - * Function to show lines of extrafields with output datas - * - * @param object $extrafields Extrafield Object - * @param string $mode Show output (view) or input (edit) for extrafield - * @param array $params Optionnal parameters - * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) - * - * @return string - */ - function showOptionals($extrafields, $mode='view', $params=0, $keyprefix='') - { - global $_POST, $conf; - - $out = ''; - - if (count($extrafields->attribute_label) > 0) - { - $out .= "\n"; - $out .= ' '; - $out .= "\n"; - - $e = 0; - foreach($extrafields->attribute_label as $key=>$label) - { - if (is_array($params) && count($params)>0) { - if (array_key_exists('colspan',$params)) { - $colspan=$params['colspan']; - } - }else { - $colspan='3'; - } - switch($mode) { - case "view": - $value=$this->array_options["options_".$key]; - break; - case "edit": - $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$this->array_options["options_".$key]); - break; - } - if ($extrafields->attribute_type[$key] == 'separate') - { - $out .= $extrafields->showSeparator($key); - } - else - { - $csstyle=''; - if (is_array($params) && count($params)>0) { - if (array_key_exists('style',$params)) { - $csstyle=$params['style']; - } - } - if ( !empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) - { - $out .= '
'.$label.'
 '.$langs->trans('Description').''.$langs->trans('VAT').''.$langs->trans('PriceUHT').'  '.$langs->trans('Qty').''.$langs->trans('ReductionShort').''.$langs->trans('BuyingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('CostPrice').''.$langs->trans('MarginRate').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').''.$langs->trans('MarkRate').'
'; + if (! empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON)) // FIXME Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better + { + print $langs->trans('ShowMarginInfos').' : '; + $hidemargininfos = $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']; + print ''.img_picto($langs->trans("Disabled"),'switch_off').''; + print ''.img_picto($langs->trans("Enabled"),'switch_on').''; + print ''; + if (!empty($hidemargininfos)) print ''; + } + + print '
'; print ''; - print ''; - print ''; + print ''; + print ''; if ($conf->global->MARGIN_TYPE == "1") - print ''; + print ''; else - print ''; - print ''; + print ''; + print ''; if (! empty($conf->global->DISPLAY_MARGIN_RATES)) - print ''; + print ''; if (! empty($conf->global->DISPLAY_MARK_RATES)) - print ''; + print ''; print ''; if (! empty($conf->product->enabled)) @@ -3329,7 +3121,7 @@ abstract class CommonObject $sql.= ", '".$mandatory."'"; $sql.= ")"; - dol_syslog(get_class($this)."::add_element_resource sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG); if ($this->db->query($sql)) { $this->db->commit(); @@ -3355,24 +3147,19 @@ abstract class CommonObject { global $user,$langs,$conf; - $error=0; + + $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources"; $sql.= " WHERE rowid =".$rowid; - dol_syslog(get_class($this)."::delete_resource sql=".$sql); + dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG); if ($this->db->query($sql)) { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers(strtoupper($element).'_DELETE_RESOURCE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // End call triggers + $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user); + if ($result < 0) { $this->db->rollback(); return -1; } } return 1; @@ -3380,7 +3167,7 @@ abstract class CommonObject else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete_resource error=".$this->error, LOG_ERR); + $this->db->rollback(); return -1; } } @@ -3404,4 +3191,458 @@ abstract class CommonObject } } + /** + * Common function for all objects extending CommonObject for generating documents + * + * @param string $modelspath Relative folder where models are placed + * @param string $modele Model to use + * @param Translate $outputlangs Language to use + * @param int $hidedetails 1 to hide details. 0 by default + * @param int $hidedesc 1 to hide product description. 0 by default + * @param int $hideref 1 to hide product reference. 0 by default + * @return int 1 if OK -1 if not OK + */ + protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref) + { + global $conf, $langs; + + $srctemplatepath=''; + + // Increase limit for PDF build + $err=error_reporting(); + error_reporting(0); + @set_time_limit(120); + error_reporting($err); + + // If selected modele is a filename template (then $modele="modelname:filename") + $tmp=explode(':',$modele,2); + if (! empty($tmp[1])) + { + $modele=$tmp[0]; + $srctemplatepath=$tmp[1]; + } + + // Search template files + $file=''; $classname=''; $filefound=0; + $dirmodels=array('/'); + if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']); + foreach($dirmodels as $reldir) + { + foreach(array('doc','pdf') as $prefix) + { + $file = $prefix."_".$modele.".modules.php"; + + // On verifie l'emplacement du modele + $file=dol_buildpath($reldir.$modelspath.$file,0); + if (file_exists($file)) + { + $filefound=1; + $classname=$prefix.'_'.$modele; + break; + } + } + if ($filefound) break; + } + + // Charge le modele + if ($filefound) + { + require_once $file; + + $obj = new $classname($this->db); + //$obj->message = $message; + + // We save charset_output to restore it because write_file can change it if needed for + // output format that does not support UTF8. + $sav_charset_output=$outputlangs->charset_output; + if ($obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref) > 0) + { + $outputlangs->charset_output=$sav_charset_output; + + // We delete old preview + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_delete_preview($this); + + // Success in building document. We build meta file. + dol_meta_create($this); + + return 1; + } + else + { + $outputlangs->charset_output=$sav_charset_output; + dol_print_error($this->db,"Error generating document for ".__CLASS__.". Error: ".$obj->error); + return -1; + } + + } + else + { + dol_print_error('',$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file)); + return -1; + } + } + + + /* Functions common to commonobject and commonobjectline */ + + + /* For triggers */ + + + /** + * Call trigger based on this instance + * NB: Error from trigger are stacked in interface->errors + * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction. + * + * @param string $trigger_name trigger's name to execute + * @param User $user Object user + * @return int Result of run_triggers + */ + function call_trigger($trigger_name, $user) + { + global $langs,$conf; + + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); + + if ($result < 0) + { + if (!empty($this->errors)) + { + $this->errors=array_merge($this->errors,$interface->errors); + } + else + { + $this->errors=$interface->errors; + } + } + + return $result; + } + + + /* Functions for extrafields */ + + + /** + * Function to get extra fields of a member into $this->array_options + * This method is in most cases called by method fetch of objects but you can call it separately. + * + * @param int $rowid Id of line + * @param array $optionsArray Array resulting of call of extrafields->fetch_name_optionals_label() + * @return int <0 if error, 0 if no optionals to find nor found, 1 if a line is found and optional loaded + */ + function fetch_optionals($rowid='',$optionsArray='') + { + if (empty($rowid)) $rowid=$this->id; + + if (! is_array($optionsArray)) + { + // optionsArray not already loaded, so we load it + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $optionsArray = $extrafields->fetch_name_optionals_label($this->table_element); + } + + // Request to get complementary values + if (count($optionsArray) > 0) + { + $sql = "SELECT rowid"; + foreach ($optionsArray as $name => $label) + { + $sql.= ", ".$name; + } + $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields"; + $sql.= " WHERE fk_object = ".$rowid; + + dol_syslog(get_class($this)."::fetch_optionals", LOG_DEBUG); + $resql=$this->db->query($sql); + if ($resql) + { + $numrows=$this->db->num_rows($resql); + if ($numrows) + { + $tab = $this->db->fetch_array($resql); + + foreach ($tab as $key => $value) + { + // Test fetch_array ! is_int($key) because fetch_array seult is a mix table with Key as alpha and Key as int (depend db engine) + if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key)) + { + // we can add this attribute to adherent object + $this->array_options["options_".$key]=$value; + } + } + } + + $this->db->free($resql); + + if ($numrows) return $numrows; + else return 0; + } + else + { + dol_print_error($this->db); + return -1; + } + } + return 0; + } + + /** + * Delete all extra fields values for the current object. + * + * @return int <0 if KO, >0 if OK + */ + function deleteExtraFields() + { + global $langs; + + $error=0; + + $this->db->begin(); + + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id; + dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG); + $resql=$this->db->query($sql_del); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + + /** + * Add/Update all extra fields values for the current object. + * All data to describe values to insert are stored into $this->array_options=array('keyextrafield'=>'valueextrafieldtoadd') + * + * @return int -1=error, O=did nothing, 1=OK + */ + function insertExtraFields() + { + global $conf,$langs; + + $error=0; + + if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used + + if (! empty($this->array_options)) + { + // Check parameters + $langs->load('admin'); + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $optionsArray = $extrafields->fetch_name_optionals_label($this->table_element); + + foreach($this->array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + $attributeType = $extrafields->attribute_type[$attributeKey]; + $attributeSize = $extrafields->attribute_size[$attributeKey]; + $attributeLabel = $extrafields->attribute_label[$attributeKey]; + switch ($attributeType) + { + case 'int': + if (!is_numeric($value) && $value!='') + { + $error++; $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel); + return -1; + } + elseif ($value=='') + { + $this->array_options[$key] = null; + } + break; + case 'price': + $this->array_options[$key] = price2num($this->array_options[$key]); + break; + case 'date': + $this->array_options[$key]=$this->db->idate($this->array_options[$key]); + break; + case 'datetime': + $this->array_options[$key]=$this->db->idate($this->array_options[$key]); + break; + } + } + $this->db->begin(); + + $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields WHERE fk_object = ".$this->id; + dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG); + $this->db->query($sql_del); + $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element."_extrafields (fk_object"; + foreach($this->array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field of attribut + if ($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate + $sql.=",".$attributeKey; + } + $sql .= ") VALUES (".$this->id; + foreach($this->array_options as $key => $value) + { + $attributeKey = substr($key,8); // Remove 'options_' prefix + // Add field o fattribut + if($extrafields->attribute_type[$attributeKey] != 'separate') // Only for other type of separate) + { + if ($this->array_options[$key] != '') + { + $sql.=",'".$this->db->escape($this->array_options[$key])."'"; + } + else + { + $sql.=",null"; + } + } + } + $sql.=")"; + + dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG); + $resql = $this->db->query($sql); + if (! $resql) + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + else + { + $this->db->commit(); + return 1; + } + } + else return 0; + } + + /** + * Function to show lines of extrafields with output datas + * + * @param object $extrafields Extrafield Object + * @param string $mode Show output (view) or input (edit) for extrafield + * @param array $params Optionnal parameters + * @param string $keyprefix Prefix string to add into name and id of field (can be used to avoid duplicate names) + * + * @return string + */ + function showOptionals($extrafields, $mode='view', $params=0, $keyprefix='') + { + global $_POST, $conf; + + $out = ''; + + if (count($extrafields->attribute_label) > 0) + { + $out .= "\n"; + $out .= ' '; + $out .= "\n"; + + $e = 0; + foreach($extrafields->attribute_label as $key=>$label) + { + if (is_array($params) && count($params)>0) { + if (array_key_exists('colspan',$params)) { + $colspan=$params['colspan']; + } + }else { + $colspan='3'; + } + switch($mode) { + case "view": + $value=$this->array_options["options_".$key]; + break; + case "edit": + $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$this->array_options["options_".$key]); + break; + } + if ($extrafields->attribute_type[$key] == 'separate') + { + $out .= $extrafields->showSeparator($key); + } + else + { + $csstyle=''; + if (is_array($params) && count($params)>0) { + if (array_key_exists('style',$params)) { + $csstyle=$params['style']; + } + } + if ( !empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) + { + $out .= ''; + $colspan='0'; + } + else + { + $out .= ''; + } + // Convert date into timestamp format + if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) + { + $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$this->db->jdate($this->array_options['options_'.$key]); + } + + if($extrafields->attribute_required[$key]) + $label = ''.$label.''; + + $out .= ''; + $out .=''; + + switch($mode) { + case "view": + $out .= $extrafields->showOutputField($key,$value); + break; + case "edit": + $out .= $extrafields->showInputField($key,$value,'',$keyprefix); + break; + } + + $out .= ''."\n"; + + if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; + else $out .= ''; + $e++; + } + } + $out .= "\n"; + $out .= ' '; + $out .= ' + '; + } + return $out; + } + } diff --git a/htdocs/core/class/commonobjectline.class.php b/htdocs/core/class/commonobjectline.class.php index bb253d2eded..c3c8d823a34 100644 --- a/htdocs/core/class/commonobjectline.class.php +++ b/htdocs/core/class/commonobjectline.class.php @@ -26,8 +26,12 @@ * Parent class for class inheritance lines of business objects * This class is useless for the moment so no inherit are done on it */ -abstract class CommonObjectLine +abstract class CommonObjectLine extends CommonObject { + // TODO + // Currently we need function at end of file CommonObject for all object lines. Should find a way to avoid duplicate code. + + // For the moment we use the extends on CommonObject until PHP min is 5.4 so use Traits. } diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index b6225de2913..9127ed614b3 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -366,12 +366,25 @@ class Conf unset($this->global->CONTACT_USE_SEARCH_TO_SELECT); } + if (! empty($conf->productbatch->enabled)) + { + $this->global->STOCK_CALCULATE_ON_BILL=0; + $this->global->STOCK_CALCULATE_ON_VALIDATE_ORDER=0; + $this->global->STOCK_CALCULATE_ON_SHIPMENT=1; + $this->global->STOCK_CALCULATE_ON_SUPPLIER_BILL=0; + $this->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER=0; + $this->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER=1; + } + // conf->currency if (empty($this->global->MAIN_MONNAIE)) $this->global->MAIN_MONNAIE='EUR'; $this->currency=$this->global->MAIN_MONNAIE; - // conf->global->COMPTA_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...) - if (empty($this->global->COMPTA_MODE)) $this->global->COMPTA_MODE='RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' + // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...) + if (empty($this->global->ACCOUNTING_MODE)) $this->global->ACCOUNTING_MODE='RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES' + + // By default, suppliers objects can be linked to all projects + $conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1; // conf->liste_limit = constante de taille maximale des listes if (empty($this->global->MAIN_SIZE_LISTE_LIMIT)) $this->global->MAIN_SIZE_LISTE_LIMIT=25; diff --git a/htdocs/core/class/ctypent.class.php b/htdocs/core/class/ctypent.class.php index 33070f83412..027dda53dd3 100644 --- a/htdocs/core/class/ctypent.class.php +++ b/htdocs/core/class/ctypent.class.php @@ -102,7 +102,7 @@ class Ctypent // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -156,14 +156,15 @@ class Ctypent // extends CommonObject $sql = "SELECT"; $sql.= " t.id,"; $sql.= " t.code,"; - $sql.= " t.libelle,"; + $sql.= " t.libelle as label,"; + $sql.= " t.fk_country as country_id,"; $sql.= " t.active,"; $sql.= " t.module"; $sql.= " FROM ".MAIN_DB_PREFIX."c_typent as t"; if ($id) $sql.= " WHERE t.id = ".$id; elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -173,7 +174,8 @@ class Ctypent // extends CommonObject $this->id = $obj->id; $this->code = $obj->code; - $this->libelle = $obj->libelle; + $this->libelle = $obj->label; + $this->country_id = $obj->country_id; $this->active = $obj->active; $this->module = $obj->module; } @@ -184,7 +186,6 @@ class Ctypent // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -197,7 +198,7 @@ class Ctypent // extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -222,7 +223,7 @@ class Ctypent // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -278,7 +279,7 @@ class Ctypent // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index 23ce9f97f6d..f0291c9d567 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -85,7 +85,7 @@ class DiscountAbsolute if ($rowid) $sql.= " sr.rowid=".$rowid; if ($fk_facture_source) $sql.= " sr.fk_facture_source=".$fk_facture_source; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -159,7 +159,7 @@ class DiscountAbsolute $sql.= " ".($this->fk_facture_source?"'".$this->fk_facture_source."'":"null"); $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -169,7 +169,6 @@ class DiscountAbsolute else { $this->error=$this->db->lasterror().' - sql='.$sql; - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } } @@ -195,7 +194,7 @@ class DiscountAbsolute $sql.=" AND fk_facture_source = ".$this->fk_facture_source; //$sql.=" AND rowid != ".$this->id; - dol_syslog(get_class($this)."::delete Check if we can remove discount sql=".$sql); + dol_syslog(get_class($this)."::delete Check if we can remove discount", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -222,7 +221,7 @@ class DiscountAbsolute $sql.= " AND (fk_facture_line IS NULL"; // Not used as absolute simple discount $sql.= " AND fk_facture IS NULL)"; // Not used as credit note and not used as deposit - dol_syslog(get_class($this)."::delete Delete discount sql=".$sql); + dol_syslog(get_class($this)."::delete Delete discount", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -233,7 +232,7 @@ class DiscountAbsolute $sql.=" set paye=0, fk_statut=1"; $sql.=" WHERE (type = 2 or type = 3) AND rowid=".$this->fk_facture_source; - dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut sql=".$sql); + dol_syslog(get_class($this)."::delete Update credit note or deposit invoice statut", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -291,7 +290,7 @@ class DiscountAbsolute if ($rowidinvoice) $sql.=" SET fk_facture = ".$rowidinvoice; $sql.=" WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::link_to_invoice sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::link_to_invoice", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -302,7 +301,6 @@ class DiscountAbsolute else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::link_to_invoice ".$this->error,LOG_ERR); return -3; } } @@ -320,7 +318,7 @@ class DiscountAbsolute $sql.=" SET fk_facture_line = NULL, fk_facture = NULL"; $sql.=" WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::unlink_invoice sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::unlink_invoice", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -329,7 +327,6 @@ class DiscountAbsolute else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::unlink_invoice ".$this->error,LOG_ERR); return -3; } } @@ -355,7 +352,7 @@ class DiscountAbsolute if ($filter) $sql.=' AND ('.$filter.')'; if ($maxvalue) $sql.=' AND rc.amount_ttc <= '.price2num($maxvalue); - dol_syslog(get_class($this)."::getAvailableDiscounts sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::getAvailableDiscounts", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -384,7 +381,7 @@ class DiscountAbsolute $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; $sql.= ' AND f.type = 2'; - dol_syslog(get_class($this)."::getSumCreditNotesUsed sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::getSumCreditNotesUsed", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -410,7 +407,7 @@ class DiscountAbsolute $sql.= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.$invoice->id; $sql.= ' AND f.type = 3'; - dol_syslog(get_class($this)."::getSumDepositsUsed sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::getSumDepositsUsed", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 33888b057b7..c400dc151d3 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -253,7 +253,7 @@ class DolGraph /** * Set legend * - * @param string $legend Legend + * @param array $legend Legend. Example: array('seriename1','seriname2',...) * @return void */ function SetLegend($legend) diff --git a/htdocs/core/class/dolprintipp.class.php b/htdocs/core/class/dolprintipp.class.php index 942ee3da3c3..71ee2a1be37 100644 --- a/htdocs/core/class/dolprintipp.class.php +++ b/htdocs/core/class/dolprintipp.class.php @@ -83,19 +83,22 @@ class dolprintIPP * @param string $file file * @param string $module module * - * @return void + * @return string '' if OK, Error message if KO */ - function print_file($file,$module) + function print_file($file, $module) { global $conf,$db; + include_once DOL_DOCUMENT_ROOT.'/includes/printipp/CupsPrintIPP.php'; + $ipp = new CupsPrintIPP(); - $ipp->setLog(DOL_DATA_ROOT.'/printipp.log','file',3); // logging very verbose + $ipp->setLog(DOL_DATA_ROOT.'/dolibarr_printipp.log','file',3); // logging very verbose $ipp->setHost($this->host); $ipp->setPort($this->port); $ipp->setJobName($file,true); $ipp->setUserName($this->userid); if (! empty($this->user)) $ipp->setAuthentication($this->user,$this->password); + // select printer uri for module order, propal,... $sql = 'SELECT rowid,printer_uri,copy FROM '.MAIN_DB_PREFIX.'printer_ipp WHERE module="'.$module.'"'; $result = $this->db->query($sql); @@ -108,13 +111,23 @@ class dolprintIPP } else { - $ipp->setPrinterURI($conf->global->PRINTIPP_URI_DEFAULT); + if (! empty($conf->global->PRINTIPP_URI_DEFAULT)) + { + $ipp->setPrinterURI($conf->global->PRINTIPP_URI_DEFAULT); + } + else + { + return 'NoDefaultPrinterDefined'; + } } } + // Set number of copy $ipp->setCopies($obj->copy); $ipp->setData(DOL_DATA_ROOT.'/'.$module.'/'.$file); $ipp->printJob(); + + return ''; } /** diff --git a/htdocs/core/class/events.class.php b/htdocs/core/class/events.class.php index b344a0c4059..299026a84bb 100644 --- a/htdocs/core/class/events.class.php +++ b/htdocs/core/class/events.class.php @@ -111,7 +111,7 @@ class Events // extends CommonObject $this->description=trim($this->description); // Check parameters - if (! $this->description) { $this->error='ErrorBadValueForParameter'; return -1; } + if (empty($this->description)) { $this->error='ErrorBadValueForParameter'; return -1; } // Insert request $sql = "INSERT INTO ".MAIN_DB_PREFIX."events("; @@ -129,10 +129,10 @@ class Events // extends CommonObject $sql.= " ".($_SERVER['HTTP_USER_AGENT']?"'".dol_trunc($_SERVER['HTTP_USER_AGENT'],250)."'":'NULL').","; $sql.= " '".$this->db->idate($this->dateevent)."',"; $sql.= " ".($user->id?"'".$user->id."'":'NULL').","; - $sql.= " '".$this->db->escape($this->description)."'"; + $sql.= " '".$this->db->escape(dol_trunc($this->description,250))."'"; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -142,7 +142,6 @@ class Events // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; } } @@ -155,7 +154,7 @@ class Events // extends CommonObject * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -174,12 +173,11 @@ class Events // extends CommonObject $sql.= " description='".$this->db->escape($this->description)."'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR); return -1; } return 1; @@ -193,7 +191,7 @@ class Events // extends CommonObject * @param User $user User that load * @return int <0 if KO, >0 if OK */ - function fetch($id, $user=0) + function fetch($id, $user=null) { global $langs; @@ -209,7 +207,7 @@ class Events // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."events as t"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -233,7 +231,6 @@ class Events // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -252,12 +249,11 @@ class Events // extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."events"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -1; } diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 8ce0a1b3b45..30c97e9f1ef 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -50,11 +50,13 @@ class ExtraFields var $attribute_param; // Int to store position of attribute var $attribute_pos; + // Int to store if attribute is editable regardless of the document status + var $attribute_alwayseditable; var $error; var $errno; - static $type2label=array( + public static $type2label=array( 'varchar'=>'String', 'text'=>'TextLong', 'int'=>'Int', @@ -103,9 +105,10 @@ class ExtraFields * @param int $required Is field required or not * @param string $default_value Defaulted value * @param array $param Params for field + * @param int $alwayseditable Is attribute always editable regardless of the document status * @return int <=0 if KO, >0 if OK */ - function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0,$default_value='', $param=0) + function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param=0, $alwayseditable=0) { if (empty($attrname)) return -1; if (empty($label)) return -1; @@ -119,7 +122,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); + $result2=$this->create_label($attrname,$label,$type,$pos,$size,$elementtype, $unique, $required, $param, $alwayseditable); $err2=$this->errno; if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) { @@ -217,9 +220,10 @@ class ExtraFields * @param int $unique Is field unique or not * @param int $required Is field required or not * @param array||string $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param int $alwayseditable Is attribute always editable regardless of the document status * @return int <=0 if KO, >0 if OK */ - private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='') + private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0) { global $conf; @@ -241,7 +245,7 @@ class ExtraFields $params=''; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(name, label, type, pos, size, entity, elementtype, fieldunique, fieldrequired, param)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(name, label, type, pos, size, entity, elementtype, fieldunique, fieldrequired, param, alwayseditable)"; $sql.= " VALUES('".$attrname."',"; $sql.= " '".$this->db->escape($label)."',"; $sql.= " '".$type."',"; @@ -251,10 +255,11 @@ class ExtraFields $sql.= " '".$elementtype."',"; $sql.= " '".$unique."',"; $sql.= " '".$required."',"; - $sql.= " '".$params."'"; + $sql.= " '".$params."',"; + $sql.= " '".$alwayseditable."'"; $sql.=')'; - dol_syslog(get_class($this)."::create_label sql=".$sql); + dol_syslog(get_class($this)."::create_label", LOG_DEBUG); if ($this->db->query($sql)) { return 1; @@ -285,7 +290,6 @@ class ExtraFields if ($result < 0) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); } $result=$this->delete_label($attrname,$elementtype); @@ -317,7 +321,7 @@ class ExtraFields $sql.= " AND entity IN (0,".$conf->entity.')'; $sql.= " AND elementtype = '".$elementtype."'"; - dol_syslog(get_class($this)."::delete_label sql=".$sql); + dol_syslog(get_class($this)."::delete_label", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -348,9 +352,10 @@ class ExtraFields * @param int $required Is field required or not * @param int $pos Position of attribute * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param int $alwayseditable Is attribute always editable regardless of the document status * @return int >0 if OK, <=0 if KO */ - function update($attrname,$label,$type,$length,$elementtype,$unique=0,$required=0,$pos=0,$param='') + function update($attrname,$label,$type,$length,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0) { $table=$elementtype.'_extrafields'; @@ -385,7 +390,7 @@ class ExtraFields { if ($label) { - $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param); + $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable); } if ($result > 0) { @@ -398,7 +403,7 @@ class ExtraFields { $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname; } - dol_syslog(get_class($this).'::update sql='.$sql); + dol_syslog(get_class($this).'::update', LOG_DEBUG); $resql=$this->db->query($sql,1,'dml'); return 1; } @@ -433,9 +438,10 @@ class ExtraFields * @param int $required Is field required or not * @param int $pos Position of attribute * @param array $param Params for field (ex for select list : array('options' => array(value'=>'label of option')) ) + * @param int $alwayseditable Is attribute always editable regardless of the document status * @return int <=0 if KO, >0 if OK */ - private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='') + private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0) { global $conf; dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required); @@ -453,7 +459,7 @@ class ExtraFields $sql_del.= " WHERE name = '".$attrname."'"; $sql_del.= " AND entity = ".$conf->entity; $sql_del.= " AND elementtype = '".$elementtype."'"; - dol_syslog(get_class($this)."::update_label sql=".$sql_del); + dol_syslog(get_class($this)."::update_label", LOG_DEBUG); $resql1=$this->db->query($sql_del); $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields("; @@ -466,6 +472,7 @@ class ExtraFields $sql.= " fieldunique,"; $sql.= " fieldrequired,"; $sql.= " pos,"; + $sql.= " alwayseditable,"; $sql.= " param"; $sql.= ") VALUES ("; $sql.= "'".$attrname."',"; @@ -477,9 +484,10 @@ class ExtraFields $sql.= " '".$unique."',"; $sql.= " '".$required."',"; $sql.= " '".$pos."',"; + $sql.= " '".$alwayseditable."',"; $sql.= " '".$param."'"; $sql.= ")"; - dol_syslog(get_class($this)."::update_label sql=".$sql); + dol_syslog(get_class($this)."::update_label", LOG_DEBUG); $resql2=$this->db->query($sql); if ($resql1 && $resql2) @@ -503,40 +511,28 @@ class ExtraFields /** - * Load array of labels - * - * @return void - */ - function fetch_optionals() - { - $this->fetch_name_optionals_label(); - } - - - /** - * Load array this->attribute_label + * Load array this->attribute_xxx like attribute_label, attribute_type, ... * * @param string $elementtype Type of element ('adherent', 'commande', societe', 'facture', 'propal', 'product', ...) * @param boolean $forceload Force load of extra fields whatever is option MAIN_EXTRAFIELDS_DISABLED * @return array Array of attributes for all extra fields */ - function fetch_name_optionals_label($elementtype='adherent',$forceload=false) + function fetch_name_optionals_label($elementtype,$forceload=false) { global $conf; $array_name_label=array(); // For avoid conflicts with external modules - if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) - return $array_name_label; + if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label; - $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable"; $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; $sql.= " WHERE entity IN (0,".$conf->entity.")"; if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'"; $sql.= " ORDER BY pos"; - dol_syslog(get_class($this)."::fetch_name_optionals_label sql=".$sql); + dol_syslog(get_class($this)."::fetch_name_optionals_label", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -558,15 +554,16 @@ class ExtraFields $this->attribute_required[$tab->name]=$tab->fieldrequired; $this->attribute_param[$tab->name]=unserialize($tab->param); $this->attribute_pos[$tab->name]=$tab->pos; + $this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable; } } - - return $array_name_label; } else { print dol_print_error($this->db); } + + return $array_name_label; } @@ -673,7 +670,7 @@ class ExtraFields elseif ($type == 'select') { $out = ''; - if ($conf->use_javascript_ajax && $conf->global->COMPANY_USE_SEARCH_TO_SELECT && ! $forcecombo) + if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo) { include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php'; $out.= ajax_combobox('options_'.$key.$keyprefix, array(), $conf->global->COMPANY_USE_SEARCH_TO_SELECT); @@ -756,7 +753,7 @@ class ExtraFields //$sql.=preg_replace('/^ AND /','',$sqlwhere); //print $sql; - dol_syslog(get_class($this).'::showInputField type=sellist sql='.$sql); + dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -966,7 +963,7 @@ class ExtraFields $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'"; //$sql.= ' AND entity = '.$conf->entity; - dol_syslog(get_class($this).':showOutputField:$type=sellist sql='.$sql); + dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/core/class/fiscalyear.class.php b/htdocs/core/class/fiscalyear.class.php new file mode 100644 index 00000000000..1abde51c263 --- /dev/null +++ b/htdocs/core/class/fiscalyear.class.php @@ -0,0 +1,327 @@ + + * + * 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/fiscalyear.php + * \ingroup fiscal year + * \brief File of class to manage fiscal years + */ + +require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; + +/** + * Class to manage fiscal year + */ +class Fiscalyear +{ + public $element='fiscalyear'; + public $table_element='accounting_fiscalyear'; + public $table_element_line = ''; + public $fk_element = ''; + protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + + var $id; + var $rowid; + + var $label; + var $date_start; + var $date_end; + var $statut; // 0=open, 1=closed + var $entity; + + var $statuts=array(); + var $statuts_short=array(); + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + function __construct($db) + { + $this->db = $db; + + $this->statuts_short = array(0 => 'Opened', 1 => 'Closed'); + $this->statuts = array(0 => 'Opened', 1 => 'Closed'); + + return 1; + } + + /** + * Create object in database + * + * @param User $user User making creation + * @return int <0 if KO, >0 if OK + */ + function create($user) + { + global $conf; + + $error = 0; + + $now=dol_now(); + + $this->db->begin(); + + $sql = "INSERT INTO ".MAIN_DB_PREFIX."accounting_fiscalyear ("; + $sql.= "label"; + $sql.= ", date_start"; + $sql.= ", date_end"; + $sql.= ", statut"; + $sql.= ", entity"; + $sql.= ", datec"; + $sql.= ", fk_user_author"; + $sql.= ") VALUES ("; + $sql.= " '".$this->label."'"; + $sql.= ", '".$this->db->idate($this->date_start)."'"; + $sql.= ", ".($this->date_end ? "'".$this->db->idate($this->date_end)."'":"null"); + $sql.= ", ".$this->statut; + $sql.= ", ".$conf->entity; + $sql.= ", '".$this->db->idate($now)."'"; + $sql.= ", ". $user->id; + $sql.= ")"; + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."accounting_fiscalyear"); + + $result=$this->update($user); + if ($result > 0) + { + $this->db->commit(); + return $this->id; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return $result; + } + } + else + { + $this->error=$this->db->lasterror()." sql=".$sql; + $this->db->rollback(); + return -1; + } + } + + /** + * Update record + * + * @param User $user User making update + * @return int <0 if KO, >0 if OK + */ + function update($user) + { + global $langs; + + // Check parameters + if (empty($this->date_start) && empty($this->date_end)) + { + $this->error='ErrorBadParameter'; + return -1; + } + + $this->db->begin(); + + $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_fiscalyear"; + $sql .= " SET label = '".$this->label."'"; + $sql .= ", date_start = '".$this->db->idate($this->date_start)."'"; + $sql .= ", date_end = ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null"); + $sql .= ", statut = '".$this->statut."'"; + $sql .= ", datec = " . ($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null'); + $sql .= ", fk_user_modif = " . $user->id; + $sql .= " WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + dol_syslog($this->error, LOG_ERR); + $this->db->rollback(); + return -1; + } + } + + /** + * Load an object from database + * + * @param int $id Id of record to load + * @return int <0 if KO, >0 if OK + */ + function fetch($id) + { + $sql = "SELECT rowid, label, date_start, date_end, statut"; + $sql.= " FROM ".MAIN_DB_PREFIX."accounting_fiscalyear"; + $sql.= " WHERE rowid = ".$id; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $result = $this->db->query($sql); + if ( $result ) + { + $obj = $this->db->fetch_object($result); + + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + $this->date_start = $this->db->jdate($obj->date_start); + $this->date_end = $this->db->jdate($obj->date_end); + $this->label = $obj->label; + $this->statut = $obj->statut; + + return 1; + } + else + { + $this->error=$this->db->lasterror(); + return -1; + } + } + + /** + * Delete record + * + * @param int $id Id of record to delete + * @return int <0 if KO, >0 if OK + */ + function delete($id) + { + $this->db->begin(); + + $sql = "DELETE FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE rowid = ".$id; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + $this->db->commit(); + return 1; + } + else + { + $this->error=$this->db->lasterror(); + $this->db->rollback(); + return -1; + } + } + + /** + * Give a label from a status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->statut,$mode); + } + + /** + * Give a label from a status + * + * @param int $statut Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto + * @return string Label + */ + function LibStatut($statut,$mode=0) + { + global $langs; + + if ($mode == 0) + { + return $langs->trans($this->statuts[$statut]); + } + if ($mode == 1) + { + return $langs->trans($this->statuts_short[$statut]); + } + if ($mode == 2) + { + if ($statut==0) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts_short[$statut]); + if ($statut==1) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts_short[$statut]); + } + if ($mode == 3) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4'); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8'); + } + if ($mode == 4) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut4').' '.$langs->trans($this->statuts[$statut]); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return img_picto($langs->trans($this->statuts_short[$statut]),'statut8').' '.$langs->trans($this->statuts[$statut]); + } + if ($mode == 5) + { + if ($statut==0 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut4'); + if ($statut==1 && ! empty($this->statuts_short[$statut])) return $langs->trans($this->statuts_short[$statut]).' '.img_picto($langs->trans($this->statuts_short[$statut]),'statut8'); + } + } + + /** + * Information on record + * + * @param int $id Id of record + * @return void + */ + function info($id) + { + $sql = 'SELECT fy.rowid, fy.datec, fy.fk_user_author, fy.fk_user_modif,'; + $sql.= ' fy.tms'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'accounting_fiscalyear as fy'; + $sql.= ' WHERE fy.rowid = '.$id; + + dol_syslog(get_class($this)."::fetch info", LOG_DEBUG); + $result = $this->db->query($sql); + + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $this->id = $obj->rowid; + if ($obj->fk_user_author) + { + $cuser = new User($this->db); + $cuser->fetch($obj->fk_user_author); + $this->user_creation = $cuser; + } + if ($obj->fk_user_modif) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modif); + $this->user_modification = $muser; + } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->tms); + } + $this->db->free($result); + } + else + { + dol_print_error($this->db); + } + } + +} \ No newline at end of file diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php index 906c1e6c4ae..d1fc6e4662d 100644 --- a/htdocs/core/class/hookmanager.class.php +++ b/htdocs/core/class/hookmanager.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2010-2012 Regis Houssin + * Copyright (C) 2010-2014 Regis Houssin * Copyright (C) 2010-2011 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -114,8 +114,8 @@ class HookManager * * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...) * @param array $parameters Array of parameters - * @param Object $object Object to use hooks on - * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) + * @param Object $object Object to use hooks on + * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) * @return mixed For doActions,formObjectOptions,pdf_xxx: Return 0 if we want to keep standard actions, >0 if if want to stop standard actions, <0 means KO. * For printSearchForm,printLeftBlock,printTopRightMenu,formAddObjectLine,...: Return HTML string. TODO Deprecated. Must always return an int and things to print into ->resprints. * Can also return some values into an array ->results. @@ -145,7 +145,8 @@ class HookManager 'moveUploadedFile', 'pdf_writelinedesc', 'paymentsupplierinvoices', - 'printSearchForm' + 'printSearchForm', + 'formatEvent' ) )) $hooktype='addreplace'; @@ -153,7 +154,7 @@ class HookManager $modulealreadyexecuted=array(); $resaction=0; $error=0; $result=''; $this->resPrint=''; $this->resArray=array(); - foreach($this->hooks as $modules) // this->hooks is an array with context as key and value is an array of modules that handle this context + foreach($this->hooks as $context => $modules) // this->hooks is an array with context as key and value is an array of modules that handle this context { if (! empty($modules)) { @@ -161,27 +162,29 @@ class HookManager { //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction." result=".$result."
\n"; - //print 'class='.get_class($actionclassinstance).' method='.$method.' action='.$action; - // jump to next class if method does not exists + // jump to next module/class if method does not exists if (! method_exists($actionclassinstance,$method)) continue; - // test to avoid to run twice a hook, when a module implements several active contexts + + // test to avoid to run twice a hook, when a module implements several active contexts if (in_array($module,$modulealreadyexecuted)) continue; - $modulealreadyexecuted[$module]=$module; + $modulealreadyexecuted[$module]=$module; // Use the $currentcontext in method for avoid to run twice + + // Clean class (an error may have been set into a previous call of another method for same module/hook) + $actionclassinstance->error=0; + $actionclassinstance->errors=array(); + + // Add current context for avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return; + $parameters['currentcontext'] = $context; // Hooks that must return int (hooks with type 'addreplace') if ($hooktype == 'addreplace') { + dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); $resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) if ($resaction < 0 || ! empty($actionclassinstance->error) || (! empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) { $error++; $this->error=$actionclassinstance->error; $this->errors=array_merge($this->errors, (array) $actionclassinstance->errors); - // TODO dead code to remove (do not enable this, but fix hook instead) - /* Change must be inside the method of hook if required. Only hook must decide if $action must be modified or not. - if ($method == 'doActions') - { - if ($action=='add') $action='create'; - if ($action=='update') $action='edit'; - }*/ + dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error)?'':" ".$this->error).(empty($this->errors)?'':" ".join(",",$this->errors)), LOG_ERR); } if (is_array($actionclassinstance->results)) $this->resArray =array_merge($this->resArray, $actionclassinstance->results); @@ -193,6 +196,7 @@ class HookManager // TODO. this should be done into the method of hook by returning nothing if (is_array($parameters) && ! empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue; + //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); $result = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) if (! empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray =array_merge($this->resArray, $actionclassinstance->results); diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index ee28ec6a495..eec9318f9ba 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4,7 +4,7 @@ * Copyright (C) 2004 Benoit Mortier * Copyright (C) 2004 Sebastien Di Cintio * Copyright (C) 2004 Eric Seigne - * Copyright (C) 2005-2013 Regis Houssin + * Copyright (C) 2005-2014 Regis Houssin * Copyright (C) 2006 Andre Cianfarani * Copyright (C) 2006 Marc Barilley/Ocebo * Copyright (C) 2007 Franky Van Liedekerke @@ -14,6 +14,7 @@ * Copyright (C) 2011 Herve Prot * Copyright (C) 2012 Marcos García * Copyright (C) 2013 Raphaël Doursenaud + * Copyright (C) 2014 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -124,11 +125,11 @@ class Form * @param string $typeofdata Type of data ('string' by default, 'amount', 'email', 'numeric:99', 'text' or 'textarea:rows:cols', 'day' or 'datepicker', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...) * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value * @param object $extObject External object - * @param string $success Success message + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') * @param string $moreparam More param to add on a href URL * @return string HTML edit field */ - function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $success=null, $moreparam='') + function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='') { global $conf,$langs,$db; @@ -140,7 +141,7 @@ class Form // When option to edit inline is activated if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker { - $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $success); + $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg); } else { @@ -193,7 +194,7 @@ class Form { $ret.='
'; } @@ -244,10 +245,10 @@ class Form * @param string $inputType Type of input ('numeric', 'datepicker', 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx') * @param string $editvalue When in edit mode, use this value as $value instead of value * @param object $extObject External object - * @param string $success Success message + * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage') * @return string HTML edit in place */ - private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $success=null) + private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null) { global $conf; @@ -334,7 +335,18 @@ class Form $out.= ''."\n"; if (! empty($savemethod)) $out.= ''."\n"; if (! empty($ext_element)) $out.= ''."\n"; - if (! empty($success)) $out.= ''."\n"; + if (! empty($custommsg)) + { + if (is_array($custommsg)) + { + if (!empty($custommsg['success'])) + $out.= ''."\n"; + if (!empty($custommsg['error'])) + $out.= ''."\n"; + } + else + $out.= ''."\n"; + } if ($inputType == 'textarea') { $out.= ''."\n"; $out.= ''."\n"; @@ -449,19 +461,6 @@ class Form return $this->textwithtooltip($text, $htmltext, 2, $direction, $img, $extracss, $notabs, '', $noencodehtmltext); } - /** - * Return combo list of activated countries, into language of user - * - * @param string $selected Id or Code or Label of preselected country - * @param string $htmlname Name of html select object - * @param string $htmloption Options html on select object - * @return void - */ - function select_pays($selected='',$htmlname='country_id',$htmloption='') - { - print $this->select_country($selected,$htmlname,$htmloption); - } - /** * Return combo list of activated countries, into language of user * @@ -479,18 +478,20 @@ class Form $out=''; $countryArray=array(); + $favorite=array(); $label=array(); + $atleastonefavorite=0; - $sql = "SELECT rowid, code as code_iso, libelle as label"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_pays"; + $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_country"; $sql.= " WHERE active = 1"; //$sql.= " ORDER BY code ASC"; - dol_syslog(get_class($this)."::select_country sql=".$sql); + dol_syslog(get_class($this)."::select_country", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { - $out.= ''; $num = $this->db->num_rows($resql); $i = 0; if ($num) @@ -502,17 +503,25 @@ class Form $obj = $this->db->fetch_object($resql); $countryArray[$i]['rowid'] = $obj->rowid; $countryArray[$i]['code_iso'] = $obj->code_iso; + $countryArray[$i]['code_iso3'] = $obj->code_iso3; $countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:'')); - $label[$i] = dol_string_unaccent($countryArray[$i]['label']); + $countryArray[$i]['favorite'] = $obj->favorite; + $favorite[$i] = $obj->favorite; + $label[$i] = dol_string_unaccent($countryArray[$i]['label']); $i++; } - array_multisort($label, SORT_ASC, $countryArray); + array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray); foreach ($countryArray as $row) { - //print 'rr'.$selected.'-'.$row['label'].'-'.$row['code_iso'].'
'; - if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['label']) ) + if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++; + if (empty($row['favorite']) && $atleastonefavorite) + { + $atleastonefavorite=0; + $out.= ''; + } + if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) ) { $foundselected=true; $out.= '
'.$langs->trans('Margins').''.$langs->trans('SellingPrice').''.$langs->trans('Margins').''.$langs->trans('SellingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('Margin').''.$langs->trans('CostPrice').''.$langs->trans('Margin').''.$langs->trans('MarginRate').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').''.$langs->trans('MarkRate').'
'.$label.'
'; $ret.=''; - $ret.='
'."\n"; + if (preg_match('/ckeditor|textarea/',$typeofdata)) $ret.='
'."\n"; $ret.=''; $ret.='
'; + print ''; + print ''; + print '
'; + $this->selectShippingMethod($selected, $htmlname, '', $addempty); + print '
'; + } else { + if ($selected) { + $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code'); + print $langs->trans("SendingMethod".strtoupper($code)); + } else { + print " "; + } + } + } + /** * Return a HTML select list of bank accounts * @@ -2437,7 +2692,7 @@ class Form if ($filtre) $sql.=" AND ".$filtre; $sql.= " ORDER BY label"; - dol_syslog(get_class($this)."::select_comptes sql=".$sql); + dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -2479,6 +2734,40 @@ class Form } } + /** + * Display form to select bank account + * + * @param string $page Page + * @param int $selected Id of bank account + * @param string $htmlname Name of select html field + * @param int $addempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @return void + */ + function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0) + { + global $langs; + if ($htmlname != "none") { + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + $this->select_comptes($selected, $htmlname, 0, '', $addempty); + print '
'; + } else { + if ($selected) { + require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php'; + $bankstatic=new Account($this->db); + $bankstatic->fetch($selected); + print $this->textwithpicto($bankstatic->label,$langs->trans("AccountCurrency").' '.$bankstatic->currency_code); + } else { + print " "; + } + } + } + /** * Return list of categories having choosed type * @@ -2488,6 +2777,7 @@ class Form * @param int $maxlength Maximum length for labels * @param int $excludeafterid Exclude all categories after this leaf in category tree. * @return void + * @see select_categories */ function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0) { @@ -2611,8 +2901,8 @@ class Form } else if ($input['type'] == 'select') { - $more.=''; - if (! empty($input['label'])) $more.=$input['label'].''; + $more.=''; + if (! empty($input['label'])) $more.=$input['label'].''; $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1); $more.=''."\n"; } @@ -2659,7 +2949,7 @@ class Form // JQUI method dialog is broken with jmobile, we use standard HTML. // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx - // See page product/fiche.php for example + // See page product/card.php for example if (! empty($conf->dol_use_jmobile)) $useajax=0; if (empty($conf->use_javascript_ajax)) $useajax=0; @@ -2808,13 +3098,14 @@ class Form /** * Show a form to select a project * - * @param int $page Page - * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) - * @param int $selected Id pre-selected project - * @param string $htmlname Name of select field + * @param int $page Page + * @param int $socid Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id) + * @param int $selected Id pre-selected project + * @param string $htmlname Name of select field + * @param int $discard_closed Hide all closed projects * @return void */ - function form_project($page, $socid, $selected='', $htmlname='projectid') + function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0) { global $langs; @@ -2831,8 +3122,7 @@ class Form print ''; print ''; print ''; print ''; print '
'; - //print "$socid,$selected,$htmlname"; - $formproject->select_projects($socid,$selected,$htmlname); + $formproject->select_projects($socid,$selected,$htmlname,20,0,1,$discard_closed); print '
'; @@ -2843,7 +3133,7 @@ class Form { $projet = new Project($this->db); $projet->fetch($selected); - //print ''.$projet->title.''; + //print ''.$projet->title.''; print $projet->getNomUrl(0,'',1); } else @@ -2859,7 +3149,7 @@ class Form * @param int $page Page * @param string $selected Id condition pre-selectionne * @param string $htmlname Name of select html field - * @param int $addempty Ajoute entree vide + * @param int $addempty Add empty entry * @return void */ function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0) @@ -3160,7 +3450,7 @@ class Form * @param string $htmlname Nom du formulaire select * @return void */ - function form_contacts($page, $societe, $selected='', $htmlname='contactidp') + function form_contacts($page, $societe, $selected='', $htmlname='contactid') { global $langs, $conf; @@ -3176,7 +3466,7 @@ class Form { $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress")); print 'Cette societe n\'a pas de contact, veuillez en cr�er un avant de faire votre proposition commerciale
'; - print ''.$addcontact.''; + print ''.$addcontact.''; } print ''; print ''; @@ -3272,7 +3562,7 @@ class Form if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite - $out.= ''; foreach ($langs->cache_currencies as $code_iso => $currency) { if ($selected && $selected == $code_iso) @@ -3307,10 +3597,10 @@ class Form if ($num > 0) return $num; // Cache deja charge $sql = "SELECT DISTINCT t.taux, t.recuperableonly"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_pays as p"; - $sql.= " WHERE t.fk_pays = p.rowid"; + $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql.= " WHERE t.fk_pays = c.rowid"; $sql.= " AND t.active = 1"; - $sql.= " AND p.code IN (".$country_code.")"; + $sql.= " AND c.code IN (".$country_code.")"; $sql.= " ORDER BY t.taux ASC, t.recuperableonly ASC"; $resql=$this->db->query($sql); @@ -3394,14 +3684,14 @@ class Form //exit; // Define list of countries to use to search VAT rates to show - // First we defined code_pays to use to find list + // First we defined code_country to use to find list if (is_object($societe_vendeuse)) { - $code_pays="'".$societe_vendeuse->country_code."'"; + $code_country="'".$societe_vendeuse->country_code."'"; } else { - $code_pays="'".$mysoc->country_code."'"; // Pour compatibilite ascendente + $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente } if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on { @@ -3412,12 +3702,12 @@ class Form { if ($type == 1) // We know product is a service { - $code_pays.=",'".$societe_acheteuse->country_code."'"; + $code_country.=",'".$societe_acheteuse->country_code."'"; } } else if (! $idprod) // We don't know type of product { - $code_pays.=",'".$societe_acheteuse->country_code."'"; + $code_country.=",'".$societe_acheteuse->country_code."'"; } else { @@ -3425,14 +3715,14 @@ class Form $prodstatic->fetch($idprod); if ($prodstatic->type == 1) // We know product is a service { - $code_pays.=",'".$societe_acheteuse->country_code."'"; + $code_country.=",'".$societe_acheteuse->country_code."'"; } } } } // Now we get list - $num = $this->load_cache_vatrates($code_pays); + $num = $this->load_cache_vatrates($code_country); if ($num > 0) { // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '') @@ -3772,7 +4062,7 @@ class Form { print ''; } - print $langs->trans('Hours'); + print ' '.$langs->trans('HourShort'); if ($minunderhours) print '
'; else print " "; @@ -3785,38 +4075,57 @@ class Form print '>'.$min.''; } print ""; - print $langs->trans('Minutes'). " "; + print ' '.$langs->trans('MinuteShort'). " "; } /** * Return a HTML select string, built from an array of key+value. + * Note: Do not use returned string into a langs->trans function, content may be entity encoded twice. * * @param string $htmlname Name of html select area * @param array $array Array with key+value * @param string $id Preselected key - * @param int $show_empty 1 si il faut ajouter une valeur vide dans la liste, 0 sinon + * @param int $show_empty 0 no empty value allowed, 1 to add an empty value into list (value is '' or ' '). * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value" * @param int $value_as_key 1 to use value as key - * @param string $option Valeur de l'option en fonction du type choisi + * @param string $moreparam Add more parameters onto the select tag * @param int $translate Translate and encode value * @param int $maxlen Length maximum for labels * @param int $disabled Html select box is disabled - * @param int $sort 'ASC' or 'DESC' =Sort on label, '' or 'NONE'=Do not sort + * @param int $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' = Do not sort * @param string $morecss Add more class to css styles - * @return string HTML select string + * @return string HTML select string. + * @see multiselectarray */ - static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $option='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='') + static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='') { - global $langs; + global $conf, $langs; if ($value_as_key) $array=array_combine($array, $array); - $out=''; if ($show_empty) { - $out.=''."\n"; + $textforempty=' '; + if (! empty($conf->use_javascript_ajax)) $textforempty=' '; // If we use ajaxcombo, we need   here to avoid to have an empty element that is too small. + $out.=''."\n"; } if (is_array($array)) @@ -3839,11 +4148,11 @@ class Form if ($key_in_label) { - $selectOptionValue = dol_htmlentitiesbr($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value)); + $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value)); } else { - $selectOptionValue = dol_htmlentitiesbr($maxlen?dol_trunc($value,$maxlen):$value); + $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value); if ($value == '' || $value == '-') $selectOptionValue=' '; } $out.=$selectOptionValue; @@ -3860,54 +4169,41 @@ class Form * * @param string $htmlname Name of select * @param array $array Array with key+value - * @param array $selected Preselected keys + * @param array $selected Array with key+value preselected * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value" * @param int $value_as_key 1 to use value as key * @param string $option Valeur de l'option en fonction du type choisi * @param int $translate Translate and encode value + * @param int $width Force width of select box. May be used only when using jquery couch. * @return string HTML multiselect string + * @see selectarray */ - function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $option='', $translate=0) + static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $option='', $translate=0, $width=0) { global $conf, $langs; - $out = ''."\n"; if (is_array($array) && ! empty($array)) { if ($value_as_key) $array=array_combine($array, $array); - if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && is_array($selected) && ! empty($selected)) - { - foreach ($selected as $selected_value) - { - foreach($array as $key => $value) - { - if ($selected_value == $key) - { - $value=$array[$selected_value]; - $out.= ''."\n"; - unset($array[$key]); - } - } - } - - if (! empty($array)) - { - foreach ($array as $key => $value) - { - $out.= ''."\n"; - } - } - } - else + if (! empty($array)) { foreach ($array as $key => $value) { @@ -3918,7 +4214,7 @@ class Form } $out.= '>'; - $newval = ($translate ? $langs->trans(ucfirst($value)) : $value); + $newval = ($translate ? $langs->trans($value) : $value); $newval = ($key_in_label ? $key.' - '.$newval : $newval); $out.= dol_htmlentitiesbr($newval); $out.= ''."\n"; @@ -3934,18 +4230,18 @@ class Form /** * Return an html string with a select combo box to choose yes or no * - * @param string $htmlname Name of html select field - * @param string $value Pre-selected value - * @param int $option 0 return yes/no, 1 return 1/0 - * @param bool $disabled true or false - * @return mixed See option + * @param string $htmlname Name of html select field + * @param string $value Pre-selected value + * @param int $option 0 return yes/no, 1 return 1/0 + * @param bool $disabled true or false + * @param useempty $useempty 1=Add empty line + * @return mixed See option */ - function selectyesno($htmlname,$value='',$option=0,$disabled=false) + function selectyesno($htmlname,$value='',$option=0,$disabled=false,$useempty='') { global $langs; $yes="yes"; $no="no"; - if ($option) { $yes="1"; @@ -3955,15 +4251,17 @@ class Form $disabled = ($disabled ? ' disabled="disabled"' : ''); $resultyesno = ''."\n"; return $resultyesno; @@ -4054,7 +4352,7 @@ class Form $ret.=''; print ''; print ''; + print ''; print ''; print "\n"; @@ -187,7 +205,15 @@ class FormActions print ''; print ''; print ''; - print ''; + print ''; print ''; + print ''; print ''; } print '
'; } - $ret.=$object->$fieldref; + $ret.=dol_htmlentities($object->$fieldref); if ($morehtmlref) { $ret.=' '.$morehtmlref; @@ -4172,7 +4470,7 @@ class Form { global $dolibarr_main_url_root; $ret.=''; - $ret.='Photo found on Gravatar'; + $ret.='Photo found on Gravatar'; // gravatar need md5 hash } else { @@ -4197,6 +4495,7 @@ class Form * @param int $enableonly Array list of groups id to be enabled. All other must be disabled * @param int $force_entity 0 or Id of environment to force * @return void + * @see select_dolusers */ function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0) { @@ -4210,7 +4509,7 @@ class Form $out=''; // On recherche les groupes - $sql = "SELECT ug.rowid, ug.nom "; + $sql = "SELECT ug.rowid, ug.nom as name"; if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity) { $sql.= ", e.label"; @@ -4230,7 +4529,7 @@ class Form if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')"; $sql.= " ORDER BY ug.nom ASC"; - dol_syslog(get_class($this)."::select_dolgroups sql=".$sql); + dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -4238,7 +4537,7 @@ class Form $i = 0; if ($num) { - $out.= ''; if ($show_empty) $out.= ''."\n"; while ($i < $num) @@ -4255,7 +4554,7 @@ class Form } $out.= '>'; - $out.= $obj->nom; + $out.= $obj->name; if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1) { $out.= " (".$obj->label.")"; diff --git a/htdocs/core/class/html.formactions.class.php b/htdocs/core/class/html.formactions.class.php index 522b2c30662..333969fc3b3 100644 --- a/htdocs/core/class/html.formactions.class.php +++ b/htdocs/core/class/html.formactions.class.php @@ -48,13 +48,15 @@ class FormActions /** * Show list of action status * - * @param string $formname Name of form where select in included - * @param string $selected Preselected value (-1..100) - * @param int $canedit 1=can edit, 0=read only - * @param string $htmlname Name of html prefix for html fields (selectX and valX) + * @param string $formname Name of form where select is included + * @param string $selected Preselected value (-1..100) + * @param int $canedit 1=can edit, 0=read only + * @param string $htmlname Name of html prefix for html fields (selectX and valX) + * @param string $showempty Show an empty line if select is used + * @param string $onlyselect 0=Standard, 1=Hide percent of completion and force usage of a select list, 2=Same than 1 and add "Incomplete (Todo+Running) * @return void */ - function form_select_status_action($formname,$selected,$canedit=1,$htmlname='complete') + function form_select_status_action($formname,$selected,$canedit=1,$htmlname='complete',$showempty=0,$onlyselect=0) { global $langs,$conf; @@ -64,6 +66,7 @@ class FormActions '50' => $langs->trans("ActionRunningShort"), '100' => $langs->trans("ActionDoneShort") ); + // +ActionUncomplete if (! empty($conf->use_javascript_ajax)) { @@ -112,18 +115,32 @@ class FormActions } } \n"; - print ''; + if ($showempty) print ''; foreach($listofstatus as $key => $val) { - print ''; + print ''; + if ($key == '50' && $onlyselect == 2) + { + print ''; + } } print ''; if ($selected == 0 || $selected == 100) $canedit=0; - print ' =0)?'':' disabled="disabled"').'>'; - print '%'; + + if (empty($onlyselect)) + { + print ' =0)?'':' disabled="disabled"').'>'; + print '%'; + } } else - { + { print ' %'; } } @@ -170,6 +187,7 @@ class FormActions print ''.$langs->trans('Action').''.$langs->trans('Date').''.$langs->trans('By').''.$langs->trans('Status').'
'.$ref.''.$label.''.dol_print_date($action->datep,'day').''.dol_print_date($action->datep,'dayhour'); + if ($action->datef) + { + $tmpa=dol_getdate($action->datep); + $tmpb=dol_getdate($action->datef); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) print '-'.dol_print_date($action->datef,'hour'); + else print '-'.dol_print_date($action->datef,'dayhour'); + } + print ''; if (! empty($action->author->id)) { @@ -197,6 +223,12 @@ class FormActions print $userstatic->getNomUrl(1); } print ''; + if (! empty($action->author->id)) + { + print $action->getLibStatut(3); + } + print '
'; @@ -209,18 +241,19 @@ class FormActions /** * Output list of type of event * - * @param string $selected Type pre-selected (can be 'manual', 'auto' or 'AC_xxx' + * @param string $selected Type pre-selected (can be 'manual', 'auto' or 'AC_xxx') * @param string $htmlname Nom champ formulaire * @param string $excludetype Type to exclude * @param string $onlyautoornot Group list by auto events or not: We keep only the 2 generic lines (AC_OTH and AC_OTH_AUTO) + * @param int $hideinfohelp 1=Do not show info help * @return void */ - function select_type_actions($selected='',$htmlname='actioncode',$excludetype='',$onlyautoornot=0) + function select_type_actions($selected='',$htmlname='actioncode',$excludetype='',$onlyautoornot=0, $hideinfohelp=0) { - global $langs,$user,$form; + global $langs,$user,$form,$conf; if (! is_object($form)) $form=new Form($db); - + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $caction=new CActionComm($this->db); @@ -233,8 +266,10 @@ class FormActions if ($selected == 'manual') $selected='AC_OTH'; if ($selected == 'auto') $selected='AC_OTH_AUTO'; + if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']); + print $form->selectarray($htmlname, $arraylist, $selected); - if ($user->admin && empty($onlyautoornot)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); + if ($user->admin && empty($onlyautoornot) && empty($hideinfohelp)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); } } diff --git a/htdocs/core/class/html.formadmin.class.php b/htdocs/core/class/html.formadmin.class.php index f7a6154706f..30ecadedb55 100644 --- a/htdocs/core/class/html.formadmin.class.php +++ b/htdocs/core/class/html.formadmin.class.php @@ -53,9 +53,10 @@ class FormAdmin * @param array $filter Array of keys to exclude in list * @param int $showempty Add empty value * @param int $showwarning Show a warning if language is not complete + * @param int $disabled Disable edit of select * @return string Return HTML select string with list of languages */ - function select_language($selected='',$htmlname='lang_id',$showauto=0,$filter=0,$showempty=0,$showwarning=0) + function select_language($selected='',$htmlname='lang_id',$showauto=0,$filter=0,$showempty=0,$showwarning=0,$disabled=0) { global $langs; @@ -63,7 +64,7 @@ class FormAdmin $out=''; - $out.= ''; if ($showempty) { $out.= '
+ diff --git a/htdocs/core/tpl/notes.tpl.php b/htdocs/core/tpl/notes.tpl.php index 0cce9a3e3b4..66b310da69d 100644 --- a/htdocs/core/tpl/notes.tpl.php +++ b/htdocs/core/tpl/notes.tpl.php @@ -22,6 +22,7 @@ $note_public = 'note_public'; $note_private = 'note_private'; $colwidth=(isset($colwidth)?$colwidth:25); + $permission=(isset($permission)?$permission:(isset($user->rights->$module->creer)?$user->rights->$module->creer:0)); // If already defined by caller page $moreparam=(isset($moreparam)?$moreparam:''); $value_public=$object->note_public; @@ -59,8 +60,9 @@ elseif ($module == 'contact') { $permission=$user->rights->societe->creer;} elseif ($module == 'shipping') { $permission=$user->rights->expedition->creer;} //else dol_print_error('','Bad value '.$module.' for param module'); -if (! empty($conf->global->FCKEDITOR_ENABLE_SOCIETE)) $typeofdata='ckeditor:dolibarr_notes:100%:200::1:12:100'; +if (! empty($conf->global->FCKEDITOR_ENABLE_SOCIETE)) $typeofdata='ckeditor:dolibarr_notes:100%:200::1:12:100'; // Rem: This var is for all notes, not only thirdparties note. else $typeofdata='textarea:12:100'; + ?> diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php index a51a6505416..6037f6c77c9 100644 --- a/htdocs/core/tpl/objectline_create.tpl.php +++ b/htdocs/core/tpl/objectline_create.tpl.php @@ -61,7 +61,7 @@ if (in_array($object->element,array('propal','facture','invoice','commande','ord if (! empty($usemargins)) { ?> - + global->MARGIN_TYPE == "1") echo $langs->trans('BuyingPrice'); @@ -70,8 +70,8 @@ if (in_array($object->element,array('propal','facture','invoice','commande','ord ?> rights->margins->creer && ! empty($conf->global->DISPLAY_MARGIN_RATES)) echo ''.$langs->trans('MarginRate').''; - if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARK_RATES)) echo ''.$langs->trans('MarkRate').''; + if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARGIN_RATES)) echo ''.$langs->trans('MarginRate').''; + if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARK_RATES)) echo ''.$langs->trans('MarkRate').''; } ?>   @@ -89,41 +89,50 @@ else { element == 'contrat') + { + if (empty($conf->product->enabled) && empty($conf->service->enabled) && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $forceall=-1; // With contract, by default, no choice at all, except if CONTRACT_SUPPORT_PRODUCTS is set + else $forceall=0; + } + // Free line echo ''; // Show radio free line - if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) + if ($forceall >= 0 && (! empty($conf->product->enabled) || ! empty($conf->service->enabled))) { + echo ''; echo ' '; - echo $form->select_type_of_lines(isset($_POST["type"])?$_POST["type"]:-1,'type',1,1,1); -// } + } + else + { + echo ''; + // Show type selector + if ($forceall >= 0) + { + echo $langs->trans("FreeLineOfType"); + echo ' '; + } + } + + echo $form->select_type_of_lines(isset($_POST["type"])?$_POST["type"]:-1,'type',1,1,$forceall); + echo ''; // Predefined product/service if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) { - echo '
'; + if ($forceall >= 0) echo '
'; + echo ''; + echo ''; echo ' '; $filtertype=''; @@ -152,7 +162,7 @@ else { 'option_disabled' => 'addPredefinedProductButton', // html id to disable once select is done 'warning' => $langs->trans("NoPriceDefinedForThisSupplier") // translation of an error saved into var 'error' ); - $form->select_produits_fournisseurs($object->fourn_id, GETPOST('idprodfournprice'), 'idprodfournprice', '', '', $ajaxoptions, 1); + $form->select_produits_fournisseurs($object->socid, GETPOST('idprodfournprice'), 'idprodfournprice', '', '', $ajaxoptions, 1); } echo ''; } @@ -184,7 +194,7 @@ else { tva_assuj == "0") echo '0'; + if ($seller->tva_assuj == "0") echo '0'; else echo $form->load_tva('tva_tx', (isset($_POST["tva_tx"])?$_POST["tva_tx"]:-1), $seller, $buyer); } ?> @@ -201,15 +211,15 @@ else { - "> + "> - remise_percent); ?>" name="remise_percent">% + remise_percent); ?>">% - + product->enabled) || ! empty($conf->service->enabled)) { ?> @@ -224,12 +234,12 @@ else { { if (! empty($conf->global->DISPLAY_MARGIN_RATES)) { - echo '%'; + echo '%'; $coldisplay++; } if (! empty($conf->global->DISPLAY_MARK_RATES)) { - echo '%'; + echo '%'; $coldisplay++; } } @@ -263,7 +273,7 @@ else { service->enabled) && $dateSelector) +if (! empty($conf->service->enabled) && $dateSelector && GETPOST('type') != '0') { if(! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) $colspan = 10; else $colspan = 9; diff --git a/htdocs/core/tpl/objectline_edit.tpl.php b/htdocs/core/tpl/objectline_edit.tpl.php index 95402139f7e..fbe2870a6a4 100644 --- a/htdocs/core/tpl/objectline_edit.tpl.php +++ b/htdocs/core/tpl/objectline_edit.tpl.php @@ -60,7 +60,7 @@ $coldisplay=-1; // We remove first td fk_product > 0) { ?> - + product_type==1) echo img_object($langs->trans('ShowService'),'service'); else print img_object($langs->trans('ShowProduct'),'product'); @@ -96,7 +96,7 @@ $coldisplay=-1; // We remove first td load_tva('tva_tx',$line->tva_tx,$seller,$buyer,0,$line->info_bits,$line->product_type); ?> - global->MAIN_FEATURES_LEVEL > 1) { ?> + @@ -107,7 +107,7 @@ $coldisplay=-1; // We remove first td // must also not be output for most entities (proposal, intervention, ...) //if($line->qty > $line->stock) print img_picto($langs->trans("StockTooLow"),"warning", 'style="vertical-align: bottom;"')." "; ?> - +   @@ -115,7 +115,7 @@ $coldisplay=-1; // We remove first td info_bits & 2) != 2) { ?> - % + %   @@ -125,7 +125,7 @@ $coldisplay=-1; // We remove first td if (! empty($usemargins)) { ?> - + product->enabled) || ! empty($conf->service->enabled)) { ?> @@ -139,9 +139,9 @@ $coldisplay=-1; // We remove first td $margin_rate = (isset($_POST["np_marginRate"])?$_POST["np_marginRate"]:(($line->pa_ht == 0)?'':price($line->marge_tx))); // if credit note, dont allow to modify margin if ($line->subprice < 0) - echo ''.$margin_rate.'%'; + echo ''.$margin_rate.'%'; else - echo '%'; + echo '%'; $coldisplay++; } elseif (! empty($conf->global->DISPLAY_MARK_RATES)) @@ -149,9 +149,9 @@ $coldisplay=-1; // We remove first td $mark_rate = (isset($_POST["np_markRate"])?$_POST["np_markRate"]:price($line->marque_tx)); // if credit note, dont allow to modify margin if ($line->subprice < 0) - echo ''.$mark_rate.'%'; + echo ''.$mark_rate.'%'; else - echo '%'; + echo '%'; $coldisplay++; } } diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index 948a61bae2c..1c8bb07f560 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -17,9 +17,27 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * - * To use this template, the following var must be defined + * Need to have following variables defined: + * $object (invoice, order, ...) + * $conf + * $langs + * $dateSelector + * $forceall (0 by default, 1 for supplier invoices/orders) + * $senderissupplier (0 by default, 1 for supplier invoices/orders) + * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax) + * * $type, $text, $description, $line */ + +$usemargins=0; +if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1; + +global $forceall, $senderissupplier, $inputalsopricewithtax; +if (empty($dateSelector)) $dateSelector=0; +if (empty($forceall)) $forceall=0; +if (empty($senderissupplier)) $senderissupplier=0; +if (empty($inputalsopricewithtax)) $inputalsopricewithtax=0; + ?> @@ -100,7 +118,7 @@ subprice); ?> - global->MAIN_FEATURES_LEVEL > 1) { ?> +   @@ -123,13 +141,13 @@ if (! empty($conf->margin->enabled) && empty($user->societe_id)) { $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT); ?> - pa_ht); ?> + pa_ht); ?> global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) {?> - pa_ht == 0)?'n/a':price($line->marge_tx, null, null, null, null, $rounding).'%'); ?> + pa_ht == 0)?'n/a':price($line->marge_tx, null, null, null, null, $rounding).'%'); ?> global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) {?> - marque_tx, null, null, null, null, $rounding).'%'; ?> + marque_tx, null, null, null, null, $rounding).'%'; ?> special_code == 3) { ?> @@ -176,7 +194,8 @@ showOptionals($extrafieldsline,'view',array('style'=>$bcdd[$var],'colspan'=>$coldisplay)); } ?> diff --git a/htdocs/core/tpl/passwordforgotten.tpl.php b/htdocs/core/tpl/passwordforgotten.tpl.php index 7331a81ead0..af27aff944b 100644 --- a/htdocs/core/tpl/passwordforgotten.tpl.php +++ b/htdocs/core/tpl/passwordforgotten.tpl.php @@ -43,7 +43,10 @@ $(document).ready(function () { +
+
-
- diff --git a/htdocs/core/tpl/resource_view.tpl.php b/htdocs/core/tpl/resource_view.tpl.php index ef2963b28c1..d57b66cc331 100644 --- a/htdocs/core/tpl/resource_view.tpl.php +++ b/htdocs/core/tpl/resource_view.tpl.php @@ -32,7 +32,7 @@ if( (array) $linked_resources && count($linked_resources) > 0) print '
'.$langs->trans('Resource').'
'; print '
'.$langs->trans('Busy').'
'; print '
'.$langs->trans('Mandatory').'
'; - print '
'.$langs->trans('Edit').'
'; + print '
'.$langs->trans('Action').'
'; print ''; //print ''; @@ -86,8 +86,13 @@ if( (array) $linked_resources && count($linked_resources) > 0) print ''; print '
'; print ''; @@ -105,4 +110,4 @@ else { print '
'.$langs->trans('NoResourceLinked').'
'; } -// FIN DU TPL +// FIN DU TPL \ No newline at end of file diff --git a/htdocs/core/triggers/dolibarrtriggers.class.php b/htdocs/core/triggers/dolibarrtriggers.class.php new file mode 100644 index 00000000000..0682bb76a71 --- /dev/null +++ b/htdocs/core/triggers/dolibarrtriggers.class.php @@ -0,0 +1,148 @@ + + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Class that all the triggers must extend + */ +abstract class DolibarrTriggers +{ + + /** + * Database handler + * @var DoliDB + */ + protected $db; + + /** + * Name of the trigger + * @var mixed|string + */ + public $name = ''; + + /** + * Description of the trigger + * @var string + */ + public $description = ''; + + /** + * Version of the trigger + * @var string + */ + public $version = self::VERSION_DEVELOPMENT; + + /** + * Image of the trigger + * @var string + */ + public $picto = 'technic'; + + /** + * Category of the trigger + * @var string + */ + public $family = ''; + + /** + * Error reported by the trigger + * @var string + * @deprecated Use $this->errors + */ + public $error = ''; + + /** + * Errors reported by the trigger + * @var array + */ + public $errors = array(); + + const VERSION_DEVELOPMENT = 'development'; + const VERSION_EXPERIMENTAL = 'experimental'; + const VERSION_DOLIBARR = 'dolibarr'; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) { + + $this->db = $db; + + if (empty($this->name)) + { + $this->name = preg_replace('/^Interface/i', '', get_class($this)); + } + } + + /** + * Returns the name of the trigger file + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns the description of trigger file + * + * @return string + */ + public function getDesc() + { + return $this->description; + } + + /** + * Returns the version of the trigger file + * + * @return string Version of trigger file + */ + public function getVersion() + { + global $langs; + $langs->load("admin"); + + if ($this->version == self::VERSION_DEVELOPMENT) { + return $langs->trans("Development"); + } elseif ($this->version == self::VERSION_EXPERIMENTAL) { + return $langs->trans("Experimental"); + } elseif ($this->version == self::VERSION_DOLIBARR) { + return DOL_VERSION; + } elseif ($this->version) { + return $this->version; + } else { + return $langs->trans("Unknown"); + } + } + + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + abstract function runTrigger($action, $object, User $user, Translate $langs, Conf $conf); + +} \ No newline at end of file diff --git a/htdocs/core/triggers/index.html b/htdocs/core/triggers/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/core/triggers/index.php b/htdocs/core/triggers/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/core/triggers/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/core/triggers/interface_20_all_Logevents.class.php b/htdocs/core/triggers/interface_20_all_Logevents.class.php index df6242a20d9..34bd187adbf 100644 --- a/htdocs/core/triggers/interface_20_all_Logevents.class.php +++ b/htdocs/core/triggers/interface_20_all_Logevents.class.php @@ -1,6 +1,7 @@ * Copyright (C) 2009 Regis Houssin + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,85 +23,31 @@ * \brief Trigger file for */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + /** * Class of triggers for security events */ -class InterfaceLogevents +class InterfaceLogevents extends DolibarrTriggers { - var $db; - var $error; + public $picto = 'technic'; + public $family = 'core'; + public $description = "Triggers of this module allows to add security event records inside Dolibarr."; + public $version = self::VERSION_DOLIBARR; - var $date; - var $duree; - var $texte; - var $desc; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "core"; - $this->description = "Triggers of this module allows to add security event records inside Dolibarr."; - $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version - $this->picto = 'technic'; - } - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @param string $entity Value for instance of data (Always 1 except if module MultiCompany is installed) - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf,$entity=1) + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { if (! empty($conf->global->MAIN_LOGEVENTS_DISABLE_ALL)) return 0; // Log events is disabled (hidden features) @@ -110,8 +57,7 @@ class InterfaceLogevents if (empty($conf->entity)) $conf->entity = $entity; // forcing of the entity if it's not defined (ex: in login form) - $this->date=dol_now(); - $this->duree=0; + $date = dol_now(); // Actions if ($action == 'USER_LOGIN') @@ -119,24 +65,26 @@ class InterfaceLogevents dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); // Initialisation donnees (date,duree,texte,desc) - $this->texte="(UserLogged,".$object->login.")"; - $this->desc="(UserLogged,".$object->login.")"; + $text="(UserLogged,".$object->login.")"; + $text.=(empty($object->trigger_mesg)?'':' - '.$object->trigger_mesg); + $desc="(UserLogged,".$object->login.")"; + $desc.=(empty($object->trigger_mesg)?'':' - '.$object->trigger_mesg); } if ($action == 'USER_LOGIN_FAILED') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$object->trigger_mesg; // Message direct - $this->desc=$object->trigger_mesg; // Message direct + $text=$object->trigger_mesg; // Message direct + $desc=$object->trigger_mesg; // Message direct } if ($action == 'USER_LOGOUT') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); // Initialisation donnees (date,duree,texte,desc) - $this->texte="(UserLogoff,".$object->login.")"; - $this->desc="(UserLogoff,".$object->login.")"; + $text="(UserLogoff,".$object->login.")"; + $desc="(UserLogoff,".$object->login.")"; } if ($action == 'USER_CREATE') { @@ -144,8 +92,8 @@ class InterfaceLogevents $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("NewUserCreated",$object->login); - $this->desc=$langs->transnoentities("NewUserCreated",$object->login); + $text=$langs->transnoentities("NewUserCreated",$object->login); + $desc=$langs->transnoentities("NewUserCreated",$object->login); } elseif ($action == 'USER_MODIFY') { @@ -153,8 +101,8 @@ class InterfaceLogevents $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("EventUserModified",$object->login); - $this->desc=$langs->transnoentities("EventUserModified",$object->login); + $text=$langs->transnoentities("EventUserModified",$object->login); + $desc=$langs->transnoentities("EventUserModified",$object->login); } elseif ($action == 'USER_NEW_PASSWORD') { @@ -162,8 +110,8 @@ class InterfaceLogevents $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("NewUserPassword",$object->login); - $this->desc=$langs->transnoentities("NewUserPassword",$object->login); + $text=$langs->transnoentities("NewUserPassword",$object->login); + $desc=$langs->transnoentities("NewUserPassword",$object->login); } elseif ($action == 'USER_ENABLEDISABLE') { @@ -172,13 +120,13 @@ class InterfaceLogevents // Initialisation donnees (date,duree,texte,desc) if ($object->statut == 0) { - $this->texte=$langs->transnoentities("UserEnabled",$object->login); - $this->desc=$langs->transnoentities("UserEnabled",$object->login); + $text=$langs->transnoentities("UserEnabled",$object->login); + $desc=$langs->transnoentities("UserEnabled",$object->login); } if ($object->statut == 1) { - $this->texte=$langs->transnoentities("UserDisabled",$object->login); - $this->desc=$langs->transnoentities("UserDisabled",$object->login); + $text=$langs->transnoentities("UserDisabled",$object->login); + $desc=$langs->transnoentities("UserDisabled",$object->login); } } elseif ($action == 'USER_DELETE') @@ -186,8 +134,8 @@ class InterfaceLogevents dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("UserDeleted",$object->login); - $this->desc=$langs->transnoentities("UserDeleted",$object->login); + $text=$langs->transnoentities("UserDeleted",$object->login); + $desc=$langs->transnoentities("UserDeleted",$object->login); } // Groupes @@ -196,24 +144,24 @@ class InterfaceLogevents dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("NewGroupCreated",$object->nom); - $this->desc=$langs->transnoentities("NewGroupCreated",$object->nom); + $text=$langs->transnoentities("NewGroupCreated",$object->name); + $desc=$langs->transnoentities("NewGroupCreated",$object->name); } elseif ($action == 'GROUP_MODIFY') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("GroupModified",$object->nom); - $this->desc=$langs->transnoentities("GroupModified",$object->nom); + $text=$langs->transnoentities("GroupModified",$object->name); + $desc=$langs->transnoentities("GroupModified",$object->name); } elseif ($action == 'GROUP_DELETE') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("users"); // Initialisation donnees (date,duree,texte,desc) - $this->texte=$langs->transnoentities("GroupDeleted",$object->nom); - $this->desc=$langs->transnoentities("GroupDeleted",$object->nom); + $text=$langs->transnoentities("GroupDeleted",$object->name); + $desc=$langs->transnoentities("GroupDeleted",$object->name); } // If not found @@ -226,30 +174,27 @@ class InterfaceLogevents */ // Add entry in event table - if ($this->date) + include_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; + + $event=new Events($this->db); + $event->type=$action; + $event->dateevent=$date; + $event->label=$text; + $event->description=$desc; + $event->user_agent=$_SERVER["HTTP_USER_AGENT"]; + + $result=$event->create($user); + if ($result > 0) { - include_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php'; + return 1; + } + else + { + $error ="Failed to insert security event: ".$event->error; + $this->error=$error; - $event=new Events($this->db); - $event->type=$action; - $event->dateevent=$this->date; - $event->label=$this->texte; - $event->description=$this->desc; - $event->user_agent=$_SERVER["HTTP_USER_AGENT"]; - - $result=$event->create($user); - if ($result > 0) - { - return 1; - } - else - { - $error ="Failed to insert security event: ".$event->error; - $this->error=$error; - - dol_syslog(get_class($this).": ".$this->error, LOG_ERR); - return -1; - } + dol_syslog(get_class($this).": ".$this->error, LOG_ERR); + return -1; } return 0; diff --git a/htdocs/core/triggers/interface_20_modPaypal_PaypalWorkflow.class.php b/htdocs/core/triggers/interface_20_modPaypal_PaypalWorkflow.class.php index 4401a0ebcfa..1d57f598d57 100644 --- a/htdocs/core/triggers/interface_20_modPaypal_PaypalWorkflow.class.php +++ b/htdocs/core/triggers/interface_20_modPaypal_PaypalWorkflow.class.php @@ -1,5 +1,6 @@ + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -21,80 +22,31 @@ * \brief Trigger file for paypal workflow */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + /** * Class of triggers for paypal module */ -class InterfacePaypalWorkflow +class InterfacePaypalWorkflow extends DolibarrTriggers { - var $db; + public $picto = 'paypal@paypal'; + public $family = 'paypal'; + public $description = "Triggers of this module allows to manage paypal workflow"; + public $version = self::VERSION_DOLIBARR; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "paypal"; - $this->description = "Triggers of this module allows to manage paypal workflow"; - $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version - $this->picto = 'paypal@paypal'; - } - - - /** - * Renvoi nom du lot de triggers - * - * @return string Nom du lot de triggers - */ - function getName() - { - return $this->name; - } - - /** - * Renvoi descriptif du lot de triggers - * - * @return string Descriptif du lot de triggers - */ - function getDesc() - { - return $this->description; - } - - /** - * Renvoi version du lot de triggers - * - * @return string Version du lot de triggers - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'development') return $langs->trans("Development"); - elseif ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Fonction appelee lors du declenchement d'un evenement Dolibarr. - * D'autres fonctions run_trigger peuvent etre presentes dans core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { // Mettre ici le code a executer en reaction de l'action // Les donnees de l'action sont stockees dans $object diff --git a/htdocs/core/triggers/interface_20_modWorkflow_WorkflowManager.class.php b/htdocs/core/triggers/interface_20_modWorkflow_WorkflowManager.class.php index adca98768d3..d144f365533 100644 --- a/htdocs/core/triggers/interface_20_modWorkflow_WorkflowManager.class.php +++ b/htdocs/core/triggers/interface_20_modWorkflow_WorkflowManager.class.php @@ -1,6 +1,7 @@ * Copyright (C) 2011 Laurent Destailleur + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,81 +23,32 @@ * \brief Trigger file for workflows */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + /** * Class of triggers for workflow module */ -class InterfaceWorkflowManager +class InterfaceWorkflowManager extends DolibarrTriggers { - var $db; + public $picto = 'paypal@paypal'; + public $family = 'core'; + public $description = "Triggers of this module allows to manage workflows"; + public $version = self::VERSION_DOLIBARR; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "core"; - $this->description = "Triggers of this module allows to manage workflows"; - $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version - $this->picto = 'technic'; - } - - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'development') return $langs->trans("Development"); - elseif ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { if (empty($conf->workflow->enabled)) return 0; // Module not active, we do nothing @@ -166,7 +118,7 @@ class InterfaceWorkflowManager return $ret; } } - + // classify billed order if ($action == 'BILL_VALIDATE') { diff --git a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php index 7b3cbe15f9a..346932ec61e 100644 --- a/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php +++ b/htdocs/core/triggers/interface_50_modAgenda_ActionsAuto.class.php @@ -3,6 +3,7 @@ * Copyright (C) 2009-2011 Regis Houssin * Copyright (C) 2011-2014 Juanjo Menent * Copyright (C) 2013 Cedric GROSS + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,127 +25,73 @@ * \brief Trigger file for agenda module */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; + /** * Class of triggered functions for agenda module */ -class InterfaceActionsAuto +class InterfaceActionsAuto extends DolibarrTriggers { - var $db; - var $error; + public $family = 'agenda'; + public $description = "Triggers of this module add actions in agenda according to setup made in agenda setup."; + public $version = self::VERSION_DOLIBARR; + public $picto = 'action'; - var $date; - var $duree; - var $texte; - var $desc; + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * Following properties must be filled: + * $object->actiontypecode (translation action code: AC_OTH, ...) + * $object->actionmsg (note, long text) + * $object->actionmsg2 (label, short text) + * $object->sendtoid (id of contact) + * $object->socid + * Optionnal: + * $object->fk_element + * $object->elementtype + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { + // Module not active, we do nothing + if (empty($conf->agenda->enabled)) { + return 0; + } - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; + $key = 'MAIN_AGENDA_ACTIONAUTO_'.$action; - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "agenda"; - $this->description = "Triggers of this module add actions in agenda according to setup made in agenda setup."; - $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version - $this->picto = 'action'; - } + // Do not log events not enabled for this action + if (empty($conf->global->$key)) { + return 0; + } - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * Following properties must be filled: - * $object->actiontypecode (translation action code: AC_OTH, ...) - * $object->actionmsg (note, long text) - * $object->actionmsg2 (label, short text) - * $object->sendtoid (id of contact) - * $object->socid - * Optionnal: - * $object->fk_element - * $object->elementtype - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) - { - $key='MAIN_AGENDA_ACTIONAUTO_'.$action; - //dol_syslog("xxxxxxxxxxx".$key); - - if (empty($conf->agenda->enabled)) return 0; // Module not active, we do nothing - if (empty($conf->global->$key)) return 0; // Log events not enabled for this action - - $ok=0; + $langs->load("agenda"); // Actions if ($action == 'COMPANY_CREATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("NewCompanyToDolibarr",$object->nom); - $object->actionmsg=$langs->transnoentities("NewCompanyToDolibarr",$object->nom); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("NewCompanyToDolibarr",$object->name); + $object->actionmsg=$langs->transnoentities("NewCompanyToDolibarr",$object->name); if (! empty($object->prefix)) $object->actionmsg.=" (".$object->prefix.")"; - //$this->desc.="\n".$langs->transnoentities("Customer").': '.yn($object->client); - //$this->desc.="\n".$langs->transnoentities("Supplier").': '.yn($object->fournisseur); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->socid=$object->id; - $ok=1; } elseif ($action == 'COMPANY_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); if (empty($object->actiontypecode)) $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) dol_syslog('Trigger called with property actionmsg2 on object not defined', LOG_ERR); @@ -152,42 +99,33 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'CONTRACT_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("contracts"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ContractValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("ContractValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("ContractValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'PROPAL_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("propal"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("PropalValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("PropalValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'PROPAL_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("propal"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProposalSentByEMail",$object->ref); @@ -199,13 +137,10 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'PROPAL_CLOSE_SIGNED') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("propal"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedSignedInDolibarr",$object->ref); @@ -213,13 +148,21 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; + } + elseif ($action == 'PROPAL_CLASSIFY_BILLED') + { + $langs->load("propal"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("PropalClassifiedBilledInDolibarr",$object->ref); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; } elseif ($action == 'PROPAL_CLOSE_REFUSED') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("propal"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("PropalClosedRefusedInDolibarr",$object->ref); @@ -227,27 +170,21 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderSentByEMail",$object->ref); @@ -259,29 +196,23 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_UNVALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceBackToDraftInDolibarr",$object->ref); @@ -289,14 +220,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceSentByEMail",$object->ref); @@ -308,14 +236,11 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_PAYED') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); // Values for this action can't be defined by caller. $object->actiontypecode='AC_OTH_AUTO'; @@ -324,14 +249,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_CANCEL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); @@ -339,66 +261,119 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } - elseif ($action == 'FICHINTER_VALIDATE') + elseif ($action == 'FICHINTER_CREATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - $langs->load("other"); + $langs->load("other"); $langs->load("interventions"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("InterventionValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("InterventionCreatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; $object->fk_element=0; $object->elementtype=''; - $ok=1; } - elseif ($action == 'FICHINTER_SENTBYMAIL') + elseif ($action == 'FICHINTER_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("interventions"); - $langs->load("agenda"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("InterventionValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; + $object->fk_element=0; + $object->elementtype=''; + } + elseif ($action == 'FICHINTER_MODIFY') + { + $langs->load("other"); + $langs->load("interventions"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("InterventionModifiedInDolibarr",$object->ref); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; + $object->fk_element=0; + $object->elementtype=''; + } + elseif ($action == 'FICHINTER_SENTBYMAIL') + { + $langs->load("other"); + $langs->load("interventions"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionSentByEMail",$object->ref); $object->actionmsg=$langs->transnoentities("InterventionSentByEMail",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; - - // Parameters $object->sendotid defined by caller + // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } - elseif ($action == 'SHIPPING_VALIDATE') + elseif ($action == 'FICHINTER_CLASSIFY_BILLED') + { + $langs->load("other"); + $langs->load("interventions"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("InterventionClassifiedBilledInDolibarr",$object->ref); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; + } + elseif ($action == 'FICHINTER_CLASSIFY_UNBILLED') + { + $langs->load("other"); + $langs->load("interventions"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("InterventionClassifiedUnbilledInDolibarr",$object->ref); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; + } + elseif ($action == 'FICHINTER_DELETE') + { + $langs->load("other"); + $langs->load("interventions"); + + $object->actiontypecode='AC_OTH_AUTO'; + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref); + $object->actionmsg=$langs->transnoentities("InterventionDeletedInDolibarr",$object->ref); + $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + + $object->sendtoid=0; + $object->fk_element=0; + $object->elementtype=''; + } + elseif ($action == 'SHIPPING_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("sendings"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ShippingValidated",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ShippingValidated",($object->newref?$object->newref:$object->ref)); if (empty($object->actionmsg)) { - $object->actionmsg=$langs->transnoentities("ShippingValidated",$object->ref); + $object->actionmsg=$langs->transnoentities("ShippingValidated",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'SHIPPING_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("sendings"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ShippingSentByEMail",$object->ref); @@ -410,27 +385,21 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_SUPPLIER_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("OrderValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_SUPPLIER_APPROVE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderApprovedInDolibarr",$object->ref); @@ -438,13 +407,10 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_SUPPLIER_REFUSE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("orders"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("OrderRefusedInDolibarr",$object->ref); @@ -452,14 +418,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'ORDER_SUPPLIER_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $langs->load("orders"); $object->actiontypecode='AC_OTH_AUTO'; @@ -470,31 +433,25 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; } - // Parameters $object->sendotid defined by caller + // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_SUPPLIER_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("InvoiceValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_SUPPLIER_SENTBYMAIL') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $langs->load("orders"); $object->actiontypecode='AC_OTH_AUTO'; @@ -507,14 +464,11 @@ class InterfaceActionsAuto // Parameters $object->sendtoid defined by caller //$object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_SUPPLIER_PAYED') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoicePaidInDolibarr",$object->ref); @@ -522,14 +476,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'BILL_SUPPLIER_CANCELED') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("bills"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("InvoiceCanceledInDolibarr",$object->ref); @@ -537,33 +488,27 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } // Members elseif ($action == 'MEMBER_VALIDATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("members"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; - if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberValidatedInDolibarr",$object->ref); - $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",$object->ref); + if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); + $object->actionmsg=$langs->transnoentities("MemberValidatedInDolibarr",($object->newref?$object->newref:$object->ref)); $object->actionmsg.="\n".$langs->transnoentities("Member").': '.$object->getFullName($langs); $object->actionmsg.="\n".$langs->transnoentities("Type").': '.$object->type; $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'MEMBER_SUBSCRIPTION') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("members"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberSubscriptionAddedInDolibarr",$object->ref); @@ -575,18 +520,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; - } - elseif ($action == 'MEMBER_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); } elseif ($action == 'MEMBER_RESILIATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("members"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberResiliatedInDolibarr",$object->ref); @@ -596,14 +534,11 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } elseif ($action == 'MEMBER_DELETE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("members"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("MemberDeletedInDolibarr",$object->ref); @@ -613,32 +548,27 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; $object->sendtoid=0; - $ok=1; } // Projects elseif ($action == 'PROJECT_CREATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("projects"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref); $object->actionmsg=$langs->transnoentities("ProjectCreatedInDolibarr",$object->ref); $object->actionmsg.="\n".$langs->transnoentities("Project").': '.$object->ref; $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; + $object->sendtoid=0; - $ok=1; } // Project tasks elseif($action == 'TASK_CREATE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("projects"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; @@ -647,14 +577,12 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; - $ok=1; + $object->sendtoid=0; } elseif($action == 'TASK_MODIFY') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("projects"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskModifiedInDolibarr",$object->ref); @@ -662,14 +590,12 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; - $ok=1; + $object->sendtoid=0; } elseif($action == 'TASK_DELETE') { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); $langs->load("other"); $langs->load("projects"); - $langs->load("agenda"); $object->actiontypecode='AC_OTH_AUTO'; if (empty($object->actionmsg2)) $object->actionmsg2=$langs->transnoentities("TaskDeletedInDolibarr",$object->ref); @@ -677,7 +603,7 @@ class InterfaceActionsAuto $object->actionmsg.="\n".$langs->transnoentities("Task").': '.$object->ref; $object->actionmsg.="\n".$langs->transnoentities("Author").': '.$user->login; - $ok=1; + $object->sendtoid=0; } // The trigger was enabled but we are missing the implementation, let the log know @@ -687,63 +613,65 @@ class InterfaceActionsAuto return 0; } + dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); + // Add entry in event table - if ($ok) - { - $now=dol_now(); + $now=dol_now(); - if(isset($_SESSION['listofnames'])) + if(isset($_SESSION['listofnames'])) + { + $attachs=$_SESSION['listofnames']; + if($attachs && strpos($action,'SENTBYMAIL')) { - $attachs=$_SESSION['listofnames']; - if($attachs && strpos($action,'SENTBYMAIL')) - { - $object->actionmsg.="\n".$langs->transnoentities("AttachedFiles").': '.$attachs; - } + $object->actionmsg.="\n".$langs->transnoentities("AttachedFiles").': '.$attachs; } + } - require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; - require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; - $contactforaction=new Contact($this->db); - $societeforaction=new Societe($this->db); - if ($object->sendtoid > 0) $contactforaction->fetch($object->sendtoid); - if ($object->socid > 0) $societeforaction->fetch($object->socid); + require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; + require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + $contactforaction=new Contact($this->db); + $societeforaction=new Societe($this->db); + if ($object->sendtoid > 0) $contactforaction->fetch($object->sendtoid); + if ($object->socid > 0) $societeforaction->fetch($object->socid); - // Insertion action - require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; - $actioncomm = new ActionComm($this->db); - $actioncomm->type_code = $object->actiontypecode; // code of parent table llx_c_actioncomm (will be deprecated) - $actioncomm->code='AC_'.$action; - $actioncomm->label = $object->actionmsg2; - $actioncomm->note = $object->actionmsg; - $actioncomm->datep = $now; - $actioncomm->datef = $now; - $actioncomm->durationp = 0; - $actioncomm->punctual = 1; - $actioncomm->percentage = -1; // Not applicable - $actioncomm->contact = $contactforaction; - $actioncomm->societe = $societeforaction; - $actioncomm->author = $user; // User saving action - $actioncomm->usertodo = $user; // User action is assigned to (owner of action) - $actioncomm->userdone = $user; // User doing action (deprecated, not used anymore) + // Insertion action + require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; + $actioncomm = new ActionComm($this->db); + $actioncomm->type_code = $object->actiontypecode; // code of parent table llx_c_actioncomm (will be deprecated) + $actioncomm->code='AC_'.$action; + $actioncomm->label = $object->actionmsg2; + $actioncomm->note = $object->actionmsg; + $actioncomm->datep = $now; + $actioncomm->datef = $now; + $actioncomm->durationp = 0; + $actioncomm->punctual = 1; + $actioncomm->percentage = -1; // Not applicable + $actioncomm->societe = $societeforaction; + $actioncomm->contact = $contactforaction; + $actioncomm->socid = $societeforaction->id; + $actioncomm->contactid = $contactforaction->id; + $actioncomm->authorid = $user->id; // User saving action + $actioncomm->userownerid = $user->id; // Owner of action + //$actioncomm->userdone = $user; // User doing action (not used anymore) + //$actioncomm->userdoneid = $user->id; // User doing action (not used anymore) - $actioncomm->fk_element = $object->id; - $actioncomm->elementtype = $object->element; + $actioncomm->fk_element = $object->id; + $actioncomm->elementtype = $object->element; - $ret=$actioncomm->add($user); // User qui saisit l'action - if ($ret > 0) - { - $_SESSION['LAST_ACTION_CREATED'] = $ret; - return 1; - } - else - { - $error ="Failed to insert event : ".$actioncomm->error." ".join(',',$actioncomm->errors); - $this->error=$error; - $this->errors=$actioncomm->errors; + $ret=$actioncomm->add($user); // User qui saisit l'action + if ($ret > 0) + { + $_SESSION['LAST_ACTION_CREATED'] = $ret; + return 1; + } + else + { + $error ="Failed to insert event : ".$actioncomm->error." ".join(',',$actioncomm->errors); + $this->error=$error; + $this->errors=$actioncomm->errors; - dol_syslog("interface_modAgenda_ActionsAuto.class.php: ".$this->error, LOG_ERR); - return -1; - } + dol_syslog("interface_modAgenda_ActionsAuto.class.php: ".$this->error, LOG_ERR); + return -1; } return 0; diff --git a/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php b/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php index 7bc742d3a26..652a1ec8d6b 100644 --- a/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php +++ b/htdocs/core/triggers/interface_50_modLdap_Ldapsynchro.class.php @@ -1,5 +1,6 @@ + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,83 +21,34 @@ * \ingroup core * \brief Fichier de gestion des triggers LDAP */ -require_once (DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"); -require_once (DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"); + +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; +require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; +require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"; /** * Class of triggers for ldap module */ -class InterfaceLdapsynchro +class InterfaceLdapsynchro extends DolibarrTriggers { - var $db; - var $error; + public $family = 'ldap'; + public $description = "Triggers of this module allows to synchronize Dolibarr toward a LDAP database."; + public $version = self::VERSION_DOLIBARR; + public $picto = 'technic'; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "ldap"; - $this->description = "Triggers of this module allows to synchronize Dolibarr toward a LDAP database."; - $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version - $this->picto = 'technic'; - } - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { if (empty($conf->ldap->enabled)) return 0; // Module not active, we do nothing @@ -215,7 +167,7 @@ class InterfaceLdapsynchro $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); - $result=$ldap->delete($dn,$info,$user); + $result=$ldap->delete($dn); if ($result < 0) { $this->error="ErrorLDAP ".$ldap->error; @@ -372,7 +324,7 @@ class InterfaceLdapsynchro $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); - $result=$ldap->delete($dn,$info,$user); + $result=$ldap->delete($dn); if ($result < 0) { $this->error="ErrorLDAP ".$ldap->error; @@ -449,7 +401,7 @@ class InterfaceLdapsynchro $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); - $result=$ldap->delete($dn,$info,$user); + $result=$ldap->delete($dn); if ($result < 0) { $this->error="ErrorLDAP ".$ldap->error; @@ -626,7 +578,7 @@ class InterfaceLdapsynchro $info=$object->_load_ldap_info(); $dn=$object->_load_ldap_dn($info); - $result=$ldap->delete($dn,$info,$user); + $result=$ldap->delete($dn); if ($result < 0) { $this->error="ErrorLDAP ".$ldap->error; diff --git a/htdocs/core/triggers/interface_50_modMailmanspip_Mailmanspipsynchro.class.php b/htdocs/core/triggers/interface_50_modMailmanspip_Mailmanspipsynchro.class.php index 01ce1f7e539..467cf678c07 100644 --- a/htdocs/core/triggers/interface_50_modMailmanspip_Mailmanspipsynchro.class.php +++ b/htdocs/core/triggers/interface_50_modMailmanspip_Mailmanspipsynchro.class.php @@ -1,5 +1,6 @@ + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,84 +21,34 @@ * \ingroup core * \brief File to manage triggers Mailman and Spip */ -require_once (DOL_DOCUMENT_ROOT."/mailmanspip/class/mailmanspip.class.php"); -require_once (DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"); +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; +require_once DOL_DOCUMENT_ROOT."/mailmanspip/class/mailmanspip.class.php"; +require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"; /** * Class of triggers for MailmanSpip module */ -class InterfaceMailmanSpipsynchro +class InterfaceMailmanSpipsynchro extends DolibarrTriggers { - var $db; - var $error; + public $family = 'ldap'; + public $description = "Triggers of this module allows to synchronize Mailman an Spip."; + public $version = self::VERSION_DOLIBARR; + public $picto = 'technic'; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "ldap"; - $this->description = "Triggers of this module allows to synchronize Mailman an Spip."; - $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version - $this->picto = 'technic'; - } - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) - { + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { if (empty($conf->mailmanspip->enabled)) return 0; // Module not active, we do nothing if (! function_exists('ldap_connect')) @@ -106,38 +57,7 @@ class InterfaceMailmanSpipsynchro return 0; } - // Users - if ($action == 'USER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - } - elseif ($action == 'USER_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_NEW_PASSWORD') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_ENABLEDISABLE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_SETINGROUP') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_REMOVEFROMGROUP') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - elseif ($action == 'CATEGORY_LINK') + if ($action == 'CATEGORY_LINK') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); @@ -211,10 +131,6 @@ class InterfaceMailmanSpipsynchro return $return; } - elseif ($action == 'MEMBER_NEW_PASSWORD') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } elseif ($action == 'MEMBER_RESILIATE' || $action == 'MEMBER_DELETE') { dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); @@ -231,16 +147,10 @@ class InterfaceMailmanSpipsynchro { $return=1; } + + return $return; } - // If not found -/* - else - { - dol_syslog("Trigger '".$this->name."' for action '$action' was ran by ".__FILE__." but no handler found for this action."); - return -1; - } -*/ return 0; } diff --git a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php index c035acac207..940e3a1712d 100644 --- a/htdocs/core/triggers/interface_50_modNotification_Notification.class.php +++ b/htdocs/core/triggers/interface_50_modNotification_Notification.class.php @@ -1,7 +1,7 @@ * Copyright (C) 2011 Regis Houssin - * Copyright (C) 2013 Marcos García + * Copyright (C) 2013-2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -22,14 +22,19 @@ * \ingroup notification * \brief File of class of triggers for notification module */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; /** * Class of triggers for notification module */ -class InterfaceNotification +class InterfaceNotification extends DolibarrTriggers { - var $db; + public $family = 'notification'; + public $description = "Triggers of this module send email notifications according to Notification module setup."; + public $version = self::VERSION_DOLIBARR; + public $picto = 'email'; + var $listofmanagedevents=array( 'BILL_VALIDATE', 'ORDER_VALIDATE', @@ -40,187 +45,29 @@ class InterfaceNotification 'SHIPPING_VALIDATE' ); - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "notification"; - $this->description = "Triggers of this module send email notifications according to Notification module setup."; - $this->version = 'dolibarr'; // 'experimental' or 'dolibarr' or version - $this->picto = 'email'; - } - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); - - if ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers - * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK - */ - function run_trigger($action,$object,$user,$langs,$conf) - { + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) + * + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK + */ + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) + { if (empty($conf->notification->enabled)) return 0; // Module not active, we do nothing + dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); + require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php'; - if ($action == 'BILL_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); + $notify = new Notify($this->db); + $notify->send($action, $object); - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->facture->dir_output . '/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $filepdf=''; // We can't add PDF as it is not generated yet. - $langs->load("other"); - $mesg = $langs->transnoentitiesnoconv("EMailTextInvoiceValidated",$object->ref); - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'facture', $object->id, $filepdf); - } - - elseif ($action == 'ORDER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->commande->dir_output . '/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $filepdf=''; // We can't add PDF as it is not generated yet. - $langs->load("other"); - $mesg = $langs->transnoentitiesnoconv("EMailTextOrderValidated",$object->ref); - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'order', $object->id, $filepdf); - } - - elseif ($action == 'PROPAL_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->propal->dir_output . '/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $filepdf=''; // We can't add PDF as it is not generated yet. - $langs->load("other"); - $mesg = $langs->transnoentitiesnoconv("EMailTextProposalValidated",$object->ref); - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'propal', $object->id, $filepdf); - } - - elseif ($action == 'FICHINTER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->facture->dir_output . '/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $filepdf=''; // We can't add PDF as it is not generated yet. - $langs->load("other"); - $mesg = $langs->transnoentitiesnoconv("EMailTextInterventionValidated",$object->ref); - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'ficheinter', $object->id, $filepdf); - } - - elseif ($action == 'ORDER_SUPPLIER_APPROVE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->fournisseur->dir_output . '/commande/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderApprovedBy",$object->ref,$user->getFullName($langs)); - $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'order_supplier', $object->id, $filepdf); - } - - elseif ($action == 'ORDER_SUPPLIER_REFUSE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->fournisseur->dir_output . '/commande/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $mesg = $langs->transnoentitiesnoconv("Hello").",\n\n"; - $mesg.= $langs->transnoentitiesnoconv("EMailTextOrderRefusedBy",$object->ref,$user->getFullName($langs)); - $mesg.= "\n\n".$langs->transnoentitiesnoconv("Sincerely").".\n\n"; - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'order_supplier', $object->id, $filepdf); - } - elseif ($action == 'SHIPPING_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - - $ref = dol_sanitizeFileName($object->ref); - $filepdf = $conf->expedition->dir_output . '/sending/' . $ref . '/' . $ref . '.pdf'; - if (! file_exists($filepdf)) $filepdf=''; - $mesg = $langs->transnoentitiesnoconv("EMailTextExpeditionValidated",$object->ref); - - - $notify = new Notify($this->db); - $notify->send($action, $object->socid, $mesg, 'expedition', $object->id, $filepdf); - } - - // If not found -/* - else - { - dol_syslog("Trigger '".$this->name."' for action '$action' was ran by ".__FILE__." but no handler found for this action."); - return -1; - } -*/ - return 0; + return 1; } @@ -231,14 +78,14 @@ class InterfaceNotification */ function getListOfManagedEvents() { - global $conf,$langs; + global $conf; $ret=array(); $sql = "SELECT rowid, code, label, description, elementtype"; $sql.= " FROM ".MAIN_DB_PREFIX."c_action_trigger"; $sql.= $this->db->order("elementtype, code"); - dol_syslog("Get list of notifications sql=".$sql); + dol_syslog("Get list of notifications", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { diff --git a/htdocs/core/triggers/interface_90_all_Demo.class.php-NORUN b/htdocs/core/triggers/interface_90_all_Demo.class.php-NORUN index be0ec9346ae..d3abf17501d 100644 --- a/htdocs/core/triggers/interface_90_all_Demo.class.php-NORUN +++ b/htdocs/core/triggers/interface_90_all_Demo.class.php-NORUN @@ -1,6 +1,7 @@ - * Copyright (C) 2005-2014 Regis Houssin +/* Copyright (C) 2005-2014 Laurent Destailleur + * Copyright (C) 2005-2014 Regis Houssin + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -27,615 +28,225 @@ * - Le nom de la classe doit etre InterfaceMytrigger * - Le nom de la propriete name doit etre Mytrigger */ +require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php'; /** * Class of triggers for demo module */ -class InterfaceDemo +class InterfaceDemo extends DolibarrTriggers { - var $db; - - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - function __construct($db) - { - $this->db = $db; - - $this->name = preg_replace('/^Interface/i','',get_class($this)); - $this->family = "demo"; - $this->description = "Triggers of this module are empty functions. They have no effect. They are provided for tutorial purpose only."; - $this->version = 'dolibarr'; // 'development', 'experimental', 'dolibarr' or version - $this->picto = 'technic'; - } - - - /** - * Return name of trigger file - * - * @return string Name of trigger file - */ - function getName() - { - return $this->name; - } - - /** - * Return description of trigger file - * - * @return string Description of trigger file - */ - function getDesc() - { - return $this->description; - } - /** - * Return version of trigger file - * - * @return string Version of trigger file - */ - function getVersion() - { - global $langs; - $langs->load("admin"); + public $family = 'demo'; + public $picto = 'technic'; + public $description = "Triggers of this module are empty functions. They have no effect. They are provided for tutorial purpose only."; + public $version = self::VERSION_DOLIBARR; - if ($this->version == 'development') return $langs->trans("Development"); - elseif ($this->version == 'experimental') return $langs->trans("Experimental"); - elseif ($this->version == 'dolibarr') return DOL_VERSION; - elseif ($this->version) return $this->version; - else return $langs->trans("Unknown"); - } - - /** - * Function called when a Dolibarrr business event is done. - * All functions "run_trigger" are triggered if file is inside directory htdocs/core/triggers + /** + * Function called when a Dolibarrr business event is done. + * All functions "runTrigger" are triggered if file is inside directory htdocs/core/triggers or htdocs/module/code/triggers (and declared) * - * @param string $action Event action code - * @param Object $object Object - * @param User $user Object user - * @param Translate $langs Object langs - * @param conf $conf Object conf - * @return int <0 if KO, 0 if no triggered ran, >0 if OK + * @param string $action Event action code + * @param Object $object Object + * @param User $user Object user + * @param Translate $langs Object langs + * @param conf $conf Object conf + * @return int <0 if KO, 0 if no triggered ran, >0 if OK */ - function run_trigger($action,$object,$user,$langs,$conf) + public function runTrigger($action, $object, User $user, Translate $langs, Conf $conf) { - // Put here code you want to execute when a Dolibarr business events occurs. + // Put here code you want to execute when a Dolibarr business events occurs. // Data and type of action are stored into $object and $action - - // Users - if ($action == 'USER_LOGIN') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_UPDATE_SESSION') - { - // Warning: To increase performances, this action is triggered only if - // constant MAIN_ACTIVATE_UPDATESESSIONTRIGGER is set to 1. - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_CREATE_FROM_CONTACT') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_NEW_PASSWORD') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_ENABLEDISABLE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_LOGOUT') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_SETINGROUP') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'USER_REMOVEFROMGROUP') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + + switch ($action) { + + // Users + case 'USER_LOGIN': + case 'USER_UPDATE_SESSION': + case 'USER_CREATE': + case 'USER_CREATE_FROM_CONTACT': + case 'USER_LOGIN': + // Warning: To increase performances, this action is triggered only if + // constant MAIN_ACTIVATE_UPDATESESSIONTRIGGER is set to 1. + case 'USER_UPDATE_SESSION': + case 'USER_CREATE': + case 'USER_CREATE_FROM_CONTACT': + case 'USER_MODIFY': + case 'USER_NEW_PASSWORD': + case 'USER_ENABLEDISABLE': + case 'USER_DELETE': + case 'USER_LOGOUT': + case 'USER_SETINGROUP': + case 'USER_REMOVEFROMGROUP': + + // Actions + case 'ACTION_MODIFY': + case 'ACTION_CREATE': + case 'ACTION_DELETE': - // Groups - elseif ($action == 'GROUP_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'GROUP_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'GROUP_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Companies - elseif ($action == 'COMPANY_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'COMPANY_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'COMPANY_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Groups + case 'GROUP_CREATE': + case 'GROUP_MODIFY': + case 'GROUP_DELETE': - // Contacts - elseif ($action == 'CONTACT_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTACT_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTACT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Companies + case 'COMPANY_CREATE': + case 'COMPANY_MODIFY': + case 'COMPANY_DELETE': - // Products - elseif ($action == 'PRODUCT_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PRODUCT_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PRODUCT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Contacts + case 'CONTACT_CREATE': + case 'CONTACT_MODIFY': + case 'CONTACT_DELETE': + case 'CONTACT_ENABLEDISABLE': - // Customer orders - elseif ($action == 'ORDER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_CLONE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SENTBYMAIL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_CLASSIFY_BILLED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_INSERT') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Products + case 'PRODUCT_CREATE': + case 'PRODUCT_MODIFY': + case 'PRODUCT_DELETE': + case 'PRODUCT_PRICE_MODIFY': - // Supplier orders - elseif ($action == 'ORDER_SUPPLIER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_CLONE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_APPROVE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_REFUSE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_CANCEL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_SENTBYMAIL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'ORDER_SUPPLIER_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_SUPPLIER_DISPATCH') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_SUPPLIER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEORDER_SUPPLIER_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + //Stock mouvement + case 'STOCK_MOVEMENT': - // Proposals - elseif ($action == 'PROPAL_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_CLONE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_SENTBYMAIL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_CLOSE_SIGNED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_CLOSE_REFUSED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROPAL_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEPROPAL_INSERT') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEPROPAL_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEPROPAL_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + //MYECMDIR + case 'MYECMDIR_DELETE': + case 'MYECMDIR_CREATE': + case 'MYECMDIR_MODIFY': - // Contracts - elseif ($action == 'CONTRACT_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTRACT_ACTIVATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTRACT_CANCEL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTRACT_CLOSE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CONTRACT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINECONTRACT_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINECONTRACT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Customer orders + case 'ORDER_CREATE': + case 'ORDER_CLONE': + case 'ORDER_VALIDATE': + case 'ORDER_DELETE': + case 'ORDER_SENTBYMAIL': + case 'ORDER_CLASSIFY_BILLED': + case 'LINEORDER_INSERT': + case 'LINEORDER_UPDATE': + case 'LINEORDER_DELETE': - // Bills - elseif ($action == 'BILL_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_CLONE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_UNVALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_SENTBYMAIL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_CANCEL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_PAYED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_INSERT') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Supplier orders + case 'ORDER_SUPPLIER_CREATE': + case 'ORDER_SUPPLIER_CLONE': + case 'ORDER_SUPPLIER_VALIDATE': + case 'ORDER_SUPPLIER_DELETE': + case 'ORDER_SUPPLIER_APPROVE': + case 'ORDER_SUPPLIER_REFUSE': + case 'ORDER_SUPPLIER_CANCEL': + case 'ORDER_SUPPLIER_SENTBYMAIL': + case 'LINEORDER_SUPPLIER_DISPATCH': + case 'LINEORDER_SUPPLIER_CREATE': + case 'LINEORDER_SUPPLIER_UPDATE': - //Supplier Bill - elseif ($action == 'BILL_SUPPLIER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_SUPPLIER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_SUPPLIER_PAYED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_SUPPLIER_UNPAYED') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'BILL_SUPPLIER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_SUPPLIER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_SUPPLIER_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEBILL_SUPPLIER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Payments - elseif ($action == 'PAYMENT_CUSTOMER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PAYMENT_SUPPLIER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PAYMENT_ADD_TO_BANK') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PAYMENT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Proposals + case 'PROPAL_CREATE': + case 'PROPAL_CLONE': + case 'PROPAL_MODIFY': + case 'PROPAL_VALIDATE': + case 'PROPAL_SENTBYMAIL': + case 'PROPAL_CLOSE_SIGNED': + case 'PROPAL_CLOSE_REFUSED': + case 'PROPAL_DELETE': + case 'LINEPROPAL_INSERT': + case 'LINEPROPAL_UPDATE': + case 'LINEPROPAL_DELETE': - // Interventions - elseif ($action == 'FICHINTER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'FICHINTER_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'FICHINTER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'FICHINTER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEFICHINTER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEFICHINTER_UPDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'LINEFICHINTER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Members - elseif ($action == 'MEMBER_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_SUBSCRIPTION') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_NEW_PASSWORD') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_RESILIATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'MEMBER_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Categories - elseif ($action == 'CATEGORY_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CATEGORY_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'CATEGORY_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Projects - elseif ($action == 'PROJECT_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROJECT_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROJECT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'PROJECT_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Project tasks - elseif ($action == 'TASK_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'TASK_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'TASK_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Task time spent - elseif ($action == 'TASK_TIMESPENT_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'TASK_TIMESPENT_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'TASK_TIMESPENT_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - - // Shipping - elseif ($action == 'SHIPPING_CREATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'SHIPPING_MODIFY') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'SHIPPING_VALIDATE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'SHIPPING_SENTBYMAIL') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'SHIPPING_DELETE') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } - elseif ($action == 'SHIPPING_BUILDDOC') - { - dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); - } + // Contracts + case 'CONTRACT_CREATE': + case 'CONTRACT_ACTIVATE': + case 'CONTRACT_CANCEL': + case 'CONTRACT_CLOSE': + case 'CONTRACT_DELETE': + case 'LINECONTRACT_CREATE': + case 'LINECONTRACT_UPDATE': + case 'LINECONTRACT_DELETE': - return 0; - } + // Bills + case 'BILL_CREATE': + case 'BILL_CLONE': + case 'BILL_MODIFY': + case 'BILL_VALIDATE': + case 'BILL_UNVALIDATE': + case 'BILL_SENTBYMAIL': + case 'BILL_CANCEL': + case 'BILL_DELETE': + case 'BILL_PAYED': + case 'LINEBILL_INSERT': + case 'LINEBILL_UPDATE': + case 'LINEBILL_DELETE': + + //Supplier Bill + case 'BILL_SUPPLIER_CREATE': + case 'BILL_SUPPLIER_UPDATE': + case 'BILL_SUPPLIER_DELETE': + case 'BILL_SUPPLIER_PAYED': + case 'BILL_SUPPLIER_UNPAYED': + case 'BILL_SUPPLIER_VALIDATE': + case 'LINEBILL_SUPPLIER_CREATE': + case 'LINEBILL_SUPPLIER_UPDATE': + case 'LINEBILL_SUPPLIER_DELETE': + + // Payments + case 'PAYMENT_CUSTOMER_CREATE': + case 'PAYMENT_SUPPLIER_CREATE': + case 'PAYMENT_ADD_TO_BANK': + case 'PAYMENT_DELETE': + + //Donation + case 'DON_CREATE': + case 'DON_UPDATE': + case 'DON_DELETE': + + // Interventions + case 'FICHINTER_CREATE': + case 'FICHINTER_MODIFY': + case 'FICHINTER_VALIDATE': + case 'FICHINTER_DELETE': + case 'LINEFICHINTER_CREATE': + case 'LINEFICHINTER_UPDATE': + case 'LINEFICHINTER_DELETE': + + // Members + case 'MEMBER_CREATE': + case 'MEMBER_VALIDATE': + case 'MEMBER_SUBSCRIPTION': + case 'MEMBER_MODIFY': + case 'MEMBER_NEW_PASSWORD': + case 'MEMBER_RESILIATE': + case 'MEMBER_DELETE': + + // Categories + case 'CATEGORY_CREATE': + case 'CATEGORY_MODIFY': + case 'CATEGORY_DELETE': + + // Projects + case 'PROJECT_CREATE': + case 'PROJECT_MODIFY': + case 'PROJECT_DELETE': + + // Project tasks + case 'TASK_CREATE': + case 'TASK_MODIFY': + case 'TASK_DELETE': + + // Task time spent + case 'TASK_TIMESPENT_CREATE': + case 'TASK_TIMESPENT_MODIFY': + case 'TASK_TIMESPENT_DELETE': + + // Shipping + case 'SHIPPING_CREATE': + case 'SHIPPING_MODIFY': + case 'SHIPPING_VALIDATE': + case 'SHIPPING_SENTBYMAIL': + case 'SHIPPING_DELETE': + dol_syslog("Trigger '".$this->name."' for action '$action' launched by ".__FILE__.". id=".$object->id); + break; + + } + + return 0; + } } -?> diff --git a/htdocs/cron/admin/index.html b/htdocs/cron/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cron/card.php b/htdocs/cron/card.php index 0a68ca211b9..17704972170 100644 --- a/htdocs/cron/card.php +++ b/htdocs/cron/card.php @@ -278,7 +278,7 @@ if ($action == 'execute'){ if (empty($object->status) && $action != 'create') { - dol_htmloutput_mesg($langs->trans("CronTaskInactive"),'','warning',1); + setEventMessage($langs->trans("CronTaskInactive"), 'warnings'); } if (($action=="create") || ($action=="edit")) diff --git a/htdocs/cron/class/cronjob.class.php b/htdocs/cron/class/cronjob.class.php index f1fc788a198..aaa69ec7f42 100644 --- a/htdocs/cron/class/cronjob.class.php +++ b/htdocs/cron/class/cronjob.class.php @@ -96,7 +96,7 @@ class Cronjob extends CommonObject $error=0; $now=dol_now(); - + // Clean parameters if (isset($this->label)) $this->label=trim($this->label); @@ -224,7 +224,7 @@ class Cronjob extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -309,7 +309,7 @@ class Cronjob extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."cronjob as t"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -356,7 +356,6 @@ class Cronjob extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -429,7 +428,7 @@ class Cronjob extends CommonObject $sql.= " WHERE ".implode(' AND ',$sqlwhere); } - dol_syslog(get_class($this)."::fetch_all sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_all", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -490,7 +489,6 @@ class Cronjob extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -503,7 +501,7 @@ class Cronjob extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -609,7 +607,7 @@ class Cronjob extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -683,7 +681,7 @@ class Cronjob extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."cronjob"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } } @@ -816,7 +814,7 @@ class Cronjob extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."cronjob as f"; $sql.= " WHERE f.rowid = ".$this->id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -836,7 +834,6 @@ class Cronjob extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } diff --git a/htdocs/cron/class/index.html b/htdocs/cron/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cron/index.html b/htdocs/cron/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/cron/list.php b/htdocs/cron/list.php index 95dd669d023..3c2844f3fe4 100644 --- a/htdocs/cron/list.php +++ b/htdocs/cron/list.php @@ -64,7 +64,7 @@ $pageprev = $page - 1; $pagenext = $page + 1; // Do we click on purge search criteria ? -if (GETPOST("button_removefilter")) +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers { $search_label=''; $status=-1; @@ -165,17 +165,17 @@ print ''; print ''; print ''; $arg_url='&page='.$page.'&status='.$status.'&search_label='.$search_label; -print_liste_field_titre($langs->trans("CronLabel"),$_SERVEUR['PHP_SELF'],"t.label","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronLabel"),$_SERVER["PHP_SELF"],"t.label","",$arg_url,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("CronTask"),'','',"",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronDtStart"),$_SERVEUR['PHP_SELF'],"t.datestart","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronDtEnd"),$_SERVEUR['PHP_SELF'],"t.dateend","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronDtLastLaunch"),$_SERVEUR['PHP_SELF'],"t.datelastrun","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronDtNextLaunch"),$_SERVEUR['PHP_SELF'],"t.datenextrun","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronDtStart"),$_SERVER["PHP_SELF"],"t.datestart","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronDtEnd"),$_SERVER["PHP_SELF"],"t.dateend","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronDtLastLaunch"),$_SERVER["PHP_SELF"],"t.datelastrun","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronDtNextLaunch"),$_SERVER["PHP_SELF"],"t.datenextrun","",$arg_url,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("CronFrequency"),'',"","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronNbRun"),$_SERVEUR['PHP_SELF'],"t.nbrun","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronLastResult"),$_SERVEUR['PHP_SELF'],"t.lastresult","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("CronLastOutput"),$_SERVEUR['PHP_SELF'],"t.lastoutput","",$arg_url,'',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("Enabled"),$_SERVEUR['PHP_SELF'],"t.status","",$arg_url,'align="center"',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronNbRun"),$_SERVER["PHP_SELF"],"t.nbrun","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronLastResult"),$_SERVER["PHP_SELF"],"t.lastresult","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("CronLastOutput"),$_SERVER["PHP_SELF"],"t.lastoutput","",$arg_url,'',$sortfield,$sortorder); +print_liste_field_titre($langs->trans("Enabled"),$_SERVER["PHP_SELF"],"t.status","",$arg_url,'align="center"',$sortfield,$sortorder); print ''; print ''; diff --git a/htdocs/ecm/ajax/index.html b/htdocs/ecm/ajax/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/ecm/class/ecmdirectory.class.php b/htdocs/ecm/class/ecmdirectory.class.php index ea29d822102..6c0de13d15b 100644 --- a/htdocs/ecm/class/ecmdirectory.class.php +++ b/htdocs/ecm/class/ecmdirectory.class.php @@ -142,7 +142,7 @@ class EcmDirectory // extends CommonObject $sql.= " '".$this->fk_user_c."'"; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -152,12 +152,10 @@ class EcmDirectory // extends CommonObject $result=dol_mkdir($dir); if ($result < 0) { $error++; $this->error="ErrorFailedToCreateDir"; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('MYECMDIR_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('MYECMDIR_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers if (! $error) { @@ -173,7 +171,6 @@ class EcmDirectory // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -187,7 +184,7 @@ class EcmDirectory // extends CommonObject * @param int $notrigger 0=no, 1=yes (no update trigger) * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; @@ -210,23 +207,20 @@ class EcmDirectory // extends CommonObject $sql.= " description='".$this->db->escape($this->description)."'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->error="Error ".$this->db->lasterror(); - dol_syslog("EcmDirectories::update ".$this->error, LOG_ERR); } if (! $error && ! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('MYECMDIR_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('MYECMDIR_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -257,12 +251,11 @@ class EcmDirectory // extends CommonObject $sql.= " cachenbofdoc = cachenbofdoc ".$sign." 1"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::changeNbOfFiles sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::changeNbOfFiles", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::changeNbOfFiles ".$this->error, LOG_ERR); return -1; } @@ -291,7 +284,7 @@ class EcmDirectory // extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."ecm_directories as t"; $sql.= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -318,7 +311,6 @@ class EcmDirectory // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -348,15 +340,25 @@ class EcmDirectory // extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."ecm_directories"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $this->db->rollback(); $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); return -2; } + else + { + // Call trigger + $result=$this->call_trigger('MYECMDIR_DELETE',$user); + if ($result < 0) + { + $this->db->rollback(); + return -2; + } + // End call triggers + } if ($mode != 'databaseonly') { @@ -376,16 +378,6 @@ class EcmDirectory // extends CommonObject $error++; } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('MYECMDIR_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - } - if (! $error) return 1; else return -1; } @@ -499,7 +491,7 @@ class EcmDirectory // extends CommonObject $sql.= " WHERE fk_parent != 0"; $sql.= " AND entity = ".$conf->entity; - dol_syslog(get_class($this)."::load_motherof sql=".$sql); + dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -519,7 +511,7 @@ class EcmDirectory // extends CommonObject /** - * Reconstruit l'arborescence des categories sous la forme d'un tableau + * Reconstruit l'arborescence des categories sous la forme d'un tableau à partir de la base de donnée * Renvoi un tableau de tableau('id','id_mere',...) trie selon arbre et avec: * id Id de la categorie * id_mere Id de la categorie mere @@ -563,7 +555,7 @@ class EcmDirectory // extends CommonObject $sql.= " AND c.entity = ".$conf->entity; $sql.= " ORDER BY c.label, c.rowid"; - dol_syslog(get_class($this)."::get_full_arbo sql=".$sql); + dol_syslog(get_class($this)."::get_full_arbo", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -688,7 +680,7 @@ class EcmDirectory // extends CommonObject $sql.= " WHERE entity = ".$conf->entity; } - dol_syslog(get_class($this)."::refreshcachenboffile sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::refreshcachenboffile", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -698,9 +690,41 @@ class EcmDirectory // extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::refreshcachenboffile ".$this->error, LOG_ERR); return -1; } } + /** + * Call trigger based on this instance + * + * NB: Error from trigger are stacked in errors + * NB2: if trigger fail, action should be canceled. + * NB3: Should be deleted if EcmDirectory extend CommonObject + * + * @param string $trigger_name trigger's name to execute + * @param User $user Object user + * @return int Result of run_triggers + */ + function call_trigger($trigger_name, $user) + { + global $langs,$conf; + + include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; + $interface=new Interfaces($this->db); + $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf); + if ($result < 0) { + if (!empty($this->errors)) + { + $this->errors=array_merge($this->errors,$interface->errors); + } + else + { + $this->errors=$interface->errors; + } + } + return $result; + + } + + } diff --git a/htdocs/ecm/class/index.html b/htdocs/ecm/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/ecm/docother.php b/htdocs/ecm/docother.php index f219e352c64..d1fda6b793a 100644 --- a/htdocs/ecm/docother.php +++ b/htdocs/ecm/docother.php @@ -104,8 +104,6 @@ print_fiche_titre($langs->trans("ECMAutoOrg")); //$head = societe_prepare_head($societe); -//dol_fiche_head($head, 'document', $societe->nom); - /* * Confirmation de la suppression d'une ligne produit @@ -113,7 +111,7 @@ print_fiche_titre($langs->trans("ECMAutoOrg")); if ($_GET['action'] == 'delete_file') { print $form->formconfirm($_SERVER["PHP_SELF"].'?socid='.$socid.'&urlfile='.urldecode($_GET["urlfile"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile'); - + } // Construit liste des fichiers diff --git a/htdocs/ecm/index.php b/htdocs/ecm/index.php index e46011c45ba..8f9bd5573bf 100644 --- a/htdocs/ecm/index.php +++ b/htdocs/ecm/index.php @@ -110,8 +110,6 @@ if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC)) $resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0, 0, $_FILES['userfile']['error']); if (is_numeric($resupload) && $resupload > 0) { - //$mesg = '
'.$langs->trans("FileTransferComplete").'
'; - //print_r($_FILES); $result=$ecmdir->changeNbOfFiles('+'); } else @@ -134,7 +132,7 @@ if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC)) else { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorFailToCreateDir",$upload_dir).'
'; + setEventMessage($langs->trans("ErrorFailToCreateDir",$upload_dir), 'errors'); } } } @@ -156,7 +154,7 @@ if ($action == 'add' && $user->rights->ecm->setup) } else { - $mesg='
Error '.$langs->trans($ecmdir->error).'
'; + setEventMessage('Error '.$langs->trans($ecmdir->error), 'errors'); $action = "create"; } @@ -198,7 +196,7 @@ if ($action == 'confirm_deletefile') if ($action == 'confirm_deletesection' && GETPOST('confirm') == 'yes') { $result=$ecmdir->delete($user); - $mesg = '
'.$langs->trans("ECMSectionWasRemoved", $ecmdir->label).'
'; + setEventMessage($langs->trans("ECMSectionWasRemoved", $ecmdir->label)); clearstatcache(); } @@ -324,7 +322,6 @@ if ($action == 'refreshmanual') $dirtotest=$conf->ecm->dir_output.'/'.$dirdesc['fullrelativename']; if (! dol_is_dir($dirtotest)) { - $mesg.=$dirtotest." not found onto disk. We delete from database dir with id=".$dirdesc['id']."
\n"; $ecmdirtmp->id=$dirdesc['id']; $ecmdirtmp->delete($user,'databaseonly'); //exit; @@ -440,9 +437,6 @@ if ($action == 'delete' && empty($conf->use_javascript_ajax)) } -dol_htmloutput_mesg($mesg); - - if (! empty($conf->use_javascript_ajax)) $classviewhide='hidden'; else $classviewhide='visible'; diff --git a/htdocs/ecm/index_auto.php b/htdocs/ecm/index_auto.php index 9c4ab7e0e2f..7d0fc5c64bf 100644 --- a/htdocs/ecm/index_auto.php +++ b/htdocs/ecm/index_auto.php @@ -110,8 +110,6 @@ if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC)) $resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0, 0, $_FILES['userfile']['error']); if (is_numeric($resupload) && $resupload > 0) { - //$mesg = '
'.$langs->trans("FileTransferComplete").'
'; - //print_r($_FILES); $result=$ecmdir->changeNbOfFiles('+'); } else @@ -134,7 +132,7 @@ if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC)) else { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorFailToCreateDir",$upload_dir).'
'; + setEventMessage($langs->trans("ErrorFailToCreateDir",$upload_dir), 'errors'); } } } @@ -156,7 +154,8 @@ if ($action == 'add' && $user->rights->ecm->setup) } else { - $mesg='
Error '.$langs->trans($ecmdir->error).'
'; + //TODO: Translate + setEventMessage('Error '.$langs->trans($ecmdir->error), 'errors'); $action = "create"; } @@ -198,7 +197,7 @@ if ($action == 'confirm_deletefile') if ($action == 'confirm_deletesection' && GETPOST('confirm') == 'yes') { $result=$ecmdir->delete($user); - $mesg = '
'.$langs->trans("ECMSectionWasRemoved", $ecmdir->label).'
'; + setEventMessage($langs->trans("ECMSectionWasRemoved", $ecmdir->label)); clearstatcache(); } @@ -324,7 +323,6 @@ if ($action == 'refreshmanual') $dirtotest=$conf->ecm->dir_output.'/'.$dirdesc['fullrelativename']; if (! dol_is_dir($dirtotest)) { - $mesg.=$dirtotest." not found onto disk. We delete from database dir with id=".$dirdesc['id']."
\n"; $ecmdirtmp->id=$dirdesc['id']; $ecmdirtmp->delete($user,'databaseonly'); //exit; @@ -411,6 +409,9 @@ if (! empty($conf->global->ECM_AUTO_TREE_ENABLED)) if (! empty($conf->fournisseur->enabled)) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'invoice_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersInvoices"), 'desc'=>$langs->trans("ECMDocsByInvoices")); } if (! empty($conf->tax->enabled)) { $langs->load("compta"); $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'tax', 'test'=>$conf->tax->enabled, 'label'=>$langs->trans("SocialContributions"), 'desc'=>$langs->trans("ECMDocsBySocialContributions")); } if (! empty($conf->projet->enabled)) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'project', 'test'=>$conf->projet->enabled, 'label'=>$langs->trans("Projects"), 'desc'=>$langs->trans("ECMDocsByProjects")); } + if (! empty($conf->ficheinter->enabled)) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'fichinter', 'test'=>$conf->ficheinter->enabled, 'label'=>$langs->trans("Interventions"), 'desc'=>$langs->trans("ECMDocsByInterventions")); } + $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'user', 'test'=>1, 'label'=>$langs->trans("Users"), 'desc'=>$langs->trans("ECMDocsByUsers")); + } print_fiche_titre($langs->trans("ECMArea").' - '.$langs->trans("ECMFileManager")); @@ -436,9 +437,6 @@ if ($action == 'delete' && empty($conf->use_javascript_ajax)) } -dol_htmloutput_mesg($mesg); - - if (! empty($conf->use_javascript_ajax)) $classviewhide='hidden'; else $classviewhide='visible'; diff --git a/htdocs/ecm/tpl/enablefiletreeajax.tpl.php b/htdocs/ecm/tpl/enablefiletreeajax.tpl.php index 301fa5f955b..b348cb03c72 100644 --- a/htdocs/ecm/tpl/enablefiletreeajax.tpl.php +++ b/htdocs/ecm/tpl/enablefiletreeajax.tpl.php @@ -42,7 +42,7 @@ $(document).ready(function() { }, // Called if we click on a dir (not a file) function(elem) { - id=elem.attr('id').substr(12); + id=elem.attr('id').substr(12); // We get id that is 'fmdirlia_id_xxx' (id we want is xxx) jQuery("#formuserfile_section_dir").val(elem.attr('rel')); jQuery("#formuserfile_section_id").val(id); jQuery('#formuserfile').show(); @@ -65,6 +65,9 @@ $(document).ready(function() { function loadandshowpreview(filedirname,section) { //alert('filedirname='+filedirname); + //console.log(filedirname); + //console.log(section); + $('#ecmfileview').empty(); var url = '?action=preview&module=ecm§ion='+section+'&file='+urlencode(filedirname); diff --git a/htdocs/ecm/tpl/index.html b/htdocs/ecm/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/expedition/fiche.php b/htdocs/expedition/card.php similarity index 91% rename from htdocs/expedition/fiche.php rename to htdocs/expedition/card.php index c11c1d549a9..6ee45778d18 100644 --- a/htdocs/expedition/fiche.php +++ b/htdocs/expedition/card.php @@ -7,6 +7,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2013 Marcos García * Copyright (C) 2014 Cedric GROSS + * Copyright (C) 2014 Francis Appels * * 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 @@ -23,7 +24,7 @@ */ /** - * \file htdocs/expedition/fiche.php + * \file htdocs/expedition/card.php * \ingroup expedition * \brief Fiche descriptive d'une expedition */ @@ -81,13 +82,31 @@ if ($id > 0 || ! empty($ref)) } // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('expeditioncard')); +$hookmanager->initHooks(array('expeditioncard','globalcard')); + /* * Actions */ + +$warehousecanbeselectedlater=1; +if (($action == 'create') || ($action == 'add')) +{ + if (! empty($conf->productbatch->enabled)) + { + if (! (GETPOST('entrepot_id','int') > 0)) + { + $langs->load("errors"); + setEventMessage($langs->trans("WarehouseMustBeSelectedAtFirstStepWhenProductBatchModuleOn"),'errors'); + header("Location: ".DOL_URL_ROOT.'/expedition/shipment.php?id='.$id); + exit; + } + } +} + $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 ($action == 'add') { @@ -162,7 +181,7 @@ if ($action == 'add') { $qty = "qtyl".$i; if (! isset($batch_line[$i])) { - if (GETPOST($qty,'int') > 0) + if (GETPOST($qty,'int') > 0 || (GETPOST($qty,'int') == 0 && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS)) { $ent = "entl".$i; $idl = "idl".$i; @@ -207,7 +226,7 @@ if ($action == 'add') if (! $error) { $db->commit(); - header("Location: fiche.php?id=".$object->id); + header("Location: card.php?id=".$object->id); exit; } else @@ -226,7 +245,7 @@ else if ($action == 'create_delivery' && $conf->livraison_bon->enabled && $user- $result = $object->create_delivery($user); if ($result > 0) { - header("Location: ".DOL_URL_ROOT.'/livraison/fiche.php?id='.$result); + header("Location: ".DOL_URL_ROOT.'/livraison/card.php?id='.$result); exit; } else @@ -241,25 +260,32 @@ else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->exped $result = $object->valid($user); - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang=GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $ret=$object->fetch($id); // Reload to get new records - $result=expedition_pdf_create($db,$object,$object->modelpdf,$outputlangs); - } if ($result < 0) { - dol_print_error($db,$result); - exit; + $langs->load("errors"); + setEventMessage($langs->trans($object->error),'errors'); + } + else + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'shipping'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } } } @@ -328,7 +354,7 @@ else if ($action == 'settrackingnumber' || $action == 'settrackingurl' { if ($object->update($user) >= 0) { - header("Location: fiche.php?id=".$object->id); + header("Location: card.php?id=".$object->id); exit; } setEventMessage($object->error,'errors'); @@ -354,7 +380,7 @@ else if ($action == 'builddoc') // En get ou en post $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } - $result=expedition_pdf_create($db,$object,$object->modelpdf,$outputlangs); + $result = $object->generateDocument($object->modelpdf, $outputlangs); if ($result <= 0) { dol_print_error($db,$result); @@ -453,12 +479,13 @@ if ($action == 'send' && ! GETPOST('addfile','alpha') && ! GETPOST('removedfile' if (dol_strlen(GETPOST('subject','alpha'))) $subject=GETPOST('subject','alpha'); else $subject = $langs->transnoentities('Shipping').' '.$object->ref; $actiontypecode='AC_SHIP'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); } @@ -583,7 +610,7 @@ if ($action == 'create') print_fiche_titre($langs->trans("CreateASending")); if (! $origin) { - $mesg='
'.$langs->trans("ErrorBadParameters").'
'; + setEventMessage($langs->trans("ErrorBadParameters"),'errors'); } dol_htmloutput_mesg($mesg); @@ -626,11 +653,11 @@ if ($action == 'create') print '
'; print "\n"; @@ -761,10 +788,13 @@ if ($action == 'create') print ''; if (! empty($conf->stock->enabled)) { - if (empty($conf->productbatch->enabled)) { - print ''; - } else { - print ''; + if (empty($conf->productbatch->enabled)) + { + print ''; + } + else + { + print ''; } } print "\n"; @@ -818,7 +848,7 @@ if ($action == 'create') print ''; } else - { + { print ""; } } } - } else { + } + else + { print ''; $subj=0; print ''; - foreach ($product->stock_warehouse[GETPOST('entrepot_id','int')]->detail_batch as $dbatch) { + foreach ($product->stock_warehouse[$warehouse_id]->detail_batch as $dbatch) + { //var_dump($dbatch); $substock=$dbatch->qty +0 ; print ''; print ''; } @@ -1011,7 +1064,7 @@ if ($action == 'create') $numcontrat=$formcontract->select_contract($soc->id,GETPOST('contratid','int'),'contratid',0,1); if ($numcontrat==0) { - print '   '.$langs->trans("AddContract").''; + print '   '.$langs->trans("AddContract").''; } print ''; } @@ -1111,14 +1164,15 @@ else if ($id > 0 || ! empty($ref)) dol_fiche_head($head, 'card', $langs->trans("InterventionCard"), 0, 'intervention'); - // Confirmation de la suppression de la fiche d'intervention + $formconfirm=''; + + // Confirm deletion of intervention if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteIntervention'), $langs->trans('ConfirmDeleteIntervention'), 'confirm_delete','',0,1); - + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteIntervention'), $langs->trans('ConfirmDeleteIntervention'), 'confirm_delete','',0,1); } - // Confirmation validation + // Confirm validation if ($action == 'validate') { // on verifie si l'objet est en numerotation provisoire @@ -1129,7 +1183,7 @@ else if ($id > 0 || ! empty($ref)) if (empty($numref)) { $error++; - dol_htmloutput_errors($object->error); + setEventMessage($object->error, 'errors'); } } else @@ -1138,29 +1192,34 @@ else if ($id > 0 || ! empty($ref)) } $text=$langs->trans('ConfirmValidateIntervention',$numref); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateIntervention'), $text, 'confirm_validate','',0,1); - + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateIntervention'), $text, 'confirm_validate','',1,1); } - // Confirmation de la validation de la fiche d'intervention + // Confirm back to draft if ($action == 'modify') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ModifyIntervention'), $langs->trans('ConfirmModifyIntervention'), 'confirm_modify','',0,1); - + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ModifyIntervention'), $langs->trans('ConfirmModifyIntervention'), 'confirm_modify','',0,1); } - // Confirmation de la suppression d'une ligne d'intervention + // Confirm deletion of line if ($action == 'ask_deleteline') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&line_id='.GETPOST('line_id','int'), $langs->trans('DeleteInterventionLine'), $langs->trans('ConfirmDeleteInterventionLine'), 'confirm_deleteline','',0,1); - + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&line_id='.$lineid, $langs->trans('DeleteInterventionLine'), $langs->trans('ConfirmDeleteInterventionLine'), 'confirm_deleteline','',0,1); } + if (!$formconfirm) + { + $parameters=array('lineid'=>$lineid); + $formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + } + + // Print form confirm + print $formconfirm; + print ''; print ''; if ($action == 'edit_extras') print ''; if ($action == 'contrat') print ''; - print ''; print '
'; if ($origin == 'commande' && ! empty($conf->commande->enabled)) { - print $langs->trans("RefOrder").''.img_object($langs->trans("ShowOrder"),'order').' '.$object->ref; + print $langs->trans("RefOrder").''.img_object($langs->trans("ShowOrder"),'order').' '.$object->ref; } if ($origin == 'propal' && ! empty($conf->propal->enabled)) { - print $langs->trans("RefProposal").''.img_object($langs->trans("ShowProposal"),'propal').' '.$object->ref; + print $langs->trans("RefProposal").''.img_object($langs->trans("ShowProposal"),'propal').' '.$object->ref; } print '
'.$langs->trans("Warehouse").' / '.$langs->trans("Stock").''.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' / '.$langs->trans("Stock").''.$langs->trans("Warehouse").' ('.$langs->trans("Stock").')'.$langs->trans("Warehouse").' / '.$langs->trans("Batch").' ('.$langs->trans("Stock").')
"; if ($type==1) $text = img_object($langs->trans('Service'),'service'); else $text = img_object($langs->trans('Product'),'product'); @@ -851,17 +881,19 @@ if ($action == 'create') $quantityAsked = $line->qty; $quantityToBeDelivered = $quantityAsked - $quantityDelivered; + $warehouse_id = GETPOST('entrepot_id','int'); + $defaultqty=0; - if (GETPOST('entrepot_id','int') > 0) + if ($warehouse_id > 0) { //var_dump($product); - $stock = $product->stock_warehouse[GETPOST('entrepot_id','int')]->real; + $stock = $product->stock_warehouse[$warehouse_id]->real; $stock+=0; // Convertit en numerique $defaultqty=min($quantityToBeDelivered, $stock); if (($line->product_type == 1 && empty($conf->global->STOCK_SUPPORTS_SERVICES)) || $defaultqty < 0) $defaultqty=0; } - if (empty($conf->productbatch->enabled) || ! ($product->hasbatch() and is_object($product->stock_warehouse[GETPOST('entrepot_id','int')]))) + if (empty($conf->productbatch->enabled) || ! ($product->hasbatch() and is_object($product->stock_warehouse[$warehouse_id]))) { // Quantity to send print ''; @@ -882,14 +914,14 @@ if ($action == 'create') // Show warehouse combo list $ent = "entl".$indiceAsked; $idl = "idl".$indiceAsked; - $tmpentrepot_id = is_numeric(GETPOST($ent,'int'))?GETPOST($ent,'int'):GETPOST('entrepot_id','int'); + $tmpentrepot_id = is_numeric(GETPOST($ent,'int'))?GETPOST($ent,'int'):$warehouse_id; print $formproduct->selectWarehouses($tmpentrepot_id,'entl'.$indiceAsked,'',1,0,$line->fk_product); - if ($tmpentrepot_id > 0 && $tmpentrepot_id == GETPOST('entrepot_id','int')) + if ($tmpentrepot_id > 0 && $tmpentrepot_id == $warehouse_id) { //print $stock.' '.$quantityToBeDelivered; if ($stock < $quantityToBeDelivered) { - print ' '.img_warning($langs->trans("StockTooLow")); // Stock too low for entrepot_id but we may have change warehouse + print ' '.img_warning($langs->trans("StockTooLow")); // Stock too low for this $warehouse_id but you can change warehouse } } } @@ -918,17 +950,20 @@ if ($action == 'create') $img=img_warning($langs->trans("StockTooLow")); } print "
      -> - ".$value['fullpath']." + ".$value['fullpath']." (".$value['nb'].") ".$value['nb_total']."   ".$value['stock']." ".$img."
'; @@ -936,8 +971,13 @@ if ($action == 'create') print ''; + + $staticwarehouse=new Entrepot($db); + $staticwarehouse->fetch($warehouse_id); + print $staticwarehouse->getNomUrl(0).' / '; + print ''; - print $langs->trans("DetailBatchFormat", dol_print_date($dbatch->eatby,"day"), dol_print_date($dbatch->sellby,"day"), $dbatch->batch, $dbatch->qty); + print $langs->trans("DetailBatchFormat", $dbatch->batch, dol_print_date($dbatch->eatby,"day"), dol_print_date($dbatch->sellby,"day"), $dbatch->qty); if ($defaultqty<=0) { $defaultqty=0; } else { @@ -1032,7 +1072,7 @@ else if ($id || $ref) } /* * Confirmation de l'annulation - */ + */ if ($action == 'annuler') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id,$langs->trans('CancelSending'),$langs->trans("ConfirmCancelSending",$object->ref),'confirm_cancel','',0,1); @@ -1079,7 +1119,7 @@ else if ($id || $ref) print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; @@ -1425,16 +1465,30 @@ else if ($id || $ref) $entrepot->fetch($lines[$i]->entrepot_id); print $entrepot->getNomUrl(1); } + else if (count($lines[$i]->details_entrepot) > 1) + { + $detail = ''; + foreach ($lines[$i]->details_entrepot as $detail_entrepot) { + if ($detail_entrepot->entrepot_id > 0) { + $entrepot = new Entrepot($db); + $entrepot->fetch($detail_entrepot->entrepot_id); + $detail.= $langs->trans("DetailWarehouseFormat",$entrepot->libelle,$detail_entrepot->qty_shipped).'
'; + } + } + print $form->textwithtooltip($langs->trans("DetailWarehouseNumber"),$detail); + } print ''; } // Batch number managment - if (! empty($conf->productbatch->enabled)) { - if (isset($lines[$i]->detail_batch) ) { - print ''; @@ -1572,21 +1626,25 @@ else if ($id || $ref) $fileparams = dol_most_recent_file($conf->expedition->dir_output . '/sending/' . $ref, preg_quote($ref,'/')); $file=$fileparams['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->client->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('sendings'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - - $result=expedition_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument(GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -1602,6 +1660,7 @@ else if ($id || $ref) // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -1612,7 +1671,7 @@ else if ($id || $ref) $formmail->withto=GETPOST("sendto")?GETPOST("sendto"):$liste; $formmail->withtocc=$liste; $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->trans('SendShippingRef','__SHIPPINGREF__'); + $formmail->withtopic=$outputlangs->trans('SendShippingRef','__SHIPPINGREF__'); $formmail->withfile=2; $formmail->withbody=1; $formmail->withdeliveryreceipt=1; diff --git a/htdocs/expedition/class/expedition.class.php b/htdocs/expedition/class/expedition.class.php index b6cdf5457d3..2cc0667d58a 100644 --- a/htdocs/expedition/class/expedition.class.php +++ b/htdocs/expedition/class/expedition.class.php @@ -6,6 +6,8 @@ * Copyright (C) 2011-2013 Juanjo Menent * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS + * Copyright (C) 2014 Marcos García + * Copyright (C) 2014 Francis Appels * * 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 @@ -227,7 +229,7 @@ class Expedition extends CommonObject $sql.= ", ".(!empty($this->model_pdf)?"'".$this->db->escape($this->model_pdf)."'":"null"); $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -237,7 +239,7 @@ class Expedition extends CommonObject $sql.= " SET ref = '(PROV".$this->id.")'"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); if ($this->db->query($sql)) { // Insertion des lignes @@ -275,12 +277,10 @@ class Expedition extends CommonObject if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SHIPPING_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('SHIPPING_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers if (! $error) { @@ -348,7 +348,7 @@ class Expedition extends CommonObject $sql.= ", ".$qty; $sql.= ")"; - dol_syslog(get_class($this)."::create_line sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create_line", LOG_DEBUG); if (! $this->db->query($sql)) { $error++; @@ -413,7 +413,7 @@ class Expedition extends CommonObject 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)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -487,14 +487,13 @@ class Expedition extends CommonObject } else { - dol_syslog(get_class($this).'::Fetch Error -2'); + dol_syslog(get_class($this).'::Fetch Error -2', LOG_ERR); $this->error='Delivery with id '.$id.' not found sql='.$sql; return -2; } } else { - dol_syslog(get_class($this).'::Fetch Error -1'); $this->error=$this->db->error(); return -1; } @@ -504,9 +503,10 @@ class Expedition extends CommonObject * Validate object and update stock if option enabled * * @param User $user Object user that validate + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if OK, >0 if KO */ - function valid($user) + function valid($user, $notrigger=0) { global $conf, $langs; @@ -548,6 +548,7 @@ class Expedition extends CommonObject { $numref = "EXP".$this->id; } + $this->newref = $numref; $now=dol_now(); @@ -559,11 +560,10 @@ class Expedition extends CommonObject $sql.= ", fk_user_valid = ".$user->id; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::valid update expedition sql=".$sql); + dol_syslog(get_class($this)."::valid update expedition", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::valid Echec update - 10 - sql=".$sql, LOG_ERR); $this->error=$this->db->lasterror(); $error++; } @@ -583,15 +583,16 @@ class Expedition extends CommonObject $sql.= " WHERE ed.fk_expedition = ".$this->id; $sql.= " AND cd.rowid = ed.fk_origin_line"; - dol_syslog(get_class($this)."::valid select details sql=".$sql); + dol_syslog(get_class($this)."::valid select details", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { $cpt = $this->db->num_rows($resql); for ($i = 0; $i < $cpt; $i++) { - dol_syslog(get_class($this)."::valid movement index ".$i); $obj = $this->db->fetch_object($resql); + if($obj->qty <= 0) continue; + dol_syslog(get_class($this)."::valid movement index ".$i); //var_dump($this->lines[$i]); $mouvS = new MouvementStock($this->db); @@ -600,7 +601,7 @@ class Expedition extends CommonObject // We use warehouse selected for each line $result=$mouvS->livraison($user, $obj->fk_product, $obj->fk_entrepot, $obj->qty, $obj->subprice, $langs->trans("ShipmentValidatedInDolibarr",$numref)); if ($result < 0) { $error++; break; } - + if (! empty($conf->productbatch->enabled)) { $details=ExpeditionLigneBatch::FetchAll($this->db,$obj->rowid); foreach ($details as $dbatch) { @@ -614,14 +615,21 @@ class Expedition extends CommonObject { $this->db->rollback(); $this->error=$this->db->error(); - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); return -2; } } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('SHIPPING_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + if (! $error) { - $this->oldref=''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) @@ -638,11 +646,17 @@ class Expedition extends CommonObject if (@rename($dirsource, $dirdest)) { - $this->oldref = $oldref; - - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($dirdest.'/'.$oldref.'*.*'); + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->expedition->dir_output.'/sending/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -655,16 +669,6 @@ class Expedition extends CommonObject $this->statut = 1; } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SHIPPING_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - } - if (! $error) { $this->db->commit(); @@ -727,25 +731,25 @@ class Expedition extends CommonObject function addline($entrepot_id, $id, $qty) { global $conf, $langs; - + $num = count($this->lines); $line = new ExpeditionLigne($this->db); $line->entrepot_id = $entrepot_id; $line->origin_line_id = $id; $line->qty = $qty; - + if($conf->global->STOCK_MUST_BE_ENOUGH_FOR_SHIPMENT) { $orderline = new OrderLine($this->db); $orderline->fetch($id); $fk_product = $orderline->fk_product; - + if (!empty($orderline->fk_product)) { $product=new Product($this->db); $result=$product->fetch($fk_product); $product_type=$product->type; - + if($product_type == 0 && $product->stock_reel < $qty) { $this->error=$langs->trans('ErrorStockIsNotEnough'); $this->db->rollback(); @@ -796,7 +800,7 @@ class Expedition extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -860,7 +864,7 @@ class Expedition extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -868,12 +872,10 @@ class Expedition extends CommonObject { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SHIPPING_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End call triggers + // Call trigger + $result=$this->call_trigger('SHIPPING_MODIFY',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -920,7 +922,7 @@ class Expedition extends CommonObject if ($conf->productbatch->enabled) { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; - if ( ExpeditionLigneBatch::deletefromexp($this->db,$this->id)<0) + if ( ExpeditionLigneBatch::deletefromexp($this->db,$this->id)<0) {$error++;$this->errors[]="Error ".$this->db->lasterror();} } // Stock control @@ -937,7 +939,7 @@ class Expedition extends CommonObject $sql.= " WHERE ed.fk_expedition = ".$this->id; $sql.= " AND cd.rowid = ed.fk_origin_line"; - dol_syslog(get_class($this)."::delete select details sql=".$sql); + dol_syslog(get_class($this)."::delete select details", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -984,12 +986,10 @@ class Expedition extends CommonObject if ($this->db->query($sql)) { - // Call triggers - include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SHIPPING_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End call triggers + // Call trigger + $result=$this->call_trigger('SHIPPING_DELETE',$user); + if ($result < 0) { $error++; } + // End call triggers if (! $error) { @@ -1076,8 +1076,9 @@ class Expedition extends CommonObject $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = cd.fk_product"; $sql.= " WHERE ed.fk_expedition = ".$this->id; $sql.= " AND ed.fk_origin_line = cd.rowid"; + $sql.= " ORDER BY cd.rang, ed.fk_origin_line"; - dol_syslog(get_class($this)."::fetch_lines sql=".$sql); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1085,6 +1086,8 @@ class Expedition extends CommonObject $num = $this->db->num_rows($resql); $i = 0; + $lineindex = 0; + $originline = 0; $this->total_ht = 0; $this->total_tva = 0; @@ -1094,13 +1097,25 @@ class Expedition extends CommonObject while ($i < $num) { - $line = new ExpeditionLigne($this->db); $obj = $this->db->fetch_object($resql); + if ($originline == $obj->fk_origin_line) { + $line->entrepot_id = 0; // entrepod_id in details_entrepot + $line->qty_shipped += $obj->qty_shipped; + } else { + $line = new ExpeditionLigne($this->db); + $line->entrepot_id = $obj->fk_entrepot; + $line->qty_shipped = $obj->qty_shipped; + } + + $detail_entrepot = new stdClass; + $detail_entrepot->entrepot_id = $obj->fk_entrepot; + $detail_entrepot->qty_shipped = $obj->qty_shipped; + $line->details_entrepot[] = $detail_entrepot; + $line->line_id = $obj->line_id; $line->fk_origin_line = $obj->fk_origin_line; $line->origin_line_id = $obj->fk_origin_line; // TODO deprecated - $line->entrepot_id = $obj->fk_entrepot; $line->fk_product = $obj->fk_product; $line->fk_product_type = $obj->fk_product_type; $line->ref = $obj->product_ref; // TODO deprecated @@ -1110,7 +1125,6 @@ class Expedition extends CommonObject $line->label = $obj->custom_label; $line->description = $obj->description; $line->qty_asked = $obj->qty_asked; - $line->qty_shipped = $obj->qty_shipped; $line->weight = $obj->weight; $line->weight_units = $obj->weight_units; $line->length = $obj->length; @@ -1123,7 +1137,7 @@ class Expedition extends CommonObject // For invoicing $tabprice = calcul_price_total($obj->qty_shipped, $obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->fk_product_type); // We force type to 0 $line->desc = $obj->description; // We need ->desc because some code into CommonObject use desc (property defined for other elements) - $line->qty = $obj->qty_shipped; + $line->qty = $line->qty_shipped; $line->total_ht = $tabprice[0]; $line->total_localtax1 = $tabprice[9]; $line->total_localtax2 = $tabprice[10]; @@ -1145,14 +1159,28 @@ class Expedition extends CommonObject // Eat-by date if (! empty($conf->productbatch->enabled)) { /* test on conf at begining of file sometimes doesn't include expeditionbatch - * May be conf is not well initialized for dark reason + * May be conf is not well initialized for dark reason */ require_once DOL_DOCUMENT_ROOT.'/expedition/class/expeditionbatch.class.php'; - $line->detail_batch=ExpeditionLigneBatch::FetchAll($this->db,$obj->line_id); + if ($originline != $obj->fk_origin_line) { + $line->detail_batch = ExpeditionLigneBatch::FetchAll($this->db,$obj->line_id); + } else { + $line->detail_batch = array_merge($line->detail_batch,ExpeditionLigneBatch::FetchAll($this->db,$obj->line_id)); + } + } + if ($originline != $obj->fk_origin_line) { + $this->lines[$lineindex] = $line; + $lineindex++; + } else { + $line->total_ht += $tabprice[0]; + $line->total_localtax1 += $tabprice[9]; + $line->total_localtax2 += $tabprice[10]; + $line->total_ttc += $tabprice[2]; + $line->total_tva += $tabprice[1]; } - $this->lines[$i] = $line; $i++; + $originline = $obj->fk_origin_line; } $this->db->free($resql); return 1; @@ -1160,7 +1188,6 @@ class Expedition extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this).'::fetch_lines: Error '.$this->error, LOG_ERR); return -3; } } @@ -1180,7 +1207,7 @@ class Expedition extends CommonObject $result=''; - $url = DOL_URL_ROOT.'/expedition/fiche.php?id='.$this->id; + $url = DOL_URL_ROOT.'/expedition/card.php?id='.$this->id; if ($short) return $url; @@ -1344,7 +1371,7 @@ class Expedition extends CommonObject $sql.= " SET date_delivery = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_date_livraison sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::set_date_livraison", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1354,7 +1381,6 @@ class Expedition extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_date_livraison ".$this->error,LOG_ERR); return -1; } } @@ -1529,10 +1555,14 @@ class Expedition extends CommonObject global $conf; $sql = 'UPDATE '.MAIN_DB_PREFIX.'expedition SET fk_statut=2'; - $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0 ;'; - if ($this->db->query($sql) ) + $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > 0'; + + $resql=$this->db->query($sql); + if ($resql) { //TODO: Option to set order billed if 100% of order is shipped + $this->statut=2; + $this->billed=1; return 1; } else @@ -1542,6 +1572,39 @@ class Expedition extends CommonObject } } + /** + * Cree un bon d'expedition sur disque + * + * @param string $modele Force le modele a utiliser ('' to not force) + * @param Translate $outputlangs Objet lang a utiliser pour traduction + * @return int <=0 if KO, >0 if OK + */ + public function generateDocument($modele, $outputlangs) + { + global $conf,$user,$langs; + + $langs->load("sendings"); + + // Sets the model on the model name to use + if (! dol_strlen($modele)) + { + if (! empty($conf->global->EXPEDITION_ADDON_PDF)) + { + $modele = $conf->global->EXPEDITION_ADDON_PDF; + } + else + { + $modele = 'rouget'; + } + } + + $modelpath = "core/modules/expedition/doc/"; + + $this->fetch_origin(); + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, 0, 0, 0); + } + } diff --git a/htdocs/expedition/class/expeditionbatch.class.php b/htdocs/expedition/class/expeditionbatch.class.php index 7bbd99706bd..62d23aaa7ff 100644 --- a/htdocs/expedition/class/expeditionbatch.class.php +++ b/htdocs/expedition/class/expeditionbatch.class.php @@ -69,7 +69,7 @@ class ExpeditionLigneBatch extends CommonObject $sql.= MAIN_DB_PREFIX."product_stock as e on t.fk_product_stock=e.rowid "; $sql.= " WHERE t.rowid = ".(int) $id_stockdluo; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -91,7 +91,6 @@ class ExpeditionLigneBatch extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(__METHOD__ .$this->error, LOG_ERR); return -1; } } @@ -123,7 +122,7 @@ class ExpeditionLigneBatch extends CommonObject $sql.= " ".(! isset($this->fk_origin_stock)?'NULL':$this->fk_origin_stock); $sql.= ")"; - dol_syslog(__METHOD__ ." sql=".$sql, LOG_DEBUG); + dol_syslog(__METHOD__ ."", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -157,7 +156,7 @@ class ExpeditionLigneBatch extends CommonObject $sql="DELETE FROM ".MAIN_DB_PREFIX.self::$_table_element; $sql.=" WHERE fk_expeditiondet in (SELECT rowid FROM ".MAIN_DB_PREFIX."expeditiondet WHERE fk_expedition=".$id_expedition.")"; - dol_syslog(__METHOD__ ." sql=".$sql, LOG_DEBUG); + dol_syslog(__METHOD__ ."", LOG_DEBUG); if ( $db->query($sql) ) { return 1; @@ -185,7 +184,7 @@ class ExpeditionLigneBatch extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX.self::$_table_element; $sql.= " WHERE fk_expeditiondet=".(int) $id_line_expdet; - dol_syslog(__METHOD__ ." sql=".$sql, LOG_DEBUG); + dol_syslog(__METHOD__ ."", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { diff --git a/htdocs/expedition/class/index.html b/htdocs/expedition/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/expedition/contact.php b/htdocs/expedition/contact.php index facca267160..c09b3e415cd 100644 --- a/htdocs/expedition/contact.php +++ b/htdocs/expedition/contact.php @@ -87,15 +87,14 @@ if ($action == 'addcontact' && $user->rights->expedition->creer) } else { - if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($objectsrc->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; - } - else - { - $mesg = '
'.$objectsrc->error.'
'; + $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); + } else { + $mesg = $objectsrc->error; } + + setEventMessage($mesg, 'errors'); } } @@ -146,7 +145,6 @@ $userstatic=new User($db); /* Mode vue et edition */ /* */ /* *************************************************************************** */ -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { @@ -161,7 +159,7 @@ if ($id > 0 || ! empty($ref)) */ print '
'.$langs->trans("Ref").''; + if (! empty($conf->productbatch->enabled)) + { + if (isset($lines[$i]->detail_batch)) + { + print ''; $detail = ''; foreach ($lines[$i]->detail_batch as $dbatch) { - $detail.= $langs->trans("DetailBatchFormat",dol_print_date($dbatch->eatby,"day"),dol_print_date($dbatch->sellby,"day"),$dbatch->batch,$dbatch->dluo_qty).'
'; + $detail.= $langs->trans("DetailBatchFormat",$dbatch->batch,dol_print_date($dbatch->eatby,"day"),dol_print_date($dbatch->sellby,"day"),$dbatch->dluo_qty).'
'; } print $form->textwithtooltip($langs->trans("DetailBatchNumber"),$detail); print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; print ''; @@ -224,7 +228,7 @@ else dol_print_error($db); * Last shipments */ $sql = "SELECT e.rowid, e.ref"; -$sql.= ", s.nom, s.rowid as socid"; +$sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", c.ref as commande_ref, c.rowid as commande_id"; $sql.= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'shipping' AND el.sourcetype IN ('commande')"; @@ -253,9 +257,9 @@ if ($resql) { $var=!$var; $obj = $db->fetch_object($resql); - print ''; - print ''; + print ''; print '
'.$langs->trans("Ref").''; diff --git a/htdocs/expedition/index.php b/htdocs/expedition/index.php index 5ce833e5e3f..2b41a939c7b 100644 --- a/htdocs/expedition/index.php +++ b/htdocs/expedition/index.php @@ -44,14 +44,12 @@ llxHeader('',$langs->trans("Shipment"),$helpurl); print_fiche_titre($langs->trans("SendingsArea")); -//print ''; -//print '"; print ''; print ''; $i++; } @@ -116,7 +114,7 @@ if ($resql) /* * Commandes a traiter */ -$sql = "SELECT c.rowid, c.ref, s.nom, s.rowid as socid"; +$sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as name, s.rowid as socid"; $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"; @@ -138,7 +136,7 @@ if ($resql) $i = 0; print '
'; print '
'; $var=false; print ''; -print ''; +print ''; print ''; print ''; print '
'.$langs->trans("SearchASending").'
'; @@ -64,7 +62,7 @@ print "

\n"; $clause = " WHERE "; $sql = "SELECT e.rowid, e.ref"; -$sql.= ", s.nom, s.rowid as socid"; +$sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", c.ref as commande_ref, c.rowid as commande_id"; $sql.= " FROM ".MAIN_DB_PREFIX."expedition as e"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON e.rowid = el.fk_target AND el.targettype = 'shipping'"; @@ -101,10 +99,10 @@ if ($resql) print $shipment->getNomUrl(1); print "
'; - print ''.$obj->nom.''; + print ''.$obj->name.''; print ''; - if ($obj->commande_id) print ''.$obj->commande_ref.''; + if ($obj->commande_id) print ''.$obj->commande_ref.''; print '
'; print ''; - print ''; + print ''; $var = True; while ($i < $num) { @@ -148,13 +146,19 @@ if ($resql) print ''; print ''; + print ''; + print ''; + print ''; $i++; } print "
'.$langs->trans("OrdersToProcess").'
'.$langs->trans("OrdersToProcess").'
'; $orderstatic->id=$obj->rowid; $orderstatic->ref=$obj->ref; + $orderstatic->statut=$obj->fk_statut; + $orderstatic->facturee=0; print $orderstatic->getNomUrl(1); print ''; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->id=$obj->socid; print $companystatic->getNomUrl(1,'customer',32); - print '
'; + print $orderstatic->getLibStatut(3); + print '

"; @@ -169,7 +173,7 @@ print '
'; /* * Commandes en traitement */ -$sql = "SELECT c.rowid, c.ref, c.fk_statut as status, c.facture as billed, s.nom, s.rowid as socid"; +$sql = "SELECT c.rowid, c.ref, c.fk_statut as status, c.facture as billed, s.nom as name, s.rowid as socid"; $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"; @@ -202,7 +206,7 @@ if ( $resql ) print $orderstatic->getNomUrl(1); print '
'; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->id=$obj->socid; print $companystatic->getNomUrl(1,'customer'); print '
'.img_object($langs->trans("ShowSending"),"sending").' '; + print '
'.img_object($langs->trans("ShowSending"),"sending").' '; print $obj->ref.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''; if ($obj->commande_id) { @@ -274,7 +278,6 @@ if ($resql) else dol_print_error($db); -//print '
'; print ''; diff --git a/htdocs/expedition/liste.php b/htdocs/expedition/list.php similarity index 55% rename from htdocs/expedition/liste.php rename to htdocs/expedition/list.php index 29ab105ee91..0722dedddf4 100644 --- a/htdocs/expedition/liste.php +++ b/htdocs/expedition/list.php @@ -18,7 +18,7 @@ */ /** - * \file htdocs/expedition/liste.php + * \file htdocs/expedition/list.php * \ingroup expedition * \brief Page to list all shipments */ @@ -34,6 +34,10 @@ $expeditionid = GETPOST('id','int'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'expedition',$expeditionid,''); +$search_ref_exp = GETPOST("search_ref_exp"); +$search_ref_liv = GETPOST('search_ref_liv'); +$search_company = GETPOST("search_company"); + $sortfield = GETPOST('sortfield','alpha'); $sortorder = GETPOST('sortorder','alpha'); $page = GETPOST('page','int'); @@ -47,6 +51,13 @@ if (! $sortfield) $sortfield="e.ref"; if (! $sortorder) $sortorder="DESC"; $limit = $conf->liste_limit; +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref_exp=''; + $search_ref_liv=''; + $search_company=''; +} /* * View @@ -79,10 +90,9 @@ if ($socid) { $sql.= " AND e.fk_soc = ".$socid; } -if (GETPOST('sf_ref','alpha')) -{ - $sql.= " AND e.ref like '%".$db->escape(GETPOST('sf_ref','alpha'))."%'"; -} +if ($search_ref_exp) $sql .= natural_search('e.ref', $search_ref_exp); +if ($search_ref_liv) $sql .= natural_search('l.ref', $search_ref_liv); +if ($search_company) $sql .= natural_search('s.nom', $search_company); $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit + 1,$offset); @@ -94,23 +104,54 @@ if ($resql) $expedition = new Expedition($db); - $param="&socid=$socid"; + $param=""; + if ($search_ref_exp) $param.= "&search_ref_exp=".$search_ref_exp; + if ($search_ref_liv) $param.= "&search_ref_liv=".$search_ref_liv; + if ($search_company) $param.= "&search_company=".$search_company; - print_barre_liste($langs->trans('ListOfSendings'), $page, "liste.php",$param,$sortfield,$sortorder,'',$num); + print_barre_liste($langs->trans('ListOfSendings'), $page, $_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num); $i = 0; + print '
'."\n"; print ''; print ''; - print_liste_field_titre($langs->trans("Ref"),"liste.php","e.ref","",$param,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Company"),"liste.php","s.nom", "", $param,'align="left"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("DateDeliveryPlanned"),"liste.php","e.date_delivery","",$param, 'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Ref"),"ship2bill.php","e.ref","",$param,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Company"),"ship2bill.php","s.nom", "", $param,'align="left"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("DateDeliveryPlanned"),"ship2bill.php","e.date_delivery","",$param, 'align="center"',$sortfield,$sortorder); if($conf->livraison_bon->enabled) { - print_liste_field_titre($langs->trans("DateReceived"),"liste.php","e.date_expedition","",$param, 'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("DeliveryOrder"),"ship2bill.php","e.date_expedition","",$param, '',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("DateReceived"),"ship2bill.php","e.date_expedition","",$param, 'align="center"',$sortfield,$sortorder); } - print_liste_field_titre($langs->trans("Status"),"liste.php","e.fk_statut","",$param,'align="right"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Status"),"ship2bill.php","e.fk_statut","",$param,'align="right"',$sortfield,$sortorder); + print ''; print "\n"; + + // Lignes des champs de filtre + print ''; + print ''; + print ''; + print ''; + if($conf->livraison_bon->enabled) { + print ''; + } + print ''; + print ''; + + print "\n"; + $var=True; while ($i < min($num,$limit)) @@ -118,20 +159,24 @@ if ($resql) $objp = $db->fetch_object($resql); $var=!$var; + + // Ref print ""; print "\n"; + // Third party print ''; - // Date delivery planed + + // Date delivery planed print ""; print ''; print ''; @@ -150,10 +155,12 @@ if ($id > 0 || ! empty($ref)) // Date print ''; - print "\n"; + print "\n"; print ''; print '
 
'; + print ''; + print ''; + print ''; + print ' '; + print ''; + print ' '; + print ''; + print ''; + print ''.$langs->trans("All").' / '.$langs->trans("None").''; + print '
"; $shipment->id=$objp->rowid; $shipment->ref=$objp->ref; print $shipment->getNomUrl(1); print "'; $companystatic->id=$objp->socid; $companystatic->ref=$objp->socname; - $companystatic->nom=$objp->socname; + $companystatic->name=$objp->socname; print $companystatic->getNomUrl(1); print '"; print dol_print_date($db->jdate($objp->date_expedition),"day"); /*$now = time(); diff --git a/htdocs/expedition/note.php b/htdocs/expedition/note.php index 27d53b03cd6..01a341d7ab5 100644 --- a/htdocs/expedition/note.php +++ b/htdocs/expedition/note.php @@ -101,7 +101,7 @@ if ($id > 0 || ! empty($ref)) print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; diff --git a/htdocs/expedition/shipment.php b/htdocs/expedition/shipment.php index fce9c3bf6a5..bce365447e1 100644 --- a/htdocs/expedition/shipment.php +++ b/htdocs/expedition/shipment.php @@ -116,6 +116,13 @@ if ($action == 'setconditions' && $user->rights->commande->creer) if ($result < 0) dol_print_error($db,$commande->error); } +// shipping method +if ($action == 'setshippingmethod' && $user->rights->commande->creer) { + $commande = new Commande($db); + $commande->fetch($id); + $result=$commande->setShippingMethod(GETPOST('shipping_method_id', 'int')); +} + /* @@ -157,7 +164,7 @@ if ($id > 0 || ! empty($ref)) } // Onglet commande - $nbrow=7; + $nbrow=8; if (! empty($conf->projet->enabled)) $nbrow++; print '
'.$langs->trans("Ref").'
'; @@ -257,11 +264,29 @@ if ($id > 0 || ! empty($ref)) print dol_print_date($commande->date_livraison,'daytext'); } print ''; + // Note on several rows print ''; print ''; + // Shipping Method + print ''; + print ''; + // Terms of payment print '"; print '"; print ""; -print ""; +print ""; print ""; $var=!$var; @@ -120,10 +120,6 @@ print ""; print "\n"; - -dol_htmloutput_mesg($mesg); - - llxFooter(); $db->close(); diff --git a/htdocs/externalsite/admin/index.html b/htdocs/externalsite/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/externalsite/index.html b/htdocs/externalsite/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/externalsite/index.php b/htdocs/externalsite/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/externalsite/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php index 23c39533e19..8cb95a30f63 100644 --- a/htdocs/fichinter/admin/fichinter_extrafields.php +++ b/htdocs/fichinter/admin/fichinter_extrafields.php @@ -39,7 +39,7 @@ $extrafields = new ExtraFields($db); $form = new Form($db); // List of supported format -$tmptype2label=getStaticMember(get_class($extrafields),'type2label'); +$tmptype2label=ExtraFields::$type2label; $type2label=array(''); foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); @@ -92,6 +92,7 @@ print ''; print ''; print ''; print ''; +print ''; print ''; print "\n"; @@ -107,6 +108,7 @@ foreach($extrafields->attribute_type as $key => $value) print '\n"; print '\n"; print '\n"; + print '\n"; // TODO This must be generalised into all page to admin extrafield. Mutualize code here is easy and will save a lot of code print '\n"; print ""; diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php new file mode 100644 index 00000000000..7f8b5193631 --- /dev/null +++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php @@ -0,0 +1,159 @@ + + * Copyright (C) 2003 Jean-Louis Bergamo + * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2012 Regis Houssin + * Copyright (C) 2013 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/fichinter/admin/fichinter_extrafields.php + * \ingroup fichinter + * \brief Page to setup extra fields of ficheinter + */ + + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + +$langs->load("companies"); +$langs->load("admin"); +$langs->load("members"); +$langs->load('interventions'); + +$extrafields = new ExtraFields($db); +$form = new Form($db); + +// List of supported format +$tmptype2label=ExtraFields::$type2label; +$type2label=array(''); +foreach ($tmptype2label as $key => $val) $type2label[$key]=$langs->trans($val); + +$action=GETPOST('action', 'alpha'); +$attrname=GETPOST('attrname', 'alpha'); +$elementtype='fichinterdet'; //Must be the $element of the class that manage extrafield + +if (!$user->admin) accessforbidden(); + + +/* + * Actions + */ + +require DOL_DOCUMENT_ROOT.'/core/actions_extrafields.inc.php'; + + + +/* + * View + */ + + +llxHeader(); + +$textobject=$langs->transnoentitiesnoconv("Interventions"); + +$linkback=''.$langs->trans("BackToModuleList").''; +print_fiche_titre($langs->trans("InterventionsSetup"),$linkback,'setup'); + + +$head=fichinter_admin_prepare_head(); + +dol_fiche_head($head, 'attributesdet', $langs->trans("Interventions"), 0, 'intervention'); + + +print $langs->trans("DefineHereComplementaryAttributes",$textobject).'
'."\n"; +print '
'; + +// Load attribute_label +$extrafields->fetch_name_optionals_label($elementtype); + +print "
'.$langs->trans('NotePublic').' :
'; print nl2br($commande->note_public); print '
'; + print ''; + if ($action != 'editshippingmethod' && $user->rights->expedition->creer) + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print 'id.'">'.img_edit($langs->trans('SetShippingMode'),1).'
'; + print '
'; + if ($action == 'editshippingmethod') { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$commande->id, $commande->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$commande->id, $commande->shipping_method_id, 'none'); + } + print '
'; print ''; - print ''; - print ''; + print ''; + print ''; // Total TVA - print ''; - print ''; + print ''; + print ''; // Total TTC - print ''; - print ''; + print ''; + print ''; // Statut print ''; @@ -363,7 +388,7 @@ if ($id > 0 || ! empty($ref)) $sql.= " ORDER BY cd.rang, cd.rowid"; //print $sql; - dol_syslog("shipment.php sql=".$sql, LOG_DEBUG); + dol_syslog("shipment.php", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -539,7 +564,7 @@ if ($id > 0 || ! empty($ref)) { $img=img_warning($langs->trans("StockTooLow")); } - print ''; + print ''; print ''; print ''; print ''; @@ -582,7 +607,7 @@ if ($id > 0 || ! empty($ref)) { if ($user->rights->expedition->creer) { - print ''.$langs->trans("NewSending").''; + print ''.$langs->trans("NewSending").''; if ($toBeShippedTotal <= 0) { print ' '.img_warning($langs->trans("WarningNoQtyLeftToSend")); @@ -604,9 +629,10 @@ if ($id > 0 || ! empty($ref)) { print_titre($langs->trans("NewSending")); - print ''; + print ''; print ''; print ''; + print ''; print ''; print ''; print '
'; @@ -325,16 +350,16 @@ if ($id > 0 || ! empty($ref)) // Total HT print '
'.$langs->trans('AmountHT').''.price($commande->total_ht).''.$langs->trans('Currency'.$conf->currency).'
'.price($commande->total_ht, 0, '', 1, -1, -1, $conf->currency).'
'.$langs->trans('AmountVAT').''.price($commande->total_tva).''.$langs->trans('Currency'.$conf->currency).'
'.$langs->trans('AmountVAT').''.price($commande->total_tva, 0, '', 1, -1, -1, $conf->currency).'
'.$langs->trans('AmountTTC').''.price($commande->total_ttc).''.$langs->trans('Currency'.$conf->currency).'
'.$langs->trans('AmountTTC').''.price($commande->total_ttc, 0, '', 1, -1, -1, $conf->currency).'
'.$langs->trans('Status').'
      -> '.$value['fullpath'].' ('.$value['nb'].')
      -> '.$value['fullpath'].' ('.$value['nb'].') '.$value['nb_total'].'  
'; @@ -617,12 +643,15 @@ if ($id > 0 || ! empty($ref)) if (! empty($conf->stock->enabled)) { - print ''; + $warehousecanbeselectedlater=1; + if (! empty($conf->productbatch->enabled)) $warehousecanbeselectedlater=0; + + print ''.$langs->trans("WarehouseSource").''; print ''; } diff --git a/htdocs/expedition/tpl/index.html b/htdocs/expedition/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/expedition/tpl/linkedobjectblock.tpl.php b/htdocs/expedition/tpl/linkedobjectblock.tpl.php index 364afb92177..72206c13e2b 100644 --- a/htdocs/expedition/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expedition/tpl/linkedobjectblock.tpl.php @@ -47,7 +47,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > + trans("ShowShipping"),"sending").' '.$object->ref; ?>
'.$langs->trans("WarehouseSource").''; print $formproduct->selectWarehouses(-1,'entrepot_id','',1); if (count($formproduct->cache_warehouses) <= 0) { - print '   '.$langs->trans("WarehouseSourceNotDefined").' '.$langs->trans("AddOne").''; + print '   '.$langs->trans("WarehouseSourceNotDefined").' '.$langs->trans("AddOne").''; } print '
- trans("ShowShipping"),"sending").' '.$object->ref; ?> date_creation,'day'); ?> date_delivery,'day'); ?> sqlusedforexport=$sql; - dol_syslog(get_class($this)."::".__FUNCTION__." sql=".$sql); + dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -592,7 +592,6 @@ class Export else { $this->error=$this->db->error()." - sql=".$sql; - dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR); return -1; } } @@ -628,7 +627,7 @@ class Export $sql.= (! empty($filter)?"'".$filter."'":"null"); $sql.= ")"; - dol_syslog("Export::create sql=".$sql, LOG_DEBUG); + dol_syslog("Export::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -639,7 +638,6 @@ class Export { $this->error=$this->db->lasterror(); $this->errno=$this->db->lasterrno(); - dol_syslog("Export::create error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -657,7 +655,7 @@ class Export $sql.= ' FROM '.MAIN_DB_PREFIX.'export_model as em'; $sql.= ' WHERE em.rowid = '.$id; - dol_syslog("Export::fetch sql=".$sql, LOG_DEBUG); + dol_syslog("Export::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -706,7 +704,7 @@ class Export $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } diff --git a/htdocs/exports/class/index.html b/htdocs/exports/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index a6d82b10a86..45e78b2ecd3 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -166,6 +166,8 @@ if ($action=='selectfield') } //print_r($array_selected); $_SESSION["export_selected_fields"]=$array_selected; + + setEventMessage($warnings, 'warnings'); } } @@ -488,9 +490,6 @@ if ($step == 2 && $datatoexport) print '
'; print '
'; - - if ($warnings) dol_htmloutput_mesg('',$warnings,'warning'); - // Combo list of export models print ''; print ''; @@ -733,7 +732,7 @@ if ($step == 3 && $datatoexport) // Filter value print '
'; - if (! empty($Typefieldsarray[$code])) // Example: Text, List:c_pays:libelle:rowid, Number, Boolean + if (! empty($Typefieldsarray[$code])) // Example: Text, List:c_country:label:rowid, Number, Boolean { $szInfoFiltre=$objexport->genDocFilter($Typefieldsarray[$code]); if ($szInfoFiltre) // Is there an info help for this filter ? diff --git a/htdocs/externalsite/admin/externalsite.php b/htdocs/externalsite/admin/externalsite.php index 9c59a7bf4ff..93595b2cb9f 100644 --- a/htdocs/externalsite/admin/externalsite.php +++ b/htdocs/externalsite/admin/externalsite.php @@ -59,12 +59,12 @@ if ($action == 'update') if ($i >= 2) { $db->commit(); - $mesg = "".$langs->trans("SetupSaved").""; + setEventMessage($langs->trans("SetupSaved")); } else { $db->rollback(); - $mesg="
".$db->lasterror()."
"; + setEventMessage($db->lasterror(), 'errors'); } } @@ -99,7 +99,7 @@ $var=!$var; print "
'.$langs->trans("Label")."global->EXTERNALSITE_LABEL) || $conf->global->EXTERNALSITE_LABEL=='ExternalSite')?'':$conf->global->EXTERNALSITE_LABEL)) . "\" size=\"12\">My menu entry".$langs->trans("ExampleMyMenuEntry")."
'.$langs->trans("Type").''.$langs->trans("Size").''.$langs->trans("Unique").''.$langs->trans("Required").''.$langs->trans("AlwaysEditable").' 
'.$extrafields->attribute_size[$key]."'.yn($extrafields->attribute_unique[$key])."'.yn($extrafields->attribute_required[$key])."'.yn($extrafields->attribute_alwayseditable[$key])."'.img_edit().''; print "  ".img_delete()."
"; + +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print "\n"; + +$var=True; +foreach($extrafields->attribute_type as $key => $value) +{ + $var=!$var; + print ""; + print "\n"; + print "\n"; + print "\n"; + print "\n"; + print '\n"; + print '\n"; + print '\n"; + print '\n"; + print ""; + // $i++; +} + +print "
'.$langs->trans("Position").''.$langs->trans("Label").''.$langs->trans("AttributeCode").''.$langs->trans("Type").''.$langs->trans("Size").''.$langs->trans("Unique").''.$langs->trans("Required").' 
".$extrafields->attribute_pos[$key]."".$extrafields->attribute_label[$key]."".$key."".$type2label[$extrafields->attribute_type[$key]]."'.$extrafields->attribute_size[$key]."'.yn($extrafields->attribute_unique[$key])."'.yn($extrafields->attribute_required[$key])."'.img_edit().''; + print "  ".img_delete()."
"; + +dol_fiche_end(); + + +// Buttons +if ($action != 'create' && $action != 'edit') +{ + print '
'; + print "".$langs->trans("NewAttribute").""; + print "
"; +} + + +/* ************************************************************************** */ +/* */ +/* Creation d'un champ optionnel + /* */ +/* ************************************************************************** */ + +if ($action == 'create') +{ + print "
"; + print_titre($langs->trans('NewAttribute')); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; +} + +/* ************************************************************************** */ +/* */ +/* Edition d'un champ optionnel */ +/* */ +/* ************************************************************************** */ +if ($action == 'edit' && ! empty($attrname)) +{ + print "
"; + print_titre($langs->trans("FieldEdition", $attrname)); + + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; +} + +llxFooter(); + +$db->close(); diff --git a/htdocs/fichinter/admin/index.html b/htdocs/fichinter/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fichinter/apercu.php b/htdocs/fichinter/apercu.php index 753a74a3ed6..0d4d3421538 100644 --- a/htdocs/fichinter/apercu.php +++ b/htdocs/fichinter/apercu.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2005 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2011 Regis Houssin * Copyright (C) 2011-2012 Juanjo Menent * @@ -40,6 +40,11 @@ $ref = GETPOST('ref','alpha'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); + +/* + * View + */ + llxHeader(); $form = new Form($db); @@ -139,7 +144,7 @@ if ($id > 0 || ! empty($ref)) // Client print "
".$langs->trans("Customer")."'; - print ''.$soc->nom.''; + print ''.$soc->name.''; print '
'.$langs->trans("Date").'".dol_print_date($object->date,"daytext")."".dol_print_date($object->datec,"daytext")."
'; + + dol_fiche_end(); } else { @@ -165,7 +172,7 @@ if ($id > 0 || ! empty($ref)) // Si fichier png PDF d'1 page trouve if (file_exists($fileimage)) { - print ''; + print ''; } // Si fichier png PDF de plus d'1 page trouve elseif (file_exists($fileimagebis)) @@ -178,13 +185,12 @@ elseif (file_exists($fileimagebis)) if (file_exists($dir_output.$preview)) { - print '

'; + print '

'; } } } -print ''; - -$db->close(); llxFooter(); + +$db->close(); diff --git a/htdocs/fichinter/fiche.php b/htdocs/fichinter/card.php similarity index 71% rename from htdocs/fichinter/fiche.php rename to htdocs/fichinter/card.php index 9be7d67115e..4ffc31c9cab 100644 --- a/htdocs/fichinter/fiche.php +++ b/htdocs/fichinter/card.php @@ -1,9 +1,10 @@ - * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2013 Juanjo Menent * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,8 +21,8 @@ */ /** - * \file htdocs/fichinter/fiche.php - * \brief Fichier fiche intervention + * \file htdocs/fichinter/card.php + * \brief Page of intervention * \ingroup ficheinter */ @@ -64,6 +65,7 @@ $mesg = GETPOST('msg','alpha'); $origin=GETPOST('origin','alpha'); $originid=(GETPOST('originid','int')?GETPOST('originid','int'):GETPOST('origin_id','int')); // For backward compatibility $note_public = GETPOST('note_public'); +$lineid = GETPOST('line_id','int'); //PDF $hidedetails = (GETPOST('hidedetails','int') ? GETPOST('hidedetails','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); @@ -75,7 +77,7 @@ if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('interventioncard')); +$hookmanager->initHooks(array('interventioncard','globalcard')); $object = new Fichinter($db); $extrafields = new ExtraFields($db); @@ -96,7 +98,11 @@ $permissionnote=$user->rights->ficheinter->creer; // Used by the include of acti * Actions */ -include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + +include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->ficheinter->creer) { @@ -152,11 +158,6 @@ else if ($action == 'confirm_modify' && $confirm == 'yes' && $user->rights->fich else if ($action == 'add' && $user->rights->ficheinter->creer) { - // Fill array 'array_options' with data from add form - $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); - $ret = $extrafields->setOptionalsFromPost($extralabels, $object); - if ($ret < 0) $error ++; - $object->socid = $socid; $object->duree = GETPOST('duree','int'); $object->fk_project = GETPOST('projectid','int'); @@ -202,6 +203,13 @@ else if ($action == 'add' && $user->rights->ficheinter->creer) $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } + // Extrafields + $extrafields = new ExtraFields($db); + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $array_option = $extrafields->getOptionalsFromPost($extralabels); + + $object->array_options = $array_option; + $id = $object->create($user); if ($id > 0) @@ -276,12 +284,20 @@ else if ($action == 'add' && $user->rights->ficheinter->creer) $duration = 0; } + $predef = ''; + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline, $predef); + + $result = $object->addline( $user, $id, $desc, $date_intervention, - $duration + $duration, + $array_option ); if ($result < 0) @@ -308,6 +324,13 @@ else if ($action == 'add' && $user->rights->ficheinter->creer) } else { + // Extrafields + $extrafields = new ExtraFields($db); + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $array_option = $extrafields->getOptionalsFromPost($extralabels); + + $object->array_options = $array_option; + $result = $object->create($user); if ($result > 0) { @@ -316,7 +339,7 @@ else if ($action == 'add' && $user->rights->ficheinter->creer) else { $langs->load("errors"); - $mesg='

'.$langs->trans($object->error).'
'; + setEventMessages($object->error, $object->errors, 'errors'); $action = 'create'; } } @@ -443,12 +466,19 @@ else if ($action == "addline" && $user->rights->ficheinter->creer) $date_intervention = dol_mktime(GETPOST('dihour','int'), GETPOST('dimin','int'), 0, GETPOST('dimonth','int'), GETPOST('diday','int'), GETPOST('diyear','int')); $duration = convertTime2Seconds(GETPOST('durationhour','int'), GETPOST('durationmin','int')); + + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline); + $result=$object->addline( $user, $id, $desc, $date_intervention, - $duration + $duration, + $array_option ); // Define output language @@ -481,7 +511,22 @@ else if ($action == "addline" && $user->rights->ficheinter->creer) // Classify Billed else if ($action == 'classifybilled' && $user->rights->ficheinter->creer) { - $result=$object->setBilled(); + $result=$object->setStatut(2); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + } +} + +// Classify Billed +else if ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) +{ + $result=$object->setStatut(1); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -495,11 +540,11 @@ else if ($action == 'classifybilled' && $user->rights->ficheinter->creer) /* * Mise a jour d'une ligne d'intervention -*/ + */ else if ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST('save','alpha') == $langs->trans("Save")) { $objectline = new FichinterLigne($db); - if ($objectline->fetch(GETPOST('line_id','int')) <= 0) + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; @@ -519,6 +564,13 @@ else if ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST( $objectline->datei = $date_inter; $objectline->desc = $desc; $objectline->duration = $duration; + + // Extrafields + $extrafieldsline = new ExtraFields($db); + $extralabelsline = $extrafieldsline->fetch_name_optionals_label($object->table_element_line); + $array_option = $extrafieldsline->getOptionalsFromPost($extralabelsline); + $objectline->array_options = $array_option; + $result = $objectline->update($user); if ($result < 0) { @@ -548,7 +600,7 @@ else if ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST( else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->ficheinter->creer) { $objectline = new FichinterLigne($db); - if ($objectline->fetch(GETPOST('line_id','int')) <= 0) + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; @@ -580,7 +632,7 @@ else if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights-> else if ($action == 'up' && $user->rights->ficheinter->creer) { - $object->line_up(GETPOST('line_id','int')); + $object->line_up($lineid); // Define output language $outputlangs = $langs; @@ -594,13 +646,13 @@ else if ($action == 'up' && $user->rights->ficheinter->creer) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('line_id','int')); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; } else if ($action == 'down' && $user->rights->ficheinter->creer) { - $object->line_down(GETPOST('line_id','int')); + $object->line_down($lineid); // Define output language $outputlangs = $langs; @@ -614,7 +666,7 @@ else if ($action == 'down' && $user->rights->ficheinter->creer) } if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->modelpdf, $outputlangs); - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('line_id','int')); + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; } @@ -693,14 +745,15 @@ if ($action == 'send' && ! GETPOST('cancel','alpha') && (empty($conf->global->MA if (strlen(GETPOST('subject','alphs'))) $subject = GETPOST('subject','alpha'); else $subject = $langs->transnoentities('Intervention').' '.$object->ref; $actiontypecode='AC_OTH_AUTO'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } - $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); + $actionmsg2=$langs->transnoentities("InterventionSentByEMail",$object->ref); } // Create form object @@ -712,7 +765,7 @@ if ($action == 'send' && ! GETPOST('cancel','alpha') && (empty($conf->global->MA $filename = $attachedfiles['names']; $mimetype = $attachedfiles['mimes']; - // Envoi de la propal + // Send by email require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt,-1); if ($mailfile->error) @@ -998,7 +1051,7 @@ if ($action == 'create') $numprojet=$formproject->select_projects($soc->id,GETPOST('projectid','int'),'projectid'); if ($numprojet==0) { - print '   '.$langs->trans("AddProject").''; + print '   '.$langs->trans("AddProject").''; } print '
'; @@ -1168,17 +1227,20 @@ else if ($id > 0 || ! empty($ref)) $linkback = ''.$langs->trans("BackToList").''; // Ref - print ''; // Third party - print ""; + print ""; - // Duration - print ''; - print ''; - print ''; + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + // Duration + print ''; + print ''; + print ''; + } // Description (must be a textarea and not html must be allowed (used in list view) print ''; + print ''; - // Other attributes (TODO Move this into an include) - $parameters=array('colspan' => ' colspan="3"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - foreach($extrafields->attribute_label as $key=>$label) - { - if ($action == 'edit_extras') { - $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]); - } else { - $value=$object->array_options["options_".$key]; - } - if ($extrafields->attribute_type[$key] == 'separate') - { - print $extrafields->showSeparator($key); - } - else - { - print 'attribute_required[$key])) print ' class="fieldrequired"'; - print '>'.$label.'
'.$langs->trans("Ref").''; + print '
'.$langs->trans("Ref").''; print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref'); print '
".$langs->trans("Company")."".$object->client->getNomUrl(1)."
".$langs->trans("Company").''.$object->client->getNomUrl(1)."
'.$langs->trans("TotalDuration").''.convertSecondToTime($object->duree, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
'.$langs->trans("TotalDuration").''.convertSecondToTime($object->duree, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
'; @@ -1254,7 +1316,7 @@ else if ($id > 0 || ! empty($ref)) { $contratstatic = new Contrat($db); $contratstatic->fetch($object->fk_contrat); - //print ''.$projet->title.''; + //print ''.$projet->title.''; print $contratstatic->getNomUrl(0,'',1); } else @@ -1267,53 +1329,14 @@ else if ($id > 0 || ! empty($ref)) } // Statut - print '
'.$langs->trans("Status").''.$object->getLibStatut(4).'
'.$langs->trans("Status").''.$object->getLibStatut(4).'
'; - // Convert date into timestamp format - if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) - { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$db->jdate($object->array_options['options_'.$key]); - } - if ($action == 'edit_extras' && $user->rights->ficheinter->creer && GETPOST('attribute') == $key) - { - print ''; + // Other attributes + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; - print $extrafields->showInputField($key,$value); + print "
"; - print ''; - } - else - { - print $extrafields->showOutputField($key,$value); - if ($object->statut == 0 && $user->rights->ficheinter->creer) print ''.img_picto('','edit').' '.$langs->trans('Modify').''; - } - print ''."\n"; - } - } - } - - print "
"; print ''; if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) @@ -1330,258 +1353,331 @@ else if ($id > 0 || ! empty($ref)) include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - - - print '
'; - print ''; - print ''; - if ($action == 'editline') - { - print ''; - print ''; - } - else - { - print ''; - } - - // Intervention lines - $sql = 'SELECT ft.rowid, ft.description, ft.fk_fichinter, ft.duree, ft.rang,'; - $sql.= ' ft.date as date_intervention'; - $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; - $sql.= ' WHERE ft.fk_fichinter = '.$object->id; - $sql.= ' ORDER BY ft.rang ASC, ft.rowid'; - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - - if ($num) + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + print ''; + print ''; + print ''; + if ($action == 'editline') { - print ''; - - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; } - $var=true; - while ($i < $num) + else { - $objp = $db->fetch_object($resql); - $var=!$var; + print ''; + } - // Ligne en mode visu - if ($action != 'editline' || GETPOST('line_id','int') != $objp->rowid) + // Intervention lines + $sql = 'SELECT ft.rowid, ft.description, ft.fk_fichinter, ft.duree, ft.rang,'; + $sql.= ' ft.date as date_intervention'; + $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; + $sql.= ' WHERE ft.fk_fichinter = '.$object->id; + $sql.= ' ORDER BY ft.rang ASC, ft.rowid'; + + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + + if ($num) { - print ''; - print '
'.$langs->trans('Description').''.$langs->trans('Date').''.$langs->trans('Duration').' 
'; - print ''; // ancre pour retourner sur la ligne - print dol_htmlentitiesbr($objp->description); + print '
'; + print ''; - // Date - print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + $var=true; + while ($i < $num) + { + $objp = $db->fetch_object($resql); + $var=!$var; - // Duration - print ''; - - print "\n"; - - - // Icone d'edition et suppression - if ($object->statut == 0 && $user->rights->ficheinter->creer) + // Ligne en mode visu + if ($action != 'editline' || GETPOST('line_id','int') != $objp->rowid) { - print ''; - print ''; - if ($num > 1) + print ''; + print ''; + + // Duration + print ''; + + print "\n"; + + + // Icone d'edition et suppression + if ($object->statut == 0 && $user->rights->ficheinter->creer) { print ''; + print ''; + if ($num > 1) + { + print ''; + } } - } - else - { - print ''; + else + { + print ''; + } + + print ''; + + $line = new FichinterLigne($db); + $line->fetch($objp->rowid); + + $extrafieldsline = new ExtraFields($db); + $extralabelslines=$extrafieldsline->fetch_name_optionals_label($line->table_element); + + $line->fetch_optionals($line->rowid, $extralabelslines); + + print $line->showOptionals($extrafieldsline, 'view', array('style'=>$bc[$var], 'colspan'=>5)); + + } - print ''; + // Line in update mode + if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id','int') == $objp->rowid) + { + print ''; + print ''; + + // Date d'intervention + print ''; + + // Duration + print ''; + + print ''; + print '' . "\n"; + + $line = new FichinterLigne($db); + $line->fetch($objp->rowid); + + $extrafieldsline = new ExtraFields($db); + $extralabelslines=$extrafieldsline->fetch_name_optionals_label($line->table_element); + $line->fetch_optionals($line->rowid, $extralabelslines); + + print $line->showOptionals($extrafieldsline, 'edit', array('style'=>$bc[$var], 'colspan'=>5)); + + + } + + $i++; } - // Line in update mode - if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id','int') == $objp->rowid) - { - print ''; - print '
'.dol_print_date($db->jdate($objp->date_intervention),'dayhour').'
'.$langs->trans('Description').''.$langs->trans('Date').''.$langs->trans('Duration').' 
'.convertSecondToTime($objp->duree).''; - print 'rowid.'#'.$objp->rowid.'">'; - print img_edit(); - print ''; - print ''; - print 'rowid.'">'; - print img_delete(); - print '
'; + print ''; // ancre pour retourner sur la ligne + print dol_htmlentitiesbr($objp->description); + + // Date + print ''.dol_print_date($db->jdate($objp->date_intervention),'dayhour').''.convertSecondToTime($objp->duree).''; - if ($i > 0) - { - print 'rowid.'">'; - print img_up(); - print ''; - } - if ($i < $num-1) - { - print 'rowid.'">'; - print img_down(); - print ''; - } + print 'rowid.'#'.$objp->rowid.'">'; + print img_edit(); + print ''; print ''; + print 'rowid.'">'; + print img_delete(); + print ''; + if ($i > 0) + { + print 'rowid.'">'; + print img_up(); + print ''; + } + if ($i < $num-1) + { + print 'rowid.'">'; + print img_down(); + print ''; + } + print '  
'; + print ''; // ancre pour retourner sur la ligne + + // Editeur wysiwyg + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor=new DolEditor('np_desc',$objp->description,'',164,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,ROWS_2,70); + $doleditor->Create(); + print ''; + $form->select_date($db->jdate($objp->date_intervention),'di',1,1,0,"date_intervention"); + print ''; + $form->select_duration('duration',$objp->duree); + print ''; + print '
'; - print ''; // ancre pour retourner sur la ligne + $db->free($resql); - // Editeur wysiwyg + // Add new line + if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + if (! $num) print '
'; + + print ''; + print ''; + print ''; + print ''; + + print ''; + print "\n"; + + $var=false; + + print '\n"; + print ''; - // Date d'intervention + // Date intervention print ''; // Duration print ''; - print ''; - print '' . "\n"; + print ''; + print ''; + + //Line extrafield + + $lineadd = new FichinterLigne($db); + + $extrafieldsline = new ExtraFields($db); + $extralabelslines=$extrafieldsline->fetch_name_optionals_label($lineadd->table_element); + + print $lineadd->showOptionals($extrafieldsline, 'edit', array('style'=>$bc[$var], 'colspan'=>5)); + + if (! $num) print '
'; + print ''; // ancre + print $langs->trans('Description').''.$langs->trans('Date').''.$langs->trans('Duration').' 
'; + // editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('np_desc',$objp->description,'',164,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,ROWS_2,70); + $doleditor=new DolEditor('np_desc',GETPOST('np_desc','alpha'),'',100,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,ROWS_2,70); $doleditor->Create(); print ''; - $form->select_date($db->jdate($objp->date_intervention),'di',1,1,0,"date_intervention"); + $now=dol_now(); + $timearray=dol_getdate($now); + if (! GETPOST('diday','int')) $timewithnohour=dol_mktime(0,0,0,$timearray['mon'],$timearray['mday'],$timearray['year']); + else $timewithnohour=dol_mktime(GETPOST('dihour','int'),GETPOST('dimin','int'), 0,GETPOST('dimonth','int'),GETPOST('diday','int'),GETPOST('diyear','int')); + $form->select_date($timewithnohour,'di',1,1,0,"addinter"); print ''; - $form->select_duration('duration',$objp->duree); + $selectmode='select'; + if (! empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) $selectmode='text'; + $form->select_duration('duration', (!GETPOST('durationhour','int') && !GETPOST('durationmin','int'))?3600:(60*60*GETPOST('durationhour','int')+60*GETPOST('durationmin','int')), 0, $selectmode, 1); print ''; - print '
'; } - $i++; + if ($num) print '
'; } - - $db->free($resql); - - // Add new line - if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline') + else { - if (! $num) print '
'; - - print ''; - print ''; - print ''; - print ''; - - print ''; - print "\n"; - - $var=false; - - print '\n"; - print ''; - - // Date intervention - print ''; - - // Duration - print ''; - - print ''; - print ''; - - if (! $num) print '
'; - print ''; // ancre - print $langs->trans('Description').''.$langs->trans('Date').''.$langs->trans('Duration').' 
'; - // editeur wysiwyg - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor=new DolEditor('np_desc',GETPOST('np_desc','alpha'),'',100,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,ROWS_2,70); - $doleditor->Create(); - print ''; - $now=dol_now(); - $timearray=dol_getdate($now); - if (! GETPOST('diday','int')) $timewithnohour=dol_mktime(0,0,0,$timearray['mon'],$timearray['mday'],$timearray['year']); - else $timewithnohour=dol_mktime(GETPOST('dihour','int'),GETPOST('dimin','int'), 0,GETPOST('dimonth','int'),GETPOST('diday','int'),GETPOST('diyear','int')); - $form->select_date($timewithnohour,'di',1,1,0,"addinter"); - print ''; - $selectmode='select'; - if (! empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) $selectmode='text'; - $form->select_duration('duration', (!GETPOST('durationhour','int') && !GETPOST('durationmin','int'))?3600:(60*60*GETPOST('durationhour','int')+60*GETPOST('durationmin','int')), 0, $selectmode, 1); - print '
'; + dol_print_error($db); } - if ($num) print '
'; - } - else - { - dol_print_error($db); - } + print '
'."\n"; + } - print ''."\n"; + dol_fiche_end(); - print ''; print "\n"; /* * Actions buttons */ + print '
'; - if ($user->societe_id == 0) + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if (empty($reshook)) { - if ($action != 'editdescription' && ($action != 'presend')) + if ($user->societe_id == 0) { - // Validate - if ($object->statut == 0 && $user->rights->ficheinter->creer && count($object->lines) > 0) + if ($action != 'editdescription' && ($action != 'presend')) { - print ''; - } - - // Modify - if ($object->statut == 1 && $user->rights->ficheinter->creer) - { - print ''; - } - - // Send - if ($object->statut > 0) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) + // Validate + if ($object->statut == 0 && $user->rights->ficheinter->creer && (count($object->lines) > 0 || ! empty($conf->global->FICHINTER_DISABLE_DETAILS))) { - print ''; - } - else print ''; - } - - // Invoicing - if (! empty($conf->facture->enabled) && $object->statut > 0) - { - $langs->load("bills"); - if ($object->statut < 2) - { - if ($user->rights->facture->creer) print ''; - else print ''; + print ''; } - if (! empty($conf->global->FICHINTER_CLASSIFY_BILLED)) + // Modify + if ($object->statut == 1 && $user->rights->ficheinter->creer) { - if ($object->statut != 2) + print ''; + } + + // Send + if ($object->statut > 0) + { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) { - print ''; + print ''; + } + else print ''; + } + + // Event agenda + if (! empty($conf->global->FICHINTER_ADDLINK_TO_EVENT)) + { + if (! empty($conf->agenda->enabled) && $object->statut > 0) + { + $langs->load("agenda"); + if ($object->statut < 2) + { + if ($user->rights->agenda->myactions->create) print ''; + else print ''; + } } } - } - // Delete - if (($object->statut == 0 && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) - { - print ''; - } + // Proposal + if (! empty($conf->propal->enabled) && $object->statut > 0) + { + $langs->load("propal"); + if ($object->statut < 2) + { + if ($user->rights->propal->creer) print ''; + else print ''; + } + } + // Invoicing + if (! empty($conf->facture->enabled) && $object->statut > 0) + { + $langs->load("bills"); + if ($object->statut < 2) + { + if ($user->rights->facture->creer) print ''; + else print ''; + } + + if (! empty($conf->global->FICHINTER_CLASSIFY_BILLED)) + { + if ($object->statut != 2) + { + print ''; + } + else + { + print ''; + } + } + } + + // Delete + if (($object->statut == 0 && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) + { + print ''; + } + + } } } @@ -1595,7 +1691,7 @@ else if ($id > 0 || ! empty($ref)) /* * Built documents - */ + */ $filename=dol_sanitizeFileName($object->ref); $filedir=$conf->ficheinter->dir_output . "/".$object->ref; $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; @@ -1629,7 +1725,7 @@ else if ($id > 0 || ! empty($ref)) /* * Action presend - */ + */ if ($action == 'presend') { $ref = dol_sanitizeFileName($object->ref); @@ -1637,20 +1733,24 @@ else if ($id > 0 || ! empty($ref)) $fileparams = dol_most_recent_file($conf->ficheinter->dir_output . '/' . $ref, preg_quote($ref,'/')); $file=$fileparams['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->client->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('interventions'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - $result=fichinter_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { @@ -1667,6 +1767,7 @@ else if ($id > 0 || ! empty($ref)) // Create form object include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -1677,7 +1778,7 @@ else if ($id > 0 || ! empty($ref)) $formmail->withto=GETPOST("sendto")?GETPOST("sendto"):$liste; $formmail->withtocc=$liste; $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->trans('SendInterventionRef','__FICHINTERREF__'); + $formmail->withtopic=$outputlangs->trans('SendInterventionRef','__FICHINTERREF__'); $formmail->withfile=2; $formmail->withbody=1; $formmail->withdeliveryreceipt=1; diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 5c556ff2356..bc12821530f 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2010 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2013 Juanjo Menent * @@ -24,10 +24,11 @@ * \brief Fichier de la classe des gestion des fiches interventions */ require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php'; /** - * Classe des gestion des fiches interventions + * Class to manage interventions */ class Fichinter extends CommonObject { @@ -151,7 +152,7 @@ class Fichinter extends CommonObject $sql.= ", ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -162,10 +163,21 @@ class Fichinter extends CommonObject $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->ref."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; } + + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + // Add linked object if (! $error && $this->origin && $this->origin_id) { @@ -176,13 +188,10 @@ class Fichinter extends CommonObject if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('FICHINTER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } + // Call trigger + $result=$this->call_trigger('FICHINTER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } if (! $error) @@ -201,7 +210,6 @@ class Fichinter extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -232,22 +240,19 @@ class Fichinter extends CommonObject $sql.= ", fk_projet = ".$this->fk_project; $sql.= ", note_private = ".($this->note_private?"'".$this->db->escape($this->note_private)."'":"null"); $sql.= ", note_public = ".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null"); + $sql.= ", fk_user_modif = ".$user->id; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); if ($this->db->query($sql)) { if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('FICHINTER_MODIFY',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('FICHINTER_MODIFY',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -256,7 +261,6 @@ class Fichinter extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::update error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -275,12 +279,12 @@ class Fichinter extends CommonObject $sql.= " f.datec,"; $sql.= " f.date_valid as datev,"; $sql.= " f.tms as datem,"; - $sql.= " f.duree, f.fk_projet, f.note_public, f.note_private, f.model_pdf, f.extraparams"; + $sql.= " f.duree, f.fk_projet, f.note_public, f.note_private, f.model_pdf, f.extraparams, fk_contrat"; $sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f"; if ($ref) $sql.= " WHERE f.ref='".$this->db->escape($ref)."'"; else $sql.= " WHERE f.rowid=".$rowid; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -301,6 +305,7 @@ class Fichinter extends CommonObject $this->note_public = $obj->note_public; $this->note_private = $obj->note_private; $this->modelpdf = $obj->model_pdf; + $this->fk_contrat = $obj->fk_contrat; $this->extraparams = (array) json_decode($obj->extraparams, true); @@ -326,7 +331,6 @@ class Fichinter extends CommonObject else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch ".$this->error,LOG_ERR); return -1; } } @@ -350,7 +354,7 @@ class Fichinter extends CommonObject $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; - dol_syslog("Fichinter::setDraft sql=".$sql); + dol_syslog("Fichinter::setDraft", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -361,7 +365,6 @@ class Fichinter extends CommonObject { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog("Fichinter::setDraft ".$this->error,LOG_ERR); return -1; } } @@ -371,11 +374,12 @@ class Fichinter extends CommonObject * Validate a intervention * * @param User $user User that validate - * @return int <0 if KO, >0 if OK + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers + * @return int <0 if KO, >0 if OK */ - function setValid($user) + function setValid($user, $notrigger=0) { - global $langs, $conf; + global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $error=0; @@ -395,6 +399,7 @@ class Fichinter extends CommonObject { $num = $this->ref; } + $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql.= " SET fk_statut = 1"; @@ -405,18 +410,25 @@ class Fichinter extends CommonObject $sql.= " AND entity = ".$conf->entity; $sql.= " AND fk_statut = 0"; - dol_syslog(get_class($this)."::setValid sql=".$sql); + dol_syslog(get_class($this)."::setValid", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::setValid Echec update - 10 - sql=".$sql, LOG_ERR); dol_print_error($this->db); $error++; } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('FICHINTER_VALIDATE',$user); + if ($result < 0) { $error++; } + // End call triggers + } + if (! $error) { - $this->oldref = ''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) @@ -424,20 +436,26 @@ class Fichinter extends CommonObject // Rename of object directory ($this->ref = old ref, $num = new ref) // to not lose the linked files $oldref = dol_sanitizeFileName($this->ref); - $snum = dol_sanitizeFileName($num); + $newref = dol_sanitizeFileName($num); $dirsource = $conf->ficheinter->dir_output.'/'.$oldref; - $dirdest = $conf->ficheinter->dir_output.'/'.$snum; + $dirdest = $conf->ficheinter->dir_output.'/'.$newref; if (file_exists($dirsource)) { - dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); + dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { - $this->oldref = $oldref; - - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($conf->ficheinter->dir_output.'/'.$snum.'/'.$oldref.'*.*'); + dol_syslog("Rename ok"); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -452,18 +470,6 @@ class Fichinter extends CommonObject $this->date_validation=$now; } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('FICHINTER_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } - if (! $error) { $this->db->commit(); @@ -478,31 +484,6 @@ class Fichinter extends CommonObject } } - /** - * Set intervetnion as billed - * - * @return int <0 si ko, >0 si ok - */ - function setBilled() - { - global $conf; - - $sql = 'UPDATE '.MAIN_DB_PREFIX.'fichinter SET fk_statut = 2'; - $sql.= ' WHERE rowid = '.$this->id; - $sql.= " AND entity = ".$conf->entity; - $sql.= " AND fk_statut = 1"; - - if ($this->db->query($sql) ) - { - return 1; - } - else - { - dol_print_error($this->db); - return -1; - } - } - /** * Returns the label status @@ -573,7 +554,7 @@ class Fichinter extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='intervention'; @@ -647,9 +628,11 @@ class Fichinter extends CommonObject global $conf; $sql = "SELECT f.rowid,"; - $sql.= " datec,"; + $sql.= " f.datec,"; + $sql.= " f.tms as date_modification,"; $sql.= " f.date_valid as datev,"; $sql.= " f.fk_user_author,"; + $sql.= " f.fk_user_modif as fk_user_modification,"; $sql.= " f.fk_user_valid"; $sql.= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql.= " WHERE f.rowid = ".$id; @@ -665,6 +648,7 @@ class Fichinter extends CommonObject $this->id = $obj->rowid; $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = $this->db->jdate($obj->date_modification); $this->date_validation = $this->db->jdate($obj->datev); $cuser = new User($this->db); @@ -677,6 +661,13 @@ class Fichinter extends CommonObject $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } + if ($obj->fk_user_modification) + { + $muser = new User($this->db); + $muser->fetch($obj->fk_user_modification); + $this->user_modification = $muser; + } + } $this->db->free($resql); } @@ -723,14 +714,14 @@ class Fichinter extends CommonObject $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql.= " WHERE fk_fichinter = ".$this->id; - dol_syslog("Fichinter::delete sql=".$sql); + dol_syslog("Fichinter::delete", LOG_DEBUG); if ( $this->db->query($sql) ) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter"; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; - dol_syslog("Fichinter::delete sql=".$sql); + dol_syslog("Fichinter::delete", LOG_DEBUG); if ( $this->db->query($sql) ) { @@ -762,14 +753,10 @@ class Fichinter extends CommonObject if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('FICHINTER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('FICHINTER_DELETE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } $this->db->commit(); @@ -828,7 +815,7 @@ class Fichinter extends CommonObject * * @param User $user Object user who modify * @param string $description description - * @return int <0 if ko, >0 if ok + * @return int <0 if KO, >0 if OK */ function set_description($user, $description) { @@ -837,10 +824,10 @@ class Fichinter extends CommonObject if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; - $sql.= " SET description = '".$this->db->escape($description)."'"; + $sql.= " SET description = '".$this->db->escape($description)."',"; + $sql.= " fk_user_modif = ".$user->id; $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; - $sql.= " AND fk_statut = 0"; if ($this->db->query($sql)) { @@ -875,7 +862,6 @@ class Fichinter extends CommonObject $sql.= " WHERE rowid = ".$this->id; $sql.= " AND entity = ".$conf->entity; - dol_syslog("sql=".$sql); if ($this->db->query($sql)) { $this->fk_contrat = $contractid; @@ -884,7 +870,6 @@ class Fichinter extends CommonObject else { $this->error=$this->db->error(); - dol_syslog($this->error, LOG_ERR); return -1; } } @@ -899,11 +884,12 @@ class Fichinter extends CommonObject * @param string $desc Line description * @param date $date_intervention Intervention date * @param int $duration Intervention duration + * @param array $array_option Array option * @return int >0 if ok, <0 if ko */ - function addline($user,$fichinterid, $desc, $date_intervention, $duration) + function addline($user,$fichinterid, $desc, $date_intervention, $duration, $array_option='') { - dol_syslog("Fichinter::Addline $fichinterid, $desc, $date_intervention, $duration"); + dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration"); if ($this->statut == 0) { @@ -917,8 +903,13 @@ class Fichinter extends CommonObject $line->datei = $date_intervention; $line->duration = $duration; + if (is_array($array_option) && count($array_option)>0) { + $line->array_options=$array_option; + } + $result=$line->insert($user); - if ($result > 0) + + if ($result >= 0) { $this->db->commit(); return 1; @@ -926,7 +917,6 @@ class Fichinter extends CommonObject else { $this->error=$this->db->error(); - dol_syslog("Error sql=$sql, error=".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -981,9 +971,9 @@ class Fichinter extends CommonObject { $sql = 'SELECT rowid, description, duree, date, rang'; $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet'; - $sql.= ' WHERE fk_fichinter = '.$this->id; + $sql.=' WHERE fk_fichinter = '.$this->id .' ORDER BY rang ASC' ; - dol_syslog(get_class($this)."::fetch_lines sql=".$sql); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1021,7 +1011,7 @@ class Fichinter extends CommonObject /** * Classe permettant la gestion des lignes d'intervention */ -class FichinterLigne +class FichinterLigne extends CommonObjectLine { var $db; var $error; @@ -1034,6 +1024,9 @@ class FichinterLigne var $duration; // Duree de l'intervention var $rang = 0; + public $element='fichinterdet'; + public $table_element='fichinterdet'; + public $fk_element='fk_fichinter'; /** * Constructor @@ -1058,12 +1051,13 @@ class FichinterLigne $sql.= ' FROM '.MAIN_DB_PREFIX.'fichinterdet as ft'; $sql.= ' WHERE ft.rowid = '.$rowid; - dol_syslog("FichinterLigne::fetch sql=".$sql); + dol_syslog("FichinterLigne::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; + $this->id = $objp->rowid; $this->fk_fichinter = $objp->fk_fichinter; $this->datei = $this->db->jdate($objp->datei); $this->desc = $objp->description; @@ -1076,7 +1070,6 @@ class FichinterLigne else { $this->error=$this->db->error().' sql='.$sql; - dol_print_error($this->db,$this->error, LOG_ERR); return -1; } } @@ -1126,25 +1119,35 @@ class FichinterLigne $sql.= ' '.$rangToUse; $sql.= ')'; - dol_syslog("FichinterLigne::insert sql=".$sql); + dol_syslog("FichinterLigne::insert", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { + $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet'); + + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + + $result=$this->update_total(); + if ($result > 0) { $this->rang=$rangToUse; if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $resulttrigger=$interface->run_triggers('LINEFICHINTER_CREATE',$this,$user,$langs,$conf); - if ($resulttrigger < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_CREATE',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -1161,7 +1164,6 @@ class FichinterLigne else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog("FichinterLigne::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1189,24 +1191,31 @@ class FichinterLigne $sql.= ",rang='".$this->rang."'"; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("FichinterLigne::update sql=".$sql); + dol_syslog("FichinterLigne::update", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { + + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $this->id=$this->rowid; + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + $result=$this->update_total(); if ($result > 0) { if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $resulttrigger=$interface->run_triggers('LINEFICHINTER_UPDATE',$this,$user,$langs,$conf); - if ($resulttrigger < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_UPDATE',$user); + if ($result < 0) { $error++; } + // End call triggers } } @@ -1218,7 +1227,6 @@ class FichinterLigne else { $this->error=$this->db->lasterror(); - dol_syslog("FichinterLigne::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1226,7 +1234,6 @@ class FichinterLigne else { $this->error=$this->db->lasterror(); - dol_syslog("FichinterLigne::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1247,7 +1254,7 @@ class FichinterLigne $sql.= " FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql.= " WHERE fk_fichinter=".$this->fk_fichinter; - dol_syslog("FichinterLigne::update_total sql=".$sql); + dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1260,7 +1267,7 @@ class FichinterLigne $sql.= " WHERE rowid = ".$this->fk_fichinter; $sql.= " AND entity = ".$conf->entity; - dol_syslog("FichinterLigne::update_total sql=".$sql); + dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1270,7 +1277,6 @@ class FichinterLigne else { $this->error=$this->db->error(); - dol_syslog("FichinterLigne::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -1278,7 +1284,6 @@ class FichinterLigne else { $this->error=$this->db->error(); - dol_syslog("FichinterLigne::update Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1302,28 +1307,22 @@ class FichinterLigne $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->rowid; $resql = $this->db->query($sql); - dol_syslog(get_class($this)."::deleteline sql=".$sql); if ($resql) { $result = $this->update_total(); if ($result > 0) { - $this->db->commit(); - if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $resulttrigger=$interface->run_triggers('LINEFICHINTER_DELETE',$this,$user,$langs,$conf); - if ($resulttrigger < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEFICHINTER_DELETE',$user); + if ($result < 0) { $error++; $this->db->rollback(); return -1; } + // End call triggers } - return $result; + $this->db->commit(); + return $result; } else { @@ -1334,7 +1333,6 @@ class FichinterLigne else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } diff --git a/htdocs/fichinter/class/index.html b/htdocs/fichinter/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index f5f355b315a..b0f9ada3af7 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -64,15 +64,14 @@ if ($action == 'addcontact' && $user->rights->ficheinter->creer) } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; - } - else - { - $mesg = '
'.$object->error.'
'; + $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); + } else { + $mesg = $object->error; } + + setEventMessage($mesg, 'errors'); } } @@ -109,9 +108,7 @@ $userstatic=new User($db); llxHeader(); - // Mode vue et edition -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { @@ -147,6 +144,9 @@ if ($id > 0 || ! empty($ref)) print '
'; + if (! empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser=1; + if (! empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) $hideaddcontactforthirdparty=1; + // Contacts lines include DOL_DOCUMENT_ROOT.'/core/tpl/contacts.tpl.php'; } diff --git a/htdocs/fichinter/index.html b/htdocs/fichinter/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/fichinter/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index aa18223c0c5..9030cd9c4ac 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2012 Juanjo Menent * Copyright (C) 2013 Cédric Salvador @@ -31,6 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->load("companies"); +$langs->load("bills"); $langs->load("interventions"); $socid=GETPOST('socid','int'); @@ -48,30 +49,45 @@ $offset = $conf->liste_limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; if (! $sortorder) $sortorder="DESC"; -if (! $sortfield) $sortfield="fd.date"; +if (! $sortfield) +{ + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sortfield="fd.date"; + else $sortfield="f.ref"; +} $limit = $conf->liste_limit; -$search_ref=GETPOST('search_ref','alpha'); +$search_ref=GETPOST('search_ref')?GETPOST('search_ref','alpha'):GETPOST('search_inter','alpha'); $search_company=GETPOST('search_company','alpha'); $search_desc=GETPOST('search_desc','alpha'); +$search_status=GETPOST('search_status'); +$sall=GETPOST('sall'); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_company=""; + $search_desc=""; + $search_status=""; +} /* * View */ -llxHeader(); +$form = new Form($db); +$interventionstatic=new Fichinter($db); + +llxHeader('', $langs->trans("Intervention")); $sql = "SELECT"; $sql.= " f.ref, f.rowid as fichid, f.fk_statut, f.description,"; -$sql.= " fd.description as descriptiondetail, fd.date as dp, fd.duree,"; -$sql.= " s.nom, s.rowid as socid, s.client"; +if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql.= " fd.description as descriptiondetail, fd.date as dp, fd.duree,"; +$sql.= " s.nom as name, s.rowid as socid, s.client"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s"; -if (! $user->rights->societe->client->voir && empty($socid)) - $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (! $user->rights->societe->client->voir && empty($socid)) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= ", ".MAIN_DB_PREFIX."fichinter as f)"; -$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; +if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; $sql.= " WHERE f.fk_soc = s.rowid "; $sql.= " AND f.entity = ".$conf->entity; if ($search_ref) { @@ -81,36 +97,48 @@ if ($search_company) { $sql .= natural_search('s.nom', $search_company); } if ($search_desc) { - $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + else $sql .= natural_search(array('f.description'), $search_desc); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= ' AND f.fk_statut = '.$search_status; } if (! $user->rights->societe->client->voir && empty($socid)) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid) $sql.= " AND s.rowid = " . $socid; -$sql.= " ORDER BY ".$sortfield." ".$sortorder; +if ($sall) { + $arraytosearch=array('f.ref', 'f.description', 's.nom'); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) $arraytosearch=array('f.ref', 'f.description', 's.nom', 'fd.description'); + $sql .= natural_search($arraytosearch, $sall); +} +$sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($limit+1, $offset); +//print $sql; $result=$db->query($sql); if ($result) { $num = $db->num_rows($result); - $interventionstatic=new Fichinter($db); - $urlparam="&socid=$socid"; print_barre_liste($langs->trans("ListOfInterventions"), $page, $_SERVER['PHP_SELF'], $urlparam, $sortfield, $sortorder, '', $num); - print '
'."\n"; + print ''."\n"; print ''; print ''; print_liste_field_titre($langs->trans("Ref"),$_SERVER["PHP_SELF"],"f.ref","",$urlparam,'width="15%"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom","",$urlparam,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Description"),$_SERVER["PHP_SELF"],"f.description","",$urlparam,'',$sortfield,$sortorder); - print_liste_field_titre('',$_SERVER["PHP_SELF"],''); - print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"fd.date","",$urlparam,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Duration"),$_SERVER["PHP_SELF"],"fd.duree","",$urlparam,'align="right"',$sortfield,$sortorder); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + print_liste_field_titre('',$_SERVER["PHP_SELF"],''); + print_liste_field_titre($langs->trans("Date"),$_SERVER["PHP_SELF"],"fd.date","",$urlparam,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Duration"),$_SERVER["PHP_SELF"],"fd.duree","",$urlparam,'align="right"',$sortfield,$sortorder); + } print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"f.fk_statut","",$urlparam,'align="right"',$sortfield,$sortorder); + print_liste_field_titre('',$_SERVER["PHP_SELF"], ''); print "\n"; print ''; @@ -121,11 +149,20 @@ if ($result) print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + // Desc of line + print ''; + print ''; + print ''; + } + print ''; + print '\n"; $companystatic=new Societe($db); @@ -143,26 +180,34 @@ if ($result) print $interventionstatic->getNomUrl(1); print "\n"; print ''; print ''; - print ''; - print '\n"; - print ''; + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + print ''; + print '\n"; + print ''; + } print ''; - + + print ''; print "\n"; $total += $objp->duree; $i++; } - print ''; - print ''; - print ''; - + $rowspan=3; + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + print ''; + print ''; + print ''; + } + print '
'; print ''; print '   
   '; + $liststatus=$interventionstatic->statuts_short; + print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); + print ''; + print ''; + print "
'; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; $companystatic->id=$objp->socid; $companystatic->client=$objp->client; print $companystatic->getNomUrl(1,'',44); print ''.dol_htmlentitiesbr(dol_trunc($objp->description,20)).''.dol_htmlentitiesbr(dol_trunc($objp->descriptiondetail,20)).''.dol_print_date($db->jdate($objp->dp),'dayhour')."'.convertSecondToTime($objp->duree).''.dol_htmlentitiesbr(dol_trunc($objp->descriptiondetail,20)).''.dol_print_date($db->jdate($objp->dp),'dayhour')."'.convertSecondToTime($objp->duree).''.$interventionstatic->LibStatut($objp->fk_statut,5).' 
'.$langs->trans("Total").''.convertSecondToTime($total).' 
'.$langs->trans("Total").''.convertSecondToTime($total).'  
'; print "
\n"; $db->free($result); diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index d263620ae47..3c5fce7caa2 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -60,8 +60,6 @@ $form = new Form($db); if ($id > 0 || ! empty($ref)) { - dol_htmloutput_mesg($mesg); - $societe = new Societe($db); if ($societe->fetch($object->socid)) { diff --git a/htdocs/fichinter/tpl/index.html b/htdocs/fichinter/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php index e104bea2a7a..4e0d6b753e7 100644 --- a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php @@ -42,7 +42,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > - trans("ShowIntervention"),"intervention").' '.$object->ref; ?> + trans("ShowIntervention"),"intervention").' '.$object->ref; ?> datev,'day'); ?> getLibStatut(3); ?> diff --git a/htdocs/filefunc.inc.php b/htdocs/filefunc.inc.php index 8066c2a1a22..d69de2f1fae 100644 --- a/htdocs/filefunc.inc.php +++ b/htdocs/filefunc.inc.php @@ -29,7 +29,7 @@ * \brief File that include conf.php file and commons lib like functions.lib.php */ -if (! defined('DOL_VERSION')) define('DOL_VERSION','3.6.1'); +if (! defined('DOL_VERSION')) define('DOL_VERSION','3.7.0-beta'); if (! defined('EURO')) define('EURO',chr(128)); // Define syslog constants @@ -92,7 +92,7 @@ if (! empty($dolibarr_main_prod)) ini_set('display_errors','Off'); // Clean parameters $dolibarr_main_data_root=trim($dolibarr_main_data_root); -$dolibarr_main_url_root=trim($dolibarr_main_url_root); +$dolibarr_main_url_root=trim(preg_replace('/\/+$/','',$dolibarr_main_url_root)); $dolibarr_main_url_root_alt=(empty($dolibarr_main_url_root_alt)?'':trim($dolibarr_main_url_root_alt)); $dolibarr_main_document_root=trim($dolibarr_main_document_root); $dolibarr_main_document_root_alt=(empty($dolibarr_main_document_root_alt)?'':trim($dolibarr_main_document_root_alt)); diff --git a/htdocs/fourn/ajax/getSupplierPrices.php b/htdocs/fourn/ajax/getSupplierPrices.php index bbe3aeba4dc..a6695dc694d 100644 --- a/htdocs/fourn/ajax/getSupplierPrices.php +++ b/htdocs/fourn/ajax/getSupplierPrices.php @@ -13,7 +13,6 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * */ /** @@ -49,7 +48,7 @@ if (! empty($idprod)) $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration,"; $sql.= " pfp.ref_fourn,"; $sql.= " pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice, pfp.charges, pfp.unitcharges,"; - $sql.= " s.nom"; + $sql.= " s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = pfp.fk_product"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = pfp.fk_soc"; @@ -58,7 +57,7 @@ if (! empty($idprod)) $sql.= " AND s.fournisseur = 1"; $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC"; - dol_syslog("Ajax::getSupplierPrices sql=".$sql, LOG_DEBUG); + dol_syslog("Ajax::getSupplierPrices", LOG_DEBUG); $result=$db->query($sql); if ($result) @@ -75,7 +74,7 @@ if (! empty($idprod)) $price = $objp->fprice * (1 - $objp->remise_percent / 100); $unitprice = $objp->unitprice * (1 - $objp->remise_percent / 100); - $title = $objp->nom.' - '.$objp->ref_fourn.' - '; + $title = $objp->name.' - '.$objp->ref_fourn.' - '; if ($objp->quantity == 1) { diff --git a/htdocs/fourn/ajax/index.html b/htdocs/fourn/ajax/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/fiche.php b/htdocs/fourn/card.php similarity index 74% rename from htdocs/fourn/fiche.php rename to htdocs/fourn/card.php index 2719f9e0a9b..3e234af68cd 100644 --- a/htdocs/fourn/fiche.php +++ b/htdocs/fourn/card.php @@ -1,9 +1,10 @@ * Copyright (C) 2003 Eric Seigne - * Copyright (C) 2004-2011 Laurent Destailleur + * Copyright (C) 2004-2014 Laurent Destailleur * Copyright (C) 2005-2010 Regis Houssin - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent + * Copyright (C) 2014 Jean Heimburger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -20,7 +21,7 @@ */ /** - * \file htdocs/fourn/fiche.php + * \file htdocs/fourn/card.php * \ingroup fournisseur, facture * \brief Page for supplier third party card (view, edit) */ @@ -49,15 +50,16 @@ $result = restrictedArea($user, 'societe&fournisseur', $id, '&societe'); $object = new Fournisseur($db); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('suppliercard')); - -$parameters = array('id' => $id); -$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$hookmanager->initHooks(array('suppliercard','globalcard')); /* * Action */ +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($action == 'setsupplieraccountancycode') { $result=$object->fetch($id); @@ -172,38 +174,26 @@ if ($object->fetch($id)) print ''; // Local Taxes - //TODO: Place into a function to control showing by country or study better option - if($mysoc->country_code=='ES') + if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") { - if($mysoc->localtax1_assuj=="1" && $mysoc->localtax2_assuj=="1") - { - print ''.$langs->trans('LocalTax1IsUsedES').''; - print yn($object->localtax1_assuj); - print ''; - print ''.$langs->trans('LocalTax2IsUsedES').''; - print yn($object->localtax2_assuj); - print ''; - } - elseif($mysoc->localtax1_assuj=="1") - { - print ''.$langs->trans("LocalTax1IsUsedES").''; - print yn($object->localtax1_assuj); - print ''; - } - elseif($mysoc->localtax2_assuj=="1") - { - print ''.$langs->trans("LocalTax2IsUsedES").''; - print yn($object->localtax2_assuj); - print ''; - } - - if ($mysoc->localtax2_assuj!="1") - { - print ''.$langs->transcountry("LocalTax2IsUsed",$mysoc->country_code).''; - print yn($object->localtax2_assuj); - print ''; - } - + print ''.$langs->trans('LocalTax1IsUsedES').''; + print yn($object->localtax1_assuj); + print ''; + print ''.$langs->trans('LocalTax2IsUsedES').''; + print yn($object->localtax2_assuj); + print ''; + } + elseif($mysoc->localtax1_assuj=="1") + { + print ''.$langs->trans("LocalTax1IsUsedES").''; + print yn($object->localtax1_assuj); + print ''; + } + elseif($mysoc->localtax2_assuj=="1") + { + print ''.$langs->trans("LocalTax2IsUsedES").''; + print yn($object->localtax2_assuj); + print ''; } // TVA Intra @@ -300,7 +290,7 @@ if ($object->fetch($id)) print ''; print ''; print '
'.$langs->trans("ProductsAndServices").''; - print ''.$langs->trans("All").' ('.$object->nbOfProductRefs().')'; + print ''.$langs->trans("All").' ('.$object->nbOfProductRefs().')'; print '
'; } @@ -314,6 +304,28 @@ if ($object->fetch($id)) if ($user->rights->fournisseur->commande->lire) { + + + // TODO move to DAO class + // Check if there are supplier orders billable + $sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_supplier,'; + $sql2.= ' c.date_valid, c.date_commande, c.date_livraison, c.fk_statut'; + $sql2.= ' FROM '.MAIN_DB_PREFIX.'societe as s'; + $sql2.= ', '.MAIN_DB_PREFIX.'commande_fournisseur as c'; + $sql2.= ' WHERE c.fk_soc = s.rowid'; + $sql2.= ' AND s.rowid = '.$object->id; + // Show orders with status validated, shipping started and delivered (well any order we can bill) + $sql2.= " AND c.fk_statut IN (5)"; + // Find order that are not already invoiced + $sql2 .= " AND c.rowid NOT IN (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE targettype='invoice_supplier')"; + $resql2=$db->query($sql2); + if ($resql2) { + $orders2invoice = $db->num_rows($resql2); + $db->free($resql2); + } else { + setEventMessage($db->lasterror(),'errors'); + } + // TODO move to DAO class $sql = "SELECT p.rowid,p.ref, p.date_commande as dc, p.fk_statut"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p "; @@ -334,7 +346,7 @@ if ($object->fetch($id)) print ''; print ''; print ''; - print ''; + print ''; print ''; print '
'.$langs->trans("LastOrders",($num<$MAXLIST?"":$MAXLIST)).''.$langs->trans("AllOrders").' ('.$num.')'.$langs->trans("AllOrders").' ('.$num.')'.img_picto($langs->trans("Statistics"),'stats').'
'; print ''; @@ -346,7 +358,7 @@ if ($object->fetch($id)) $var=!$var; print ""; - print ''.img_object($langs->trans("ShowOrder"),"order")." ".$obj->ref.''; + print ''.img_object($langs->trans("ShowOrder"),"order")." ".$obj->ref.''; print ''; if ($obj->dc) { @@ -382,13 +394,13 @@ if ($object->fetch($id)) if ($user->rights->fournisseur->facture->lire) { // TODO move to DAO class - $sql = 'SELECT f.rowid,f.libelle,f.ref_supplier,f.fk_statut,f.datef as df,f.total_ttc as amount,f.paye,'; + $sql = 'SELECT f.rowid,f.libelle,f.ref,f.ref_supplier,f.fk_statut,f.datef as df,f.total_ttc as amount,f.paye,'; $sql.= ' SUM(pf.amount) as am'; $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON f.rowid=pf.fk_facturefourn'; $sql.= ' WHERE f.fk_soc = '.$object->id; $sql.= " AND f.entity =".$conf->entity; - $sql.= ' GROUP BY f.rowid,f.libelle,f.ref_supplier,f.fk_statut,f.datef,f.total_ttc,f.paye'; + $sql.= ' GROUP BY f.rowid,f.libelle,f.ref,f.ref_supplier,f.fk_statut,f.datef,f.total_ttc,f.paye'; $sql.= ' ORDER BY f.datef DESC'; $resql=$db->query($sql); if ($resql) @@ -412,8 +424,14 @@ if ($object->fetch($id)) $var=!$var; print ''; print ''; - print ''; - print img_object($langs->trans('ShowBill'),'bill').' '.$obj->ref_supplier.' '.dol_trunc($obj->libelle,14).''; + print ''; + $facturestatic->id=$obj->rowid; + $facturestatic->ref=($obj->ref?$obj->ref:$obj->rowid).($obj->ref_supplier?' - '.$obj->ref_supplier:''); + //$facturestatic->ref_supplier=$obj->ref_supplier; + print $facturestatic->getNomUrl(1); + //print img_object($langs->trans('ShowBill'),'bill').' '.($obj->ref?$obj->ref:$obj->rowid).' - '.$obj->ref_supplier.''; + print ' '.dol_trunc($obj->libelle,14); + print ''; print ''.dol_print_date($db->jdate($obj->df),'day').''; print ''.price($obj->amount).''; print ''; @@ -440,42 +458,46 @@ if ($object->fetch($id)) /* * Barre d'actions */ - - - print '
'; - $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook - if (empty($reshook)) { - - if ($user->rights->fournisseur->commande->creer) - { - $langs->load("orders"); - print ''.$langs->trans("AddOrder").''; - } - - if ($user->rights->fournisseur->facture->creer) - { - $langs->load("bills"); - print ''.$langs->trans("AddBill").''; - } - - // Add action - if (! empty($conf->agenda->enabled) && ! empty($conf->global->MAIN_REPEATTASKONEACHTAB)) - { - if ($user->rights->agenda->myactions->create) - { - print ''.$langs->trans("AddAction").''; - } - else - { - print ''.$langs->trans("AddAction").''; - } - } - - print '
'; + // modified by hook + if (empty($reshook)) + { + + print '
'; + + if ($user->rights->fournisseur->commande->creer) + { + $langs->load("orders"); + print ''.$langs->trans("AddOrder").''; } + + if ($user->rights->fournisseur->facture->creer) + { + $langs->load("bills"); + print ''.$langs->trans("AddBill").''; + } + + if ($user->rights->fournisseur->facture->creer) + { + if (! empty($orders2invoice) && $orders2invoice > 0) print ''; + else print ''; + } + + // Add action + if (! empty($conf->agenda->enabled) && ! empty($conf->global->MAIN_REPEATTASKONEACHTAB)) + { + if ($user->rights->agenda->myactions->create) + { + print ''.$langs->trans("AddAction").''; + } + else + { + print ''.$langs->trans("AddAction").''; + } + } + + print '
'; print '
'; if (! empty($conf->global->MAIN_REPEATCONTACTONEACHTAB)) @@ -502,6 +524,7 @@ if ($object->fetch($id)) show_actions_done($conf,$langs,$db,$object); } } +} else { dol_print_error($db); diff --git a/htdocs/fourn/class/fournisseur.class.php b/htdocs/fourn/class/fournisseur.class.php index f557573fdfc..35620bf91fb 100644 --- a/htdocs/fourn/class/fournisseur.class.php +++ b/htdocs/fourn/class/fournisseur.class.php @@ -157,7 +157,7 @@ class Fournisseur extends Societe $sql.= " VALUES "; $sql.= " ('".$this->db->escape($name)."',1,1)"; - dol_syslog("Fournisseur::CreateCategory sql=".$sql); + dol_syslog("Fournisseur::CreateCategory", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -184,7 +184,7 @@ class Fournisseur extends Societe $arr = array(); - $sql = "SELECT s.rowid, s.nom"; + $sql = "SELECT s.rowid, s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE s.fournisseur = 1"; @@ -196,16 +196,14 @@ class Fournisseur extends Societe if ($resql) { while ($obj=$this->db->fetch_object($resql)) - { - $arr[$obj->rowid] = stripslashes($obj->nom); - } - + { + $arr[$obj->rowid] = $obj->name; + } } else { dol_print_error($this->db); - $this->error=$this->db->error(); - + $this->error=$this->db->lasterror(); } return $arr; } diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 3aa9d77f5de..b96e7f01c95 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -3,9 +3,9 @@ * Copyright (C) 2004-2012 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2007 Franky Van Liedekerke - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2010-2014 Philippe Grand - * Copyright (C) 2012 Marcos García + * Copyright (C) 2012-2014 Marcos García * Copyright (C) 2013 Florian Henry * Copyright (C) 2013 Cédric Salvador * @@ -74,6 +74,7 @@ class CommandeFournisseur extends CommonOrder var $fk_project; var $cond_reglement_id; var $cond_reglement_code; + var $fk_account; var $mode_reglement_id; var $mode_reglement_code; var $user_author_id; @@ -126,6 +127,7 @@ class CommandeFournisseur extends CommonOrder $sql.= " c.date_creation, c.date_valid, c.date_approve,"; $sql.= " c.fk_user_author, c.fk_user_valid, c.fk_user_approve,"; $sql.= " c.date_commande as date_commande, c.date_livraison as date_livraison, c.fk_cond_reglement, c.fk_mode_reglement, c.fk_projet as fk_project, c.remise_percent, c.source, c.fk_input_method,"; + $sql.= " c.fk_account,"; $sql.= " c.note_private, c.note_public, c.model_pdf, c.extraparams,"; $sql.= " cm.libelle as methode_commande,"; $sql.= " cr.code as cond_reglement_code, cr.libelle as cond_reglement_libelle,"; @@ -138,14 +140,14 @@ class CommandeFournisseur extends CommonOrder if ($ref) $sql.= " AND c.ref='".$this->db->escape($ref)."'"; else $sql.= " AND c.rowid=".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); if (! $obj) { - $this->error='Bill with id '.$id.' not found sql='.$sql; + $this->error='Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; } @@ -180,6 +182,7 @@ class CommandeFournisseur extends CommonOrder $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; $this->cond_reglement_doc = $obj->cond_reglement_libelle; + $this->fk_account = $obj->fk_account; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; @@ -191,7 +194,7 @@ class CommandeFournisseur extends CommonOrder $this->extraparams = (array) json_decode($obj->extraparams, true); $this->db->free($resql); - + // Retreive all extrafield // fetch optionals attributes and labels require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); @@ -207,14 +210,15 @@ class CommandeFournisseur extends CommonOrder $sql.= " l.tva_tx, l.remise_percent, l.subprice,"; $sql.= " l.localtax1_tx, l. localtax2_tx, l.total_localtax1, l.total_localtax2,"; $sql.= " l.total_ht, l.total_tva, l.total_ttc,"; - $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc"; + $sql.= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.description as product_desc,"; + $sql.= " l.date_start, l.date_end"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; $sql.= " WHERE l.fk_commande = ".$this->id; $sql.= " ORDER BY l.rowid"; //print $sql; - dol_syslog(get_class($this)."::fetch get lines sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -255,6 +259,9 @@ class CommandeFournisseur extends CommonOrder $line->ref_fourn = $objp->ref_supplier; // TODO deprecated $line->ref_supplier = $objp->ref_supplier; // Reference supplier + $line->date_start = $this->db->jdate($objp->date_start); + $line->date_end = $this->db->jdate($objp->date_end); + $this->lines[$i] = $line; $i++; @@ -266,14 +273,12 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } else { $this->error=$this->db->error()." sql=".$sql; - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -295,7 +300,7 @@ class CommandeFournisseur extends CommonOrder $sql.= ($comment?"'".$this->db->escape($comment)."'":'null'); $sql.= ")"; - dol_syslog("FournisseurCommande::log sql=".$sql, LOG_DEBUG); + dol_syslog("FournisseurCommande::log", LOG_DEBUG); if ( $this->db->query($sql) ) { return 1; @@ -303,7 +308,6 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::log ".$this->error, LOG_ERR); return -1; } } @@ -313,9 +317,10 @@ class CommandeFournisseur extends CommonOrder * * @param User $user Validator User * @param int $idwarehouse Id of warehouse to use for stock decrease + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, >0 if OK */ - function valid($user,$idwarehouse=0) + function valid($user,$idwarehouse=0,$notrigger=0) { global $langs,$conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -338,12 +343,13 @@ class CommandeFournisseur extends CommonOrder $num = $this->getNextNumRef($soc); } else - { + { $num = $this->ref; } + $this->newref = $num; $sql = 'UPDATE '.MAIN_DB_PREFIX."commande_fournisseur"; - $sql.= " SET ref='".$num."',"; + $sql.= " SET ref='".$this->db->escape($num)."',"; $sql.= " fk_statut = 1,"; $sql.= " date_valid='".$this->db->idate(dol_now())."',"; $sql.= " fk_user_valid = ".$user->id; @@ -353,14 +359,21 @@ class CommandeFournisseur extends CommonOrder $resql=$this->db->query($sql); if (! $resql) { - dol_syslog(get_class($this)."::valid Echec update - 10 - sql=".$sql, LOG_ERR); dol_print_error($this->db); $error++; } + if (! $error && ! $notrigger) + { + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_VALIDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + if (! $error) { - $this->oldref=''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) @@ -377,11 +390,17 @@ class CommandeFournisseur extends CommonOrder if (@rename($dirsource, $dirdest)) { - $this->oldref = $oldref; - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($dirdest.'/'.$oldref.'*.*'); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->fournisseur->dir_output.'/commande/'.$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -394,22 +413,6 @@ class CommandeFournisseur extends CommonOrder $this->ref = $num; } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; - $this->errors=$interface->errors; - $this->db->rollback(); - return -1; - } - // Fin appel triggers - } - if (! $error) { $this->db->commit(); @@ -417,8 +420,6 @@ class CommandeFournisseur extends CommonOrder } else { - $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -434,8 +435,8 @@ class CommandeFournisseur extends CommonOrder /** * Return label of the status of object * - * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label - * @return string Label + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto + * @return string Label */ function getLibStatut($mode=0) { @@ -526,7 +527,7 @@ class CommandeFournisseur extends CommonOrder $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='order'; @@ -622,9 +623,10 @@ class CommandeFournisseur extends CommonOrder $num = $this->getNextNumRef($soc); } else - { + { $num = $this->ref; } + $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql.= " SET ref='".$this->db->escape($num)."',"; @@ -663,12 +665,10 @@ class CommandeFournisseur extends CommonOrder if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_APPROVE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_APPROVE',$user); + if ($result < 0) $error++; + // End call triggers } if (! $error) @@ -686,7 +686,6 @@ class CommandeFournisseur extends CommonOrder { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::approve Error ",$this->error, LOG_ERR); return -1; } } @@ -709,43 +708,32 @@ class CommandeFournisseur extends CommonOrder $error=0; + dol_syslog(get_class($this)."::refuse"); $result = 0; if ($user->rights->fournisseur->commande->approuver) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 9"; - $sql.= " WHERE rowid = ".$this->id; + $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::refuse sql=".$sql); - $resql=$this->db->query($sql); - - if ($resql) + if ($this->db->query($sql)) { $result = 0; $this->log($user, 9, time()); - if (! $error) + if ($error == 0) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_REFUSE',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_REFUSE',$user); + if ($result < 0) { $error++; - $this->errors=$interface->errors; + $this->db->rollback(); } - // Fin appel triggers - } - - if (! $error) - { - $this->db->commit(); - } - else - { - $this->db->rollback(); + else + $this->db->commit(); + // End call triggers } } else @@ -760,7 +748,7 @@ class CommandeFournisseur extends CommonOrder { dol_syslog(get_class($this)."::refuse Not Authorized"); } - return $result; + return $result ; } /** @@ -787,18 +775,16 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut; $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::cancel sql=".$sql); + dol_syslog(get_class($this)."::cancel", LOG_DEBUG); if ($this->db->query($sql)) { $result = 0; $this->log($user, $statut, time()); - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_CANCEL',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_CANCEL',$user); + if ($result < 0) $error++; + // End call triggers if ($error == 0) { @@ -845,7 +831,7 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = 3, fk_input_method=".$methode.",date_commande=".$this->db->idate("$date"); $sql .= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::commande sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::commande", LOG_DEBUG); if ($this->db->query($sql)) { $result = 1; @@ -853,7 +839,6 @@ class CommandeFournisseur extends CommonOrder } else { - dol_syslog(get_class($this)."::cCommande Error -1", LOG_ERR); $result = -1; } } @@ -901,6 +886,7 @@ class CommandeFournisseur extends CommonOrder $sql.= ", model_pdf"; $sql.= ", fk_mode_reglement"; $sql.= ", fk_cond_reglement"; + $sql.= ", fk_account"; $sql.= ") "; $sql.= " VALUES ("; $sql.= "''"; @@ -917,9 +903,10 @@ class CommandeFournisseur extends CommonOrder $sql.= ", '".$conf->global->COMMANDE_SUPPLIER_ADDON_PDF."'"; $sql.= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : 'null'); $sql.= ", ".($this->cond_reglement_id > 0 ? $this->cond_reglement_id : 'null'); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur"); @@ -958,7 +945,7 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql.= " SET ref='(PROV".$this->id.")'"; $sql.= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); if ($this->db->query($sql)) { // On logue creation pour historique @@ -966,6 +953,8 @@ class CommandeFournisseur extends CommonOrder if (! $error) { + $action='create'; + // Actions on extra fields (by external module or standard code) // FIXME le hook fait double emploi avec le trigger !! $hookmanager->initHooks(array('supplierorderdao')); @@ -987,18 +976,14 @@ class CommandeFournisseur extends CommonOrder if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_CREATE',$user); + if ($result < 0) { - $error++; - $this->errors=$interface->errors; $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -1007,7 +992,6 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create: Failed -2 - ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } @@ -1016,7 +1000,6 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::create: Failed -1 - ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1063,12 +1046,10 @@ class CommandeFournisseur extends CommonOrder if ($reshook < 0) $error++; } - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_CLONE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_CLONE',$user); + if ($result < 0) $error++; + // End call triggers } // End @@ -1195,7 +1176,7 @@ class CommandeFournisseur extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc,$this->thirdparty); $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $this->thirdparty, $localtaxes_type); $total_ht = $tabprice[0]; @@ -1234,7 +1215,7 @@ class CommandeFournisseur extends CommonOrder $sql.= "'".price2num($total_ttc)."'"; $sql.= ")"; - dol_syslog(get_class($this)."::addline sql=".$sql); + dol_syslog(get_class($this)."::addline", LOG_DEBUG); $resql=$this->db->query($sql); //print $sql; if ($resql) @@ -1244,18 +1225,14 @@ class CommandeFournisseur extends CommonOrder if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEORDER_SUPPLIER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('LINEORDER_SUPPLIER_CREATE',$user); + if ($result < 0) { - $error++; - $this->errors=$interface->errors; $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } $this->update_price('','auto'); @@ -1267,7 +1244,6 @@ class CommandeFournisseur extends CommonOrder { $this->error=$this->db->error(); $this->db->rollback(); - dol_syslog(get_class($this)."::addline ".$this->error, LOG_ERR); return -1; } } @@ -1311,25 +1287,21 @@ class CommandeFournisseur extends CommonOrder $sql.= " (fk_commande,fk_product, qty, fk_entrepot, fk_user, datec) VALUES "; $sql.= " ('".$this->id."','".$product."','".$qty."',".($entrepot>0?"'".$entrepot."'":"null").",'".$user->id."','".$this->db->idate($now)."')"; - dol_syslog(get_class($this)."::DispatchProduct sql=".$sql); + dol_syslog(get_class($this)."::DispatchProduct", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEORDER_SUPPLIER_DISPATCH',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('LINEORDER_SUPPLIER_DISPATCH',$user); + if ($result < 0) { - $error++; - $this->errors=$interface->errors; $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -1393,15 +1365,10 @@ class CommandeFournisseur extends CommonOrder if (! $notrigger) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $result = 0; - $interface=new Interfaces($this->db); - $result = $interface->run_triggers('LINEORDER_SUPPLIER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEORDER_SUPPLIER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers } if (! $error) @@ -1449,17 +1416,27 @@ class CommandeFournisseur extends CommonOrder $error = 0; + // Call trigger + $result=$this->call_trigger('ORDER_SUPPLIER_DELETE',$user); + if ($result < 0) + { + dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); + return -1; + } + // End call triggers + + $this->db->begin(); $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =". $this->id ; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if (! $this->db->query($sql) ) { $error++; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); if ($resql = $this->db->query($sql) ) { if ($this->db->affected_rows($resql) < 1) @@ -1485,18 +1462,6 @@ class CommandeFournisseur extends CommonOrder } } - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('ORDER_SUPPLIER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers - } - if (! $error) { // We remove directory @@ -1603,7 +1568,7 @@ class CommandeFournisseur extends CommonOrder $sql.= " WHERE rowid = ".$this->id; $sql.= " AND fk_statut IN (3,4)"; // Process running or Partially received - dol_syslog(get_class($this)."::Livraison sql=".$sql); + dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1616,7 +1581,6 @@ class CommandeFournisseur extends CommonOrder { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::Livraison Error ".$this->error, LOG_ERR); $result = -1; } } @@ -1649,7 +1613,7 @@ class CommandeFournisseur extends CommonOrder $sql.= " SET date_livraison = ".($date_livraison ? "'".$this->db->idate($date_livraison)."'" : 'null'); $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_date_livraison sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::set_date_livraison", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1659,7 +1623,6 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::set_date_livraison ".$this->error,LOG_ERR); return -1; } } @@ -1729,7 +1692,7 @@ class CommandeFournisseur extends CommonOrder $sql.= ' SET fk_statut='.$status; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog(get_class($this)."::setStatus sql=".$sql); + dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -1769,10 +1732,13 @@ class CommandeFournisseur extends CommonOrder * @param int $info_bits Miscellaneous informations * @param int $type Type of line (0=product, 1=service) * @param int $notrigger Disable triggers + * @param timestamp $date_start Date start of service + * @param timestamp $date_end Date end of service * @return int < 0 if error, > 0 if ok */ - function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false) + function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1=0, $txlocaltax2=0, $price_base_type='HT', $info_bits=0, $type=0, $notrigger=false, $date_start='', $date_end='') { + global $mysoc; dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $txtva, $price_base_type, $info_bits, $type"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1805,7 +1771,7 @@ class CommandeFournisseur extends CommonOrder // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty); + $localtaxes_type=getLocalTaxesFromRate($txtva,0,$mysoc, $this->thirdparty); $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type); $total_ht = $tabprice[0]; @@ -1831,10 +1797,8 @@ class CommandeFournisseur extends CommonOrder $sql.= ",localtax1_type='".$localtax1_type."'"; $sql.= ",localtax2_type='".$localtax2_type."'"; $sql.= ",qty='".price2num($qty)."'"; - /*if ($date_end) { $sql.= ",date_start='$date_end'"; } - else { $sql.=',date_start=null'; } - if ($date_end) { $sql.= ",date_end='$date_end'"; } - else { $sql.=',date_end=null'; }*/ + $sql.= ",date_start=".(! empty($date_start)?"'".$this->db->idate($date_start)."'":"null"); + $sql.= ",date_end=".(! empty($date_end)?"'".$this->db->idate($date_end)."'":"null"); $sql.= ",info_bits='".$info_bits."'"; $sql.= ",total_ht='".price2num($total_ht)."'"; $sql.= ",total_tva='".price2num($total_tva)."'"; @@ -1844,7 +1808,7 @@ class CommandeFournisseur extends CommonOrder $sql.= ",product_type=".$type; $sql.= " WHERE rowid = ".$rowid; - dol_syslog(get_class($this)."::updateline sql=".$sql); + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); if ($result > 0) { @@ -1853,18 +1817,14 @@ class CommandeFournisseur extends CommonOrder if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEORDER_SUPPLIER_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('LINEORDER_SUPPLIER_UPDATE',$user); + if ($result < 0) { - $error++; - $this->errors=$interface->errors; $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } // Mise a jour info denormalisees au niveau facture @@ -1876,7 +1836,6 @@ class CommandeFournisseur extends CommonOrder else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::updateline ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -1971,6 +1930,47 @@ class CommandeFournisseur extends CommonOrder } } + /** + * Charge indicateurs this->nb de tableau de bord + * + * @return int <0 si ko, >0 si ok + */ + function load_state_board() + { + global $conf, $user; + + $this->nb=array(); + $clause = "WHERE"; + + $sql = "SELECT count(co.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->societe_id) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = "AND"; + } + $sql.= " ".$clause." co.entity = ".$conf->entity; + + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["supplier_orders"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + /** * Load indicators for dashboard (this->nbtodo and this->nbtodolate) * @@ -1986,7 +1986,7 @@ class CommandeFournisseur extends CommonOrder $this->nbtodo=$this->nbtodolate=0; $clause = " WHERE"; - $sql = "SELECT c.rowid, c.date_creation as datec, c.fk_statut"; + $sql = "SELECT c.rowid, c.date_creation as datec, c.fk_statut,c.date_livraison as delivery_date"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; if (!$user->rights->societe->client->voir && !$user->societe_id) { @@ -2004,7 +2004,9 @@ class CommandeFournisseur extends CommonOrder while ($obj=$this->db->fetch_object($resql)) { $this->nbtodo++; - if ($obj->fk_statut != 3 && $this->db->jdate($obj->datec) < ($now - $conf->commande->fournisseur->warning_delay)) $this->nbtodolate++; + + $date_to_test = empty($obj->delivery_date) ? $obj->datec : $obj->delivery_date; + if ($obj->fk_statut != 3 && $this->db->jdate($date_to_test) < ($now - $conf->commande->fournisseur->warning_delay)) $this->nbtodolate++; } return 1; } @@ -2050,6 +2052,42 @@ class CommandeFournisseur extends CommonOrder return ''; } + + /** + * Create a document onto disk according to template model. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs Object lang to use for traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf, $user, $langs; + + $langs->load("suppliers"); + + // Sets the model on the model name to use + if (! dol_strlen($modele)) + { + if (! empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF)) + { + $modele = $conf->global->COMMANDE_SUPPLIER_ADDON_PDF; + } + else + { + $modele = 'muscadet'; + } + } + + $modelpath = "core/modules/supplier_order/pdf/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + + } @@ -2057,7 +2095,7 @@ class CommandeFournisseur extends CommonOrder /** * Classe de gestion des lignes de commande */ -class CommandeFournisseurLigne +class CommandeFournisseurLigne extends CommonOrderLine { // From llx_commandedet var $qty; @@ -2078,6 +2116,8 @@ class CommandeFournisseurLigne var $total_ttc; var $info_bits; var $special_code; + var $date_start; + var $date_end; // From llx_product var $libelle; // Label produit @@ -2110,7 +2150,8 @@ class CommandeFournisseurLigne $sql.= ' cd.remise, cd.remise_percent, cd.subprice,'; $sql.= ' cd.info_bits, cd.total_ht, cd.total_tva, cd.total_ttc,'; $sql.= ' cd.total_localtax1, cd.total_localtax2,'; - $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc'; + $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc,'; + $sql.= ' cd.date_start, cd.date_end'; $sql.= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; $sql.= ' WHERE cd.rowid = '.$rowid; @@ -2141,6 +2182,9 @@ class CommandeFournisseurLigne $this->product_libelle = $objp->product_libelle; $this->product_desc = $objp->product_desc; + $this->date_start = $this->db->jdate($objp->date_start); + $this->date_end = $this->db->jdate($objp->date_end); + $this->db->free($result); return 1; } @@ -2169,7 +2213,7 @@ class CommandeFournisseurLigne $sql.= ",total_ttc='".price2num($this->total_ttc)."'"; $sql.= " WHERE rowid = ".$this->rowid; - dol_syslog("CommandeFournisseurLigne.class.php::update_total sql=$sql"); + dol_syslog("CommandeFournisseurLigne.class.php::update_total", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) @@ -2180,7 +2224,6 @@ class CommandeFournisseurLigne else { $this->error=$this->db->error(); - dol_syslog("CommandeFournisseurLigne.class.php::update_total Error ".$this->error, LOG_ERR); $this->db->rollback(); return -2; } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 786d619665e..69c235fd831 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -4,9 +4,10 @@ * Copyright (C) 2004 Christophe Combelles * Copyright (C) 2005 Marc Barilley * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2013 Philippe Grand * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -79,6 +80,7 @@ class FactureFournisseur extends CommonInvoice var $propalid; var $cond_reglement_id; var $cond_reglement_code; + var $fk_account; var $mode_reglement_id; var $mode_reglement_code; @@ -144,7 +146,7 @@ class FactureFournisseur extends CommonInvoice */ function create($user) { - global $langs,$conf; + global $langs,$conf,$hookmanager; $error=0; $now=dol_now(); @@ -174,6 +176,7 @@ class FactureFournisseur extends CommonInvoice $sql.= ", fk_projet"; $sql.= ", fk_cond_reglement"; $sql.= ", fk_mode_reglement"; + $sql.= ", fk_account"; $sql.= ", note_private"; $sql.= ", note_public"; $sql.= ", fk_user_author"; @@ -190,13 +193,14 @@ class FactureFournisseur extends CommonInvoice $sql.= ", ".(isset($this->fk_project)?$this->fk_project:"null"); $sql.= ", ".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null"); $sql.= ", ".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null"); + $sql.= ", ".($this->fk_account>0?$this->fk_account:'NULL'); $sql.= ", '".$this->db->escape($this->note_private)."'"; $sql.= ", '".$this->db->escape($this->note_public)."'"; $sql.= ", ".$user->id.","; $sql.= $this->date_echeance!=''?"'".$this->db->idate($this->date_echeance)."'":"null"; $sql.= ")"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -206,7 +210,7 @@ class FactureFournisseur extends CommonInvoice $this->ref='(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."facture_fourn SET ref='".$this->ref."' WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::create sql=".$sql); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) $error++; @@ -226,7 +230,7 @@ class FactureFournisseur extends CommonInvoice $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)'; $sql .= ' VALUES ('.$this->id.');'; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql_insert=$this->db->query($sql); if ($resql_insert) { @@ -251,12 +255,29 @@ class FactureFournisseur extends CommonInvoice $result=$this->update_price(); if ($result > 0) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_SUPPLIER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + $action='create'; + + // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('supplierinvoicedao')); + $parameters=array('socid'=>$this->id); + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if (empty($reshook)) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + $result=$this->insertExtraFields(); + if ($result < 0) + { + $error++; + } + } + } + else if ($reshook < 0) $error++; + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_CREATE',$user); + if ($result < 0) $error++; + // End call triggers if (! $error) { @@ -333,7 +354,8 @@ class FactureFournisseur extends CommonInvoice $sql.= " t.fk_facture_source,"; $sql.= " t.fk_projet,"; $sql.= " t.fk_cond_reglement,"; - $sql.= " t.fk_mode_reglement,"; + $sql.= " t.fk_account,"; + $sql.= " t.fk_mode_reglement,"; $sql.= " t.date_lim_reglement,"; $sql.= " t.note_private,"; $sql.= " t.note_public,"; @@ -350,7 +372,7 @@ class FactureFournisseur extends CommonInvoice if ($id) $sql.= " WHERE t.rowid=".$id; if ($ref) $sql.= " WHERE t.ref='".$this->db->escape($ref)."'"; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -394,6 +416,7 @@ class FactureFournisseur extends CommonInvoice $this->cond_reglement_code = $obj->cond_reglement_code; $this->cond_reglement = $obj->cond_reglement_libelle; $this->cond_reglement_doc = $obj->cond_reglement_libelle; + $this->fk_account = $obj->fk_account; $this->mode_reglement_id = $obj->fk_mode_reglement; $this->mode_reglement_code = $obj->mode_reglement_code; $this->mode_reglement = $obj->mode_reglement_libelle; @@ -410,18 +433,26 @@ class FactureFournisseur extends CommonInvoice $this->socid = $obj->socid; $this->socnom = $obj->socnom; + // Retreive all extrafield + // fetch optionals attributes and labels + require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'); + $extrafields=new ExtraFields($this->db); + $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true); + $this->fetch_optionals($this->id,$extralabels); + + if ($this->statut == 0) $this->brouillon = 1; + $result=$this->fetch_lines(); if ($result < 0) { $this->error=$this->db->error(); - dol_syslog(get_class($this).'::fetch Error '.$this->error, LOG_ERR); return -3; } } else { - $this->error='Bill with id '.$id.' not found sql='.$sql; + $this->error='Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; } @@ -432,7 +463,6 @@ class FactureFournisseur extends CommonInvoice else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -453,7 +483,7 @@ class FactureFournisseur extends CommonInvoice $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON f.fk_product = p.rowid'; $sql.= ' WHERE fk_facture_fourn='.$this->id; - dol_syslog(get_class($this)."::fetch_lines sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql_rows = $this->db->query($sql); if ($resql_rows) { @@ -499,7 +529,6 @@ class FactureFournisseur extends CommonInvoice else { $this->error=$this->db->error(); - dol_syslog(get_class($this).'::fetch_lines: Error '.$this->error,LOG_ERR); return -3; } } @@ -512,7 +541,7 @@ class FactureFournisseur extends CommonInvoice * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -591,7 +620,7 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -599,11 +628,9 @@ class FactureFournisseur extends CommonInvoice { if (! $notrigger) { - // Call triggers - //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - //$interface=new Interfaces($this->db); - //$result=$interface->run_triggers('BILL_SUPPLIER_MODIFY',$this,$user,$langs,$conf); - //if ($result < 0) { $error++; $this->errors=$interface->errors; } + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_UPDATE',$user); + if ($result < 0) $error++; // End call triggers } } @@ -647,12 +674,12 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql2 = $this->db->query($sql); if (! $resql2) { $error++; @@ -671,15 +698,12 @@ class FactureFournisseur extends CommonInvoice if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_SUPPLIER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; - $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_DELETE',$user); + if ($result < 0) + { $this->db->rollback(); - return -1; + return -1; } // Fin appel triggers } @@ -742,7 +766,6 @@ class FactureFournisseur extends CommonInvoice else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); return -$error; } @@ -766,16 +789,14 @@ class FactureFournisseur extends CommonInvoice $sql.= ' SET paye = 1, fk_statut=2'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog("FactureFournisseur::set_paid sql=".$sql); + dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_SUPPLIER_PAYED',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_PAYED',$user); + if ($result < 0) $error++; + // End call triggers } else { @@ -816,16 +837,14 @@ class FactureFournisseur extends CommonInvoice $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog("FactureFournisseur::set_unpaid sql=".$sql); + dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_SUPPLIER_UNPAYED',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_UNPAYED',$user); + if ($result < 0) $error++; + // End call triggers } else { @@ -852,9 +871,10 @@ class FactureFournisseur extends CommonInvoice * @param User $user Object user that validate * @param string $force_number Reference to force on invoice * @param int $idwarehouse Id of warehouse for stock change + * @param int $notrigger 1=Does not execute triggers, 0= execuete triggers * @return int <0 if KO, =0 if nothing to do, >0 if OK */ - function validate($user, $force_number='', $idwarehouse=0) + function validate($user, $force_number='', $idwarehouse=0, $notrigger=0) { global $conf,$langs; @@ -886,15 +906,16 @@ class FactureFournisseur extends CommonInvoice $num = $this->getNextNumRef($this->client); } else - { + { $num = $this->ref; } + $this->newref = $num; $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn"; $sql.= " SET ref='".$num."', fk_statut = 1, fk_user_valid = ".$user->id; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::validate sql=".$sql); + dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -920,31 +941,46 @@ class FactureFournisseur extends CommonInvoice } } + // Triggers call + if (! $error && $notrigger) + { + // Call trigger + $result=$this->call_trigger('BILL_SUPPLIER_VALIDATE',$user); + if ($result < 0) $error++; + // End call triggers + } + if (! $error) { - $this->oldref = ''; + $this->oldref = $this->ref; // Rename directory if dir was a temporary ref if (preg_match('/^[\(]?PROV/i', $this->ref)) { // On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref) // in order not to lose the attached files - $facref = dol_sanitizeFileName($this->ref); - $snumfa = dol_sanitizeFileName($num); + $oldref = dol_sanitizeFileName($this->ref); + $newref = dol_sanitizeFileName($num); - $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$facref; - $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$snumfa; + $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$oldref; + $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$newref; if (file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); if (@rename($dirsource, $dirdest)) { - $this->oldref = $facref; - dol_syslog("Rename ok"); - // Suppression ancien fichier PDF dans nouveau rep - dol_delete_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$snumfa.'/'.$facref.'*.*'); + // Rename docs starting with $oldref with $newref + $listoffiles=dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id,2).$newref, 'files', 1, '^'.preg_quote($oldref,'/')); + foreach($listoffiles as $fileentry) + { + $dirsource=$fileentry['name']; + $dirdest=preg_replace('/^'.preg_quote($oldref,'/').'/',$newref, $dirsource); + $dirsource=$fileentry['path'].'/'.$dirsource; + $dirdest=$fileentry['path'].'/'.$dirdest; + @rename($dirsource, $dirdest); + } } } } @@ -958,17 +994,6 @@ class FactureFournisseur extends CommonInvoice //$this->date_validation=$now; this is stored into log table } - // Triggers call - if (! $error) - { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('BILL_SUPPLIER_VALIDATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers - } - if (! $error) { $this->db->commit(); @@ -1014,7 +1039,7 @@ class FactureFournisseur extends CommonInvoice $sql.= " SET fk_statut = 0"; $sql.= " WHERE rowid = ".$this->id; - dol_syslog(get_class($this)."::set_draft sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::set_draft", LOG_DEBUG); $result=$this->db->query($sql); if ($result) { @@ -1113,7 +1138,7 @@ class FactureFournisseur extends CommonInvoice $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn)'; $sql.= ' VALUES ('.$this->id.')'; - dol_syslog(get_class($this)."::addline sql=".$sql); + dol_syslog(get_class($this)."::addline", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -1128,18 +1153,14 @@ class FactureFournisseur extends CommonInvoice if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEBILL_SUPPLIER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; - $this->errors=$interface->errors; + // Call trigger + $result=$this->call_trigger('LINEBILL_SUPPLIER_CREATE',$user); + if ($result < 0) + { $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } $this->db->commit(); @@ -1180,6 +1201,7 @@ class FactureFournisseur extends CommonInvoice */ function updateline($id, $desc, $pu, $vatrate, $txlocaltax1=0, $txlocaltax2=0, $qty=1, $idproduct=0, $price_base_type='HT', $info_bits=0, $type=0, $remise_percent=0, $notrigger=false) { + global $mysoc; dol_syslog(get_class($this)."::updateline $id,$desc,$pu,$vatrate,$qty,$idproduct,$price_base_type,$info_bits,$type,$remise_percent", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; @@ -1204,7 +1226,7 @@ class FactureFournisseur extends CommonInvoice // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva. - $localtaxes_type=getLocalTaxesFromRate($vatrate,0,$this->thirdparty); + $localtaxes_type=getLocalTaxesFromRate($vatrate,0,$mysoc, $this->thirdparty); $tabprice = calcul_price_total($qty, $pu, $remise_percent, $vatrate, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $this->thirdparty, $localtaxes_type); $total_ht = $tabprice[0]; @@ -1229,7 +1251,7 @@ class FactureFournisseur extends CommonInvoice } $this->db->begin(); - + $sql = "UPDATE ".MAIN_DB_PREFIX."facture_fourn_det SET"; $sql.= " description ='".$this->db->escape($desc)."'"; $sql.= ", pu_ht = ".price2num($pu_ht); @@ -1252,7 +1274,7 @@ class FactureFournisseur extends CommonInvoice $sql.= ", info_bits = ".$info_bits; $sql.= " WHERE rowid = ".$id; - dol_syslog(get_class($this)."::updateline sql=".$sql); + dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -1261,32 +1283,27 @@ class FactureFournisseur extends CommonInvoice if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEBILL_SUPPLIER_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) + // Call trigger + $result=$this->call_trigger('LINEBILL_SUPPLIER_UPDATE',$user); + if ($result < 0) { - $error++; - $this->errors=$interface->errors; $this->db->rollback(); return -1; } - // Fin appel triggers + // End call triggers } // Update total price into invoice record $result=$this->update_price('','auto'); $this->db->commit(); - + return $result; } else { $this->db->rollback(); $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::updateline error=".$this->error, LOG_ERR); return -1; } } @@ -1311,14 +1328,10 @@ class FactureFournisseur extends CommonInvoice if (! $error && ! $notrigger) { - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('LINEBILL_SUPPLIER_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { - $error++; $this->errors=$interface->errors; - } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('LINEBILL_SUPPLIER_DELETE',$user); + if ($result < 0) $error++; + // End call triggers } if (! $error) @@ -1326,13 +1339,12 @@ class FactureFournisseur extends CommonInvoice // Supprime ligne $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det '; $sql.= ' WHERE rowid = '.$rowid; - dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); } } @@ -1463,7 +1475,7 @@ class FactureFournisseur extends CommonInvoice } else { - $lien = ''; + $lien = ''; $lienfin=''; } $label=$langs->trans("ShowInvoice").': '.$this->ref; @@ -1621,6 +1633,48 @@ class FactureFournisseur extends CommonInvoice $this->total_ttc = $xnbp*119.6; } + /** + * Load indicators for dashboard (this->nbtodo and this->nbtodolate) + * + * @return int <0 if KO, >0 if OK + */ + function load_state_board() + { + global $conf, $user; + + $this->nb=array(); + + $clause = "WHERE"; + + $sql = "SELECT count(f.rowid) as nb"; + $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->societe_id) + { + $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + $sql.= " WHERE sc.fk_user = " .$user->id; + $clause = "AND"; + } + $sql.= " ".$clause." f.entity = ".$conf->entity; + + $resql=$this->db->query($sql); + if ($resql) + { + while ($obj=$this->db->fetch_object($resql)) + { + $this->nb["supplier_invoices"]=$obj->nb; + } + $this->db->free($resql); + return 1; + } + else + { + dol_print_error($this->db); + $this->error=$this->db->error(); + return -1; + } + } + /** * Load an object from its id and create a new one in database * @@ -1695,4 +1749,38 @@ class FactureFournisseur extends CommonInvoice } } + /** + * Create a document onto disk according to template model. + * + * @param string $modele Force template to use ('' to not force) + * @param Translate $outputlangs Object lang a utiliser pour traduction + * @param int $hidedetails Hide details of lines + * @param int $hidedesc Hide description + * @param int $hideref Hide ref + * @return int 0 if KO, 1 if OK + */ + public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0) + { + global $conf, $user, $langs; + + $langs->load("suppliers"); + + // Set the model on the model name to use + if (! dol_strlen($modele)) + { + if (! empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) + { + $modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF; + } + else + { + $modele = 'canelle'; + } + } + + $modelpath = "core/modules/supplier_invoice/pdf/"; + + return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref); + } + } diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index b642926f802..75ac674e877 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -1,9 +1,9 @@ * Copyright (C) 2006-2011 Laurent Destailleur - * Copyright (C) 2009-2012 Regis Houssin + * Copyright (C) 2009-2014 Regis Houssin * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2012 Christophe Battarel + * Copyright (C) 2012 Christophe Battarel * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -83,12 +83,11 @@ class ProductFournisseur extends Product $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql.= " WHERE fk_product = ".$this->id." AND fk_soc = ".$id_fourn; - dol_syslog(get_class($this)."::remove_fournisseur sql=".$sql); + dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG); $resql2=$this->db->query($sql); if (! $resql2) { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::remove_fournisseur ".$this->error, LOG_ERR); $ok=0; } @@ -120,7 +119,7 @@ class ProductFournisseur extends Product $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql.= " WHERE rowid = ".$rowid; - dol_syslog(get_class($this)."::remove_product_fournisseur_price sql=".$sql); + dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -130,7 +129,6 @@ class ProductFournisseur extends Product else { $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::remove_product_fournisseur_price ".$this->error,LOG_ERR); $this->db->rollback(); return -1; } @@ -156,7 +154,7 @@ class ProductFournisseur extends Product */ function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges=0, $remise_percent=0, $remise=0, $newnpr=0) { - global $conf,$mysoc; + global $conf; // Clean parameter if (empty($qty)) $qty=0; @@ -201,18 +199,14 @@ class ProductFournisseur extends Product $sql.= " WHERE rowid = ".$this->product_fourn_price_id; // TODO Add price_base_type and price_ttc - dol_syslog(get_class($this).'::update_buyprice sql='.$sql); + dol_syslog(get_class($this).'::update_buyprice', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SUPPLIER_PRODUCT_BUYPRICE_UPDATE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; $this->error=$interface->errors; - } + // Call trigger + $result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE',$user); + if ($result < 0) $error++; + // End call triggers if (empty($error)) { @@ -238,7 +232,7 @@ class ProductFournisseur extends Product // Delete price for this quantity $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql.= " WHERE fk_soc = ".$fourn->id." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".$qty." AND entity = ".$conf->entity; - dol_syslog(get_class($this).'::update_buyprice sql='.$sql); + dol_syslog(get_class($this).'::update_buyprice', LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -263,15 +257,15 @@ class ProductFournisseur extends Product $sql.= $conf->entity; $sql.=")"; - dol_syslog(get_class($this)."::update_buyprice sql=".$sql); + dol_syslog(get_class($this)."::update_buyprice", LOG_DEBUG); if (! $this->db->query($sql)) { $error++; } - /*if (! $error) + if (! $error && !empty($cong->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { - // Ajoute modif dans table log + // Add record into log table $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log("; $sql.= "datec, fk_product_fournisseur,fk_user,price,quantity)"; $sql.= "values('".$this->db->idate($now)."',"; @@ -287,18 +281,14 @@ class ProductFournisseur extends Product $error++; } } - */ + if (! $error) { - // Appel des triggers - include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php"); - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('SUPPLIER_PRODUCT_BUYPRICE_CREATE',$this,$user,$langs,$conf); - if ($result < 0) - { - $error++; $this->error=$interface->errors; - } + // Call trigger + $result=$this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE',$user); + if ($result < 0) $error++; + // End call triggers if (empty($error)) { @@ -340,7 +330,7 @@ class ProductFournisseur extends Product $sql.= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql.= " WHERE pfp.rowid = ".$rowid; - dol_syslog(get_class($this)."::fetch_product_fournisseur_price sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -371,7 +361,6 @@ class ProductFournisseur extends Product else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::fetch_product_fournisseur_price error=".$this->error, LOG_ERR); return -1; } } @@ -399,7 +388,7 @@ class ProductFournisseur extends Product $sql.= " AND pfp.fk_product = ".$prodid; if (empty($sortfield)) $sql.= " ORDER BY s.nom, pfp.quantity, pfp.price"; else $sql.= $this->db->order($sortfield,$sortorder); - dol_syslog(get_class($this)."::list_product_fournisseur_price sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -449,7 +438,6 @@ class ProductFournisseur extends Product else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::list_product_fournisseur_price error=".$this->error, LOG_ERR); return -1; } } @@ -479,7 +467,8 @@ class ProductFournisseur extends Product $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,"; $sql.= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,"; - $sql.= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges, pfp.unitcharges"; + $sql.= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges, pfp.unitcharges, "; + $sql.= " pfp.remise, pfp.remise_percent"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp"; $sql.= " WHERE s.entity IN (".getEntity('societe', 1).")"; $sql.= " AND pfp.fk_product = ".$prodid; @@ -488,7 +477,7 @@ class ProductFournisseur extends Product $sql.= " ORDER BY pfp.unitprice"; $sql.= $this->db->plimit(1); - dol_syslog(get_class($this)."::find_min_price_product_fournisseur sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) @@ -513,7 +502,6 @@ class ProductFournisseur extends Product else { $this->error=$this->db->error(); - dol_syslog(get_class($this)."::find_min_price_product_fournisseur error=".$this->error, LOG_ERR); return -1; } } diff --git a/htdocs/fourn/class/index.html b/htdocs/fourn/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index 0f70dc6bafc..59dc5dab3d1 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -163,7 +163,7 @@ class PaiementFourn extends Paiement $sql.= " VALUES ('".$this->db->idate($now)."',"; $sql.= " '".$this->db->idate($this->datepaye)."', '".$this->total."', ".$this->paiementid.", '".$this->num_paiement."', '".$this->db->escape($this->note)."', ".$user->id.", 0)"; - dol_syslog("PaiementFourn::create sql=".$sql); + dol_syslog("PaiementFourn::create", LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -215,18 +215,15 @@ class PaiementFourn extends Paiement if (! $error) { - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('PAYMENT_SUPPLIER_CREATE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$this->call_trigger('PAYMENT_SUPPLIER_CREATE',$user); + if ($result < 0) $error++; + // End call triggers } } else { $this->error=$this->db->lasterror(); - dol_syslog('PaiementFourn::Create Error '.$this->error, LOG_ERR); $error++; } } @@ -272,7 +269,7 @@ class PaiementFourn extends Paiement { if (count($billsarray)) { - $this->error='Can\'t delete a payment shared by at least one invoice with status payed'; + $this->error="ErrorCantDeletePaymentSharedWithPayedInvoice"; $this->db->rollback(); return -1; } @@ -291,7 +288,7 @@ class PaiementFourn extends Paiement $accline->fetch($bank_line_id); if ($accline->rappro) { - $this->error='Impossible de supprimer un paiement qui a genere une ecriture qui a ete rapprochee'; + $this->error="ErrorCantDeletePaymentReconciliated"; $this->db->rollback(); return -3; } @@ -300,13 +297,11 @@ class PaiementFourn extends Paiement // Efface la ligne de paiement (dans paiement_facture et paiement) $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; $sql.= ' WHERE fk_paiementfourn = '.$this->id; - dol_syslog("sql=".$sql); $resql = $this->db->query($sql); if ($resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn'; $sql.= ' WHERE rowid = '.$this->id; - dol_syslog("sql=".$sql); $result = $this->db->query($sql); if (! $result) { @@ -398,7 +393,7 @@ class PaiementFourn extends Paiement $sql.= ' WHERE pf.fk_facturefourn = f.rowid AND fk_paiementfourn = '.$this->id; if ($filter) $sql.= ' AND '.$filter; - dol_syslog(get_class($this).'::getBillsArray sql='.$sql,LOG_DEBUG); + dol_syslog(get_class($this).'::getBillsArray', LOG_DEBUG); $resql = $this->db->query($sql); if ($resql) { @@ -493,7 +488,7 @@ class PaiementFourn extends Paiement $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $text=$this->ref; // Sometimes ref contains label diff --git a/htdocs/fourn/commande/fiche.php b/htdocs/fourn/commande/card.php similarity index 68% rename from htdocs/fourn/commande/fiche.php rename to htdocs/fourn/commande/card.php index 00884d368f6..753f91fbdda 100644 --- a/htdocs/fourn/commande/fiche.php +++ b/htdocs/fourn/commande/card.php @@ -3,10 +3,11 @@ * Copyright (C) 2004-2013 Laurent Destailleur * Copyright (C) 2005 Eric Seigne * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2010-2013 Juanjo Menent + * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2011 Philippe Grand * Copyright (C) 2012 Marcos García * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Ion Agorria * * 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 +25,7 @@ */ /** - * \file htdocs/fourn/commande/fiche.php + * \file htdocs/fourn/commande/card.php * \ingroup supplier, order * \brief Card supplier order */ @@ -43,7 +44,9 @@ if (!empty($conf->produit->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP +$langs->load('admin'); $langs->load('orders'); $langs->load('sendings'); $langs->load('companies'); @@ -72,7 +75,7 @@ if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'fournisseur', $id, '', 'commande'); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('ordersuppliercard')); +$hookmanager->initHooks(array('ordersuppliercard','globalcard')); $object = new CommandeFournisseur($db); $extrafields = new ExtraFields($db); @@ -80,6 +83,9 @@ $extrafields = new ExtraFields($db); // fetch optionals attributes and labels $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); +//Date prefix +$date_pf = ''; + // Load object if ($id > 0 || ! empty($ref)) { @@ -105,6 +111,10 @@ $permissionnote=$user->rights->fournisseur->commande->creer; // Used by the incl * Actions */ +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once if ($action == 'setref_supplier' && $user->rights->fournisseur->commande->creer) @@ -125,6 +135,12 @@ else if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); } +// bank account +else if ($action == 'setbankaccount' && $user->rights->fournisseur->commande->creer) +{ + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); +} + // date de livraison if ($action == 'setdate_livraison' && $user->rights->fournisseur->commande->creer) { @@ -150,10 +166,11 @@ else if ($action == 'setremisepercent' && $user->rights->fournisseur->commande-> else if ($action == 'reopen' && $user->rights->fournisseur->commande->approuver) { - if (in_array($object->statut, array(1, 5, 6, 7, 9))) + if (in_array($object->statut, array(1, 2, 5, 6, 7, 9))) { if ($object->statut == 1) $newstatus=0; // Validated->Draft - else if ($object->statut == 5) $newstatus=4; // Received->Received partially + else if ($object->statut == 2) $newstatus=0; // Approved->Draft + else if ($object->statut == 5) $newstatus=4; // Received->Received partially else if ($object->statut == 6) $newstatus=2; // Canceled->Approved else if ($object->statut == 7) $newstatus=3; // Canceled->Process running else if ($object->statut == 9) $newstatus=1; // Refused->Validated @@ -182,6 +199,8 @@ else if ($action == 'addline' && $user->rights->fournisseur->commande->creer) // Set if we used free entry or predefined product $predef=''; $product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):''); + $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); + $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); if (GETPOST('prod_entry_mode') == 'free') { $idprod=0; @@ -267,7 +286,12 @@ else if ($action == 'addline' && $user->rights->fournisseur->commande->creer) $productsupplier->fourn_ref, $remise_percent, 'HT', - $type + $pu_ttc, + $type, + '', + '', + $date_start, + $date_end ); } if ($idprod == -2 || $idprod == 0) @@ -305,14 +329,14 @@ else if ($action == 'addline' && $user->rights->fournisseur->commande->creer) { $price_base_type = 'HT'; $ht = price2num($_POST['price_ht']); - $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, 0, $type); + $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, 0, $type,'','', $date_start, $date_end); } else { $ttc = price2num($_POST['price_ttc']); $ht = $ttc / (1 + ($tauxtva / 100)); $price_base_type = 'HT'; - $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type); + $result=$object->addline($desc, $ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, '', $remise_percent, $price_base_type, $ttc, $type,'','', $date_start, $date_end); } } @@ -321,19 +345,24 @@ else if ($action == 'addline' && $user->rights->fournisseur->commande->creer) { $ret=$object->fetch($object->id); // Reload to get new records + // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - // Define output language $outputlangs = $langs; - $newlang=GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'order_supplier'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); } unset($_POST ['prod_entry_mode']); @@ -384,6 +413,9 @@ else if ($action == 'update_line' && $user->rights->fournisseur->commande->creer if (!$res) dol_print_error($db); } + $date_start=dol_mktime(GETPOST('date_start'.$date_pf.'hour'), GETPOST('date_start'.$date_pf.'min'), 0, GETPOST('date_start'.$date_pf.'month'), GETPOST('date_start'.$date_pf.'day'), GETPOST('date_start'.$date_pf.'year')); + $date_end=dol_mktime(GETPOST('date_end'.$date_pf.'hour'), GETPOST('date_end'.$date_pf.'min'), 0, GETPOST('date_end'.$date_pf.'month'), GETPOST('date_end'.$date_pf.'day'), GETPOST('date_end'.$date_pf.'year')); + $localtax1_tx=get_localtax($_POST['tva_tx'],1,$mysoc,$object->thirdparty); $localtax2_tx=get_localtax($_POST['tva_tx'],2,$mysoc,$object->thirdparty); @@ -398,7 +430,10 @@ else if ($action == 'update_line' && $user->rights->fournisseur->commande->creer $localtax2_tx, 'HT', 0, - isset($_POST["type"])?$_POST["type"]:$line->product_type + isset($_POST["type"])?$_POST["type"]:$line->product_type, + false, + $date_start, + $date_end ); unset($_POST['qty']); unset($_POST['type']); @@ -408,21 +443,32 @@ else if ($action == 'update_line' && $user->rights->fournisseur->commande->creer unset($_POST['np_desc']); unset($_POST['pu']); unset($_POST['tva_tx']); + unset($_POST['date_start']); + unset($_POST['date_end']); unset($localtax1_tx); unset($localtax2_tx); + if ($result >= 0) { - $outputlangs = $langs; - if (GETPOST('lang_id')) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang(GETPOST('lang_id')); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $ret=$object->fetch($object->id); // Reload to get new records - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'order_supplier'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } } else { @@ -446,7 +492,7 @@ else if ($action == 'confirm_deleteproductline' && $confirm == 'yes' && $user->r if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $ret=$object->fetch($object->id); // Reload to get new records - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } else @@ -468,17 +514,25 @@ else if ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->fourn $result = $object->valid($user); if ($result >= 0) { - $outputlangs = $langs; - if (GETPOST('lang_id')) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang(GETPOST('lang_id')); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $ret=$object->fetch($object->id); // Reload to get new records - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - } + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'order_supplier'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } } else { @@ -523,7 +577,7 @@ else if ($action == 'confirm_approve' && $confirm == 'yes' && $user->rights->fou if ($result > 0) { if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; @@ -555,7 +609,7 @@ else if ($action == 'confirm_commande' && $confirm == 'yes' && $user->rights->fo if ($result > 0) { if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; @@ -572,7 +626,7 @@ else if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->four $result=$object->delete($user); if ($result > 0) { - header("Location: ".DOL_URL_ROOT.'/fourn/commande/liste.php'); + header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php'); exit; } else @@ -633,7 +687,7 @@ else if ($action == 'livraison' && $user->rights->fournisseur->commande->recepti } else { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Delivery")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("Delivery")), 'errors'); } } @@ -662,7 +716,9 @@ else if ($action == 'up' && $user->rights->fournisseur->commande->creer) $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($_REQUEST['lang_id']); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#'.$_GET['rowid'])); exit; } @@ -676,7 +732,9 @@ else if ($action == 'down' && $user->rights->fournisseur->commande->creer) $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($_REQUEST['lang_id']); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) supplier_order_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#'.$_GET['rowid'])); exit; } @@ -694,7 +752,7 @@ else if ($action == 'builddoc' && $user->rights->fournisseur->commande->creer) / $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang(GETPOST('lang_id')); } - $result=supplier_order_pdf_create($db, $object,$object->modelpdf,$outputlangs, $hidedetails, $hidedesc, $hideref); + $result= $object->generateDocument($object->modelpdf,$outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -762,7 +820,7 @@ else if ($action == 'add' && $user->rights->fournisseur->commande->creer) if ($socid <1) { - $mesg='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); $action='create'; $error++; } @@ -776,6 +834,7 @@ else if ($action == 'add' && $user->rights->fournisseur->commande->creer) $object->socid = $socid; $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->note_private = GETPOST('note_private'); $object->note_public = GETPOST('note_public'); @@ -792,7 +851,7 @@ else if ($action == 'add' && $user->rights->fournisseur->commande->creer) { $langs->load("errors"); $db->rollback(); - $mesg='
'.$langs->trans($object->error).'
'; + setEventMessage($langs->trans($object->error), 'errors'); $action='create'; $_GET['socid']=$_POST['socid']; } @@ -886,12 +945,13 @@ if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! G if (dol_strlen(GETPOST('subject'))) $subject=GETPOST('subject'); else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; $actiontypecode='AC_SUP_ORD'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); } @@ -989,6 +1049,99 @@ if ($action == 'send' && ! GETPOST('addfile') && ! GETPOST('removedfile') && ! G } } +if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && ! GETPOST('cancel')) +{ + $ws_url = $object->thirdparty->webservices_url; + $ws_key = $object->thirdparty->webservices_key; + $ws_user = GETPOST('ws_user','alpha'); + $ws_password = GETPOST('ws_password','alpha'); + $ws_entity = GETPOST('ws_entity','int'); + $ws_thirdparty = GETPOST('ws_thirdparty','int'); + + // NS and Authentication parameters + $ws_ns='http://www.dolibarr.org/ns/'; + $ws_authentication=array( + 'dolibarrkey'=>$ws_key, + 'sourceapplication'=>'DolibarrWebServiceClient', + 'login'=>$ws_user, + 'password'=>$ws_password, + 'entity'=>$ws_entity + ); + + //Is sync supplier web services module activated? and everything filled? + if (empty($conf->syncsupplierwebservices->enabled)) { + setEventMessage($langs->trans("WarningModuleNotActive",$langs->transnoentities("Module2650Name"))); + } else if (empty($ws_url) || empty($ws_key)) { + setEventMessage($langs->trans("ErrorWebServicesFieldsRequired"), 'errors'); + } else if (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) { + setEventMessage($langs->trans("ErrorFieldsRequired"), 'errors'); + } + else + { + //Create SOAP client and connect it to order + $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php"); + $soapclient_order->soap_defencoding='UTF-8'; + $soapclient_order->decodeUTF8(false); + + //Create SOAP client and connect it to product/service + $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); + $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->decodeUTF8(false); + + //Prepare the order lines from order + $order_lines = array(); + foreach ($object->lines as $line) + { + $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); + $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); + + if ($result_product["result"]["result_code"] == "OK") + { + $order_lines[] = array( + 'desc' => $line->product_desc, + 'type' => $line->product_type, + 'product_id' => $result_product["product"]["id"], + 'vat_rate' => $line->tva_tx, + 'qty' => $line->qty, + 'price' => $line->price, + 'unitprice' => $line->subprice, + 'total_net' => $line->total_ht, + 'total_vat' => $line->total_tva, + 'total' => $line->total_ttc, + 'date_start' => $line->date_start, + 'date_end' => $line->date_end, + ); + } + } + + //Prepare the order header + $order = array( + 'thirdparty_id' => $ws_thirdparty, + 'date' => dol_print_date(dol_now(),'dayrfc'), + 'total_net' => $object->total_ht, + 'total_var' => $object->total_tva, + 'total' => $object->total_ttc, + 'lines' => $order_lines + ); + + $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); + $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); + + if (empty($result_order["result"]["result_code"])) //No result, check error str + { + setEventMessage($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", 'errors'); + } + else if ($result_order["result"]["result_code"] != "OK") //Something went wrong + { + setEventMessage($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", 'errors'); + } + else + { + setEventMessage($langs->trans("RemoteOrderRef")." ".$result_order["ref"], 'mesgs'); + } + } +} + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->commande->creer) { if ($action == 'addcontact') @@ -1064,7 +1217,6 @@ if ($action=="create") { print_fiche_titre($langs->trans('NewOrder')); - dol_htmloutput_mesg($mesg); dol_htmloutput_events(); $societe=''; @@ -1116,6 +1268,15 @@ if ($action=="create") $form->select_types_paiements(isset($_POST['mode_reglement_id'])?$_POST['mode_reglement_id']:$mode_reglement_id,'mode_reglement_id'); print ''; + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) + { + $langs->load("bank"); + print '' . $langs->trans('BankAccount') . ''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print ''; + } + print ''.$langs->trans('NotePublic').''; print ''; $doleditor = new DolEditor('note_public', GETPOST('note_public'), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, 70); @@ -1152,19 +1313,20 @@ if ($action=="create") } elseif (! empty($object->id)) { - $author = new User($db); - $author->fetch($object->user_author_id); - $societe = new Fournisseur($db); $result=$societe->fetch($object->socid); if ($result < 0) dol_print_error($db); + $author = new User($db); + $author->fetch($object->user_author_id); + + $res=$object->fetch_optionals($object->id,$extralabels); + $head = ordersupplier_prepare_head($object); $title=$langs->trans("SupplierOrder"); dol_fiche_head($head, 'card', $title, 0, 'order'); - $res=$object->fetch_optionals($object->id,$extralabels); /* * Confirmation de la suppression de la commande @@ -1288,20 +1450,12 @@ elseif (! empty($object->id)) if (! empty($conf->projet->enabled)) $nbrow++; //Local taxes - //TODO: Place into a function to control showing by country or study better option - if ($mysoc->country_code=='ES') - { - if($mysoc->localtax1_assuj=="1") $nbrow++; - if($object->thirdparty->localtax2_assuj=="1") $nbrow++; - } - else - { - if($mysoc->localtax1_assuj=="1") $nbrow++; - if($mysoc->localtax2_assuj=="1") $nbrow++; - } + if($mysoc->localtax1_assuj=="1") $nbrow++; + if($mysoc->localtax2_assuj=="1") $nbrow++; + print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; @@ -1389,8 +1543,28 @@ elseif (! empty($object->id)) } print ''; + // Bank Account + if (! empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && ! empty($conf->banque->enabled)) + { + print ''; + print ''; + } + // Delivery date planed - print ''; + print "
'.$langs->trans("Ref").'
'; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->commande->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print '
'; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print '
'; + print '
'; print ''; @@ -1411,13 +1585,13 @@ elseif (! empty($object->id)) { print $object->date_livraison ? dol_print_date($object->date_livraison,'daytext') : ' '; } - print ''; + print ''; // Project if (! empty($conf->projet->enabled)) { $langs->load('projects'); - print '
'; print $langs->trans('DateDeliveryPlanned'); print '
'; + print '
'; print ''; @@ -1438,72 +1612,8 @@ elseif (! empty($object->id)) } // Other attributes - $parameters=array('socid'=>$socid, 'colspan' => ' colspan="3"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && ! empty($extrafields->attribute_label)) - { - if ($action == 'edit_extras') - { - print ''; - print ''; - print ''; - print ''; - } - - foreach($extrafields->attribute_label as $key=>$label) - { - if ($action == 'edit_extras') { - $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]); - } else { - $value=$object->array_options["options_".$key]; - } - - if ($extrafields->attribute_type[$key] == 'separate') - { - print $extrafields->showSeparator($key); - } - else - { - print 'attribute_required[$key])) print ' class="fieldrequired"'; - print '>'.$label.''."\n"; - } - } - - if(count($extrafields->attribute_label) > 0) - { - if ($action == 'edit_extras' && $user->rights->fournisseur->commande->creer) - { - print ''; - } - else - { - if ($object->statut == 0 && $user->rights->fournisseur->commande->creer) - { - print ''; - } - } - } - } + $cols = 3; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; // Ligne de 3 colonnes print ''; @@ -1514,37 +1624,19 @@ elseif (! empty($object->id)) print ''; // Amount Local Taxes - //TODO: Place into a function to control showing by country or study better option - if ($mysoc->country_code=='ES') + if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 { - if ($mysoc->localtax1_assuj=="1") //Localtax1 RE - { - print ''; - print ''; - print ''; - } - if ($object->thirdparty->localtax2_assuj=="1") //Localtax2 IRPF - { - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; } - else + if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 { - if ($mysoc->localtax1_assuj=="1") //Localtax1 - { - print ''; - print ''; - print ''; - } - if ($mysoc->localtax2_assuj=="1") //Localtax2 - { - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; } + print ''; print ''; @@ -1740,6 +1832,12 @@ elseif (! empty($object->id)) $doleditor=new DolEditor('eldesc',$line->description,'',200,'dolibarr_details','',false,true,$conf->global->FCKEDITOR_ENABLE_DETAILS,$nbrows,70); $doleditor->Create(); + print '
'; + print $langs->trans('ServiceLimitedDuration').' '.$langs->trans('From').' '; + print $form->select_date($date_start,'date_start'.$date_pf,$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE,$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE,1,''); + print ' '.$langs->trans('to').' '; + print $form->select_date($date_end,'date_end'.$date_pf,$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE,$conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE,1,''); + print ''; print '
'; print $langs->trans('Project'); print '
'; - // Convert date into timestamp format - if (in_array($extrafields->attribute_type[$key],array('date','datetime'))) - { - $value = isset($_POST["options_".$key])?dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]):$db->jdate($object->array_options['options_'.$key]); - } - - if ($action == 'edit_extras' && $user->rights->fournisseur->commande->creer) - { - print $extrafields->showInputField($key,$value); - } - else - { - print $extrafields->showOutputField($key,$value); - } - - print '
'; - print ''; - print ''; - print '
'.img_picto('','edit').' '.$langs->trans('Modify').'
'.$langs->trans("AmountHT").''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($object->total_localtax1).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($object->total_localtax2).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($object->total_localtax1).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($object->total_localtax1).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($object->total_localtax2).''.$langs->trans("Currency".$conf->currency).'
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($object->total_localtax2).''.$langs->trans("Currency".$conf->currency).'
'.$langs->trans("AmountTTC").''.price($object->total_ttc).''.$langs->trans("Currency".$conf->currency).'
'; print $form->load_tva('tva_tx',$line->tva_tx,$object->thirdparty,$mysoc); @@ -1768,7 +1866,6 @@ elseif (! empty($object->id)) $parameters = array(); $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - } print '
'; @@ -1777,206 +1874,6 @@ elseif (! empty($object->id)) dol_fiche_end(); - if ($action != 'presend') - { - /** - * Boutons actions - */ - if ($user->societe_id == 0 && $action != 'edit_line' && $action != 'delete') - { - print '
'; - - // Validate - if ($object->statut == 0 && $num > 0) - { - if ($user->rights->fournisseur->commande->valider) - { - print ''.$langs->trans('Validate').''; - } - } - - // Modify - if ($object->statut == 1) - { - if ($user->rights->fournisseur->commande->commander) - { - print ''.$langs->trans("Modify").''; - } - } - - // Approve - if ($object->statut == 1) - { - if ($user->rights->fournisseur->commande->approuver) - { - print ''.$langs->trans("ApproveOrder").''; - print ''.$langs->trans("RefuseOrder").''; - } - else - { - print ''.$langs->trans("ApproveOrder").''; - print ''.$langs->trans("RefuseOrder").''; - } - } - - // Send - if (in_array($object->statut, array(2, 3, 4, 5))) - { - if ($user->rights->fournisseur->commande->commander) - { - print ''.$langs->trans('SendByMail').''; - } - } - - // Reopen - if (in_array($object->statut, array(5, 6, 7, 9))) - { - if ($user->rights->fournisseur->commande->commander) - { - print ''.$langs->trans("ReOpen").''; - } - } - - // Create bill - if (! empty($conf->fournisseur->enabled) && $object->statut >= 2) // 2 means accepted - { - if ($user->rights->fournisseur->facture->creer) - { - print ''.$langs->trans("CreateBill").''; - } - - //if ($user->rights->fournisseur->commande->creer && $object->statut > 2) - //{ - // print ''.$langs->trans("ClassifyBilled").''; - //} - } - - // Cancel - if ($object->statut == 2) - { - if ($user->rights->fournisseur->commande->commander) - { - print ''.$langs->trans("CancelOrder").''; - } - } - - // Clone - if ($user->rights->fournisseur->commande->creer) - { - print ''.$langs->trans("ToClone").''; - } - - // Delete - if ($user->rights->fournisseur->commande->supprimer) - { - print ''.$langs->trans("Delete").''; - } - - print "
"; - } - print "
"; - - - print '
'; - - /* - * Documents generes - */ - $comfournref = dol_sanitizeFileName($object->ref); - $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; - $relativepath = $comfournref.'/'.$comfournref.'.pdf'; - $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; - $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed=$user->rights->fournisseur->commande->creer; - $delallowed=$user->rights->fournisseur->commande->supprimer; - - print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); - $somethingshown=$formfile->numoffiles; - - /* - * Linked object block - */ - $somethingshown=$object->showLinkedObjectBlock(); - - print '
'; - - - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown=$formactions->showactions($object,'order_supplier',$socid); - - - if ($user->rights->fournisseur->commande->commander && $object->statut == 2) - { - /* - * Commander (action=commande) - */ - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - - print ''; - - print ''; - print ''; - print '
'.$langs->trans("ToOrder").'
'.$langs->trans("OrderDate").''; - $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - print $form->select_date($date_com,'','','','',"commande"); - print '
'.$langs->trans("OrderMode").''; - $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); - print '
'.$langs->trans("Comment").'
'; - print '
'; - } - - if ($user->rights->fournisseur->commande->receptionner && ($object->statut == 3 || $object->statut == 4)) - { - /* - * Receptionner (action=livraison) - */ - print '
'; - print '
'; - print ''; - print ''; - print ''; - print ''; - print '\n"; - - print "'; - print ''; - print ''; - print "
'.$langs->trans("Receive").'
'.$langs->trans("DeliveryDate").''; - print $form->select_date('','','','','',"commande"); - print "
".$langs->trans("Delivery")."\n"; - $liv = array(); - $liv[''] = ' '; - $liv['tot'] = $langs->trans("TotalWoman"); - $liv['par'] = $langs->trans("PartialWoman"); - $liv['nev'] = $langs->trans("NeverReceived"); - $liv['can'] = $langs->trans("Canceled"); - - print $form->selectarray("type",$liv); - - print '
'.$langs->trans("Comment").'
\n"; - print "
\n"; - } - - // List of actions on element - /* Hidden because" available into "Log" tab - print '
'; - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown=$formactions->showactions($object,'order_supplier',$socid); - */ - - print '
'; - } - /* * Action presend */ @@ -1987,21 +1884,25 @@ elseif (! empty($object->id)) $fileparams = dol_most_recent_file($conf->fournisseur->commande->dir_output . '/' . $ref, preg_quote($ref,'/')); $file=$fileparams['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->client->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('commercial'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - - $result=supplier_order_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result= $object->generateDocument(GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -2018,6 +1919,7 @@ elseif (! empty($object->id)) // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -2028,7 +1930,7 @@ elseif (! empty($object->id)) $formmail->withto=GETPOST("sendto")?GETPOST("sendto"):$liste; $formmail->withtocc=$liste; $formmail->withtoccc=(! empty($conf->global->MAIN_EMAIL_USECCC)?$conf->global->MAIN_EMAIL_USECCC:false); - $formmail->withtopic=$langs->trans('SendOrderRef','__ORDERREF__'); + $formmail->withtopic=$outputlangs->trans('SendOrderRef','__ORDERREF__'); $formmail->withfile=2; $formmail->withbody=1; $formmail->withdeliveryreceipt=1; @@ -2077,6 +1979,430 @@ elseif (! empty($object->id)) print '
'; } + /* + * Action webservice + */ + elseif ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && ! GETPOST('cancel')) + { + $mode = GETPOST('mode', 'alpha'); + $ws_url = $object->thirdparty->webservices_url; + $ws_key = $object->thirdparty->webservices_key; + $ws_user = GETPOST('ws_user','alpha'); + $ws_password = GETPOST('ws_password','alpha'); + + // NS and Authentication parameters + $ws_ns = 'http://www.dolibarr.org/ns/'; + $ws_authentication = array( + 'dolibarrkey'=>$ws_key, + 'sourceapplication'=>'DolibarrWebServiceClient', + 'login'=>$ws_user, + 'password'=>$ws_password, + 'entity'=>'' + ); + + print_titre($langs->trans('CreateRemoteOrder')); + + //Is everything filled? + if (empty($ws_url) || empty($ws_key)) { + setEventMessage($langs->trans("ErrorWebServicesFieldsRequired"), 'errors'); + $mode = "init"; + $error_occurred = true; //Don't allow to set the user/pass if thirdparty fields are not filled + } else if ($mode != "init" && (empty($ws_user) || empty($ws_password))) { + setEventMessage($langs->trans("ErrorFieldsRequired"), 'errors'); + $mode = "init"; + } + + if ($mode == "init") + { + //Table/form header + print ''; + print ''; + print ''; + print ''; + print ''; + + if ($error_occurred) + { + print "
".$langs->trans("ErrorOccurredReviseAndRetry")."
"; + print ''; + } + else + { + $textinput_size = "50"; + // Webservice url + print ''; + //Remote User + print ''; + //Remote Password + print ''; + //Submit button + print ''; + } + + //End table/form + print ''; + print '
'.$langs->trans("WebServiceURL").''.dol_print_url($ws_url).'
'.$langs->trans("User").'
'.$langs->trans("Password").'
'; + print ''; + print '     '; + //Cancel button + print ''; + print '
'; + } + elseif ($mode == "check") + { + $ws_entity = ''; + $ws_thirdparty = ''; + $error_occurred = false; + + //Create SOAP client and connect it to user + $soapclient_user = new nusoap_client($ws_url."/webservices/server_user.php"); + $soapclient_user->soap_defencoding='UTF-8'; + $soapclient_user->decodeUTF8(false); + + //Get the thirdparty associated to user + $ws_parameters = array('authentication'=>$ws_authentication, 'id' => '', 'ref'=>$ws_user); + $result_user = $soapclient_user->call("getUser", $ws_parameters, $ws_ns, ''); + $user_status_code = $result_user["result"]["result_code"]; + + if ($user_status_code == "OK") + { + //Fill the variables + $ws_entity = $result_user["user"]["entity"]; + $ws_authentication['entity'] = $ws_entity; + $ws_thirdparty = $result_user["user"]["fk_thirdparty"]; + if (empty($ws_thirdparty)) + { + setEventMessage($langs->trans("RemoteUserMissingAssociatedSoc"), 'errors'); + $error_occurred = true; + } + else + { + //Create SOAP client and connect it to product/service + $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php"); + $soapclient_product->soap_defencoding='UTF-8'; + $soapclient_product->decodeUTF8(false); + + // Iterate each line and get the reference that uses the supplier of that product/service + $i = 0; + foreach ($object->lines as $line) { + $i = $i + 1; + $ref_supplier = $line->ref_supplier; + $line_id = $i."º) ".$line->product_ref.": "; + if (empty($ref_supplier)) { + continue; + } + $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $ref_supplier); + $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); + if (!$result_product) + { + setEventMessage($line_id.$langs->trans("SOAPError")." ".$soapclient_product->error_str." - ".$soapclient_product->response, 'errors'); + $error_occurred = true; + break; + } + + // Check the result code + $status_code = $result_product["result"]["result_code"]; + if (empty($status_code)) //No result, check error str + { + setEventMessage($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", 'errors'); + } + else if ($status_code != "OK") //Something went wrong + { + if ($status_code == "NOT_FOUND") + { + setEventMessage($line_id.$langs->trans("SupplierMissingRef")." '".$ref_supplier."'", 'warnings'); + } + else + { + setEventMessage($line_id.$langs->trans("ResponseNonOK")." '".$status_code."' - '".$result_product["result"]["result_label"]."'", 'errors'); + $error_occurred = true; + break; + } + } + + + // Ensure that price is equal and warn user if it's not + $supplier_price = price($result_product["product"]["price_net"]); //Price of client tab in supplier dolibarr + $local_price = NULL; //Price of supplier as stated in product suppliers tab on this dolibarr, NULL if not found + + $product_fourn = new ProductFournisseur($db); + $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product); + if (count($product_fourn_list)>0) + { + foreach($product_fourn_list as $product_fourn_line) + { + //Only accept the line where the supplier is the same at this order and has the same ref + if ($product_fourn_line->fourn_id == $object->socid && $product_fourn_line->fourn_ref == $ref_supplier) { + $local_price = price($product_fourn_line->fourn_price); + } + } + } + + if ($local_price != NULL && $local_price != $supplier_price) { + setEventMessage($line_id.$langs->trans("RemotePriceMismatch")." ".$supplier_price." - ".$local_price, 'warnings'); + } + + // Check if is in sale + if (empty($result_product["product"]["status_tosell"])) { + setEventMessage($line_id.$langs->trans("ProductStatusNotOnSellShort")." '".$ref_supplier."'", 'warnings'); + } + } + } + + } + elseif ($user_status_code == "PERMISSION_DENIED") + { + setEventMessage($langs->trans("RemoteUserNotPermission"), 'errors'); + $error_occurred = true; + } + elseif ($user_status_code == "BAD_CREDENTIALS") + { + setEventMessage($langs->trans("RemoteUserBadCredentials"), 'errors'); + $error_occurred = true; + } + else + { + setEventMessage($langs->trans("ResponseNonOK")." '".$user_status_code."'", 'errors'); + $error_occurred = true; + } + + //Form + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($error_occurred) + { + print "
".$langs->trans("ErrorOccurredReviseAndRetry")."
"; + } + else + { + print ''; + print '     '; + } + print ''; + print '
'; + } + } + /* + * Show buttons + */ + else + { + /** + * Boutons actions + */ + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been + // modified by hook + if (empty($reshook)) + { + if ($user->societe_id == 0 && $action != 'edit_line' && $action != 'delete') + { + print '
'; + + // Validate + if ($object->statut == 0 && $num > 0) + { + if ($user->rights->fournisseur->commande->valider) + { + print ''.$langs->trans('Validate').''; + } + } + + // Modify + if ($object->statut == 1) + { + if ($user->rights->fournisseur->commande->commander) + { + print ''.$langs->trans("Modify").''; + } + } + + // Approve + if ($object->statut == 1) + { + if ($user->rights->fournisseur->commande->approuver) + { + print ''.$langs->trans("ApproveOrder").''; + print ''.$langs->trans("RefuseOrder").''; + } + else + { + print ''.$langs->trans("ApproveOrder").''; + print ''.$langs->trans("RefuseOrder").''; + } + } + + // Send + if (in_array($object->statut, array(2, 3, 4, 5))) + { + if ($user->rights->fournisseur->commande->commander) + { + print ''.$langs->trans('SendByMail').''; + } + } + + // Reopen + if (in_array($object->statut, array(2, 5, 6, 7, 9))) + { + if ($user->rights->fournisseur->commande->commander) + { + print ''.$langs->trans("ReOpen").''; + } + } + + // Create bill + if (! empty($conf->fournisseur->enabled) && $object->statut >= 2) // 2 means accepted + { + if ($user->rights->fournisseur->facture->creer) + { + print ''.$langs->trans("CreateBill").''; + } + + //if ($user->rights->fournisseur->commande->creer && $object->statut > 2) + //{ + // print ''.$langs->trans("ClassifyBilled").''; + //} + } + + + // Create a remote order using WebService only if module is activated + if (! empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) // 2 means accepted + { + print ''.$langs->trans('CreateRemoteOrder').''; + } + + // Cancel + if ($object->statut == 2) + { + if ($user->rights->fournisseur->commande->commander) + { + print ''.$langs->trans("CancelOrder").''; + } + } + + // Clone + if ($user->rights->fournisseur->commande->creer) + { + print ''.$langs->trans("ToClone").''; + } + + // Delete + if ($user->rights->fournisseur->commande->supprimer) + { + print ''.$langs->trans("Delete").''; + } + + print "
"; + } + } + print "
"; + + + print '
'; + + /* + * Documents generes + */ + $comfournref = dol_sanitizeFileName($object->ref); + $file = $conf->fournisseur->dir_output . '/commande/' . $comfournref . '/' . $comfournref . '.pdf'; + $relativepath = $comfournref.'/'.$comfournref.'.pdf'; + $filedir = $conf->fournisseur->dir_output . '/commande/' . $comfournref; + $urlsource=$_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed=$user->rights->fournisseur->commande->creer; + $delallowed=$user->rights->fournisseur->commande->supprimer; + + print $formfile->showdocuments('commande_fournisseur',$comfournref,$filedir,$urlsource,$genallowed,$delallowed,$object->modelpdf,1,0,0,0,0,'','','',$object->thirdparty->default_lang); + $somethingshown=$formfile->numoffiles; + + /* + * Linked object block + */ + $somethingshown=$object->showLinkedObjectBlock(); + + print '
'; + + + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown=$formactions->showactions($object,'order_supplier',$socid); + + + if ($user->rights->fournisseur->commande->commander && $object->statut == 2) + { + /* + * Commander (action=commande) + */ + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + + print ''; + + print ''; + print ''; + print '
'.$langs->trans("ToOrder").'
'.$langs->trans("OrderDate").''; + $date_com = dol_mktime(0, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + print $form->select_date($date_com,'','','','',"commande"); + print '
'.$langs->trans("OrderMode").''; + $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1); + print '
'.$langs->trans("Comment").'
'; + print '
'; + } + + if ($user->rights->fournisseur->commande->receptionner && ($object->statut == 3 || $object->statut == 4)) + { + /* + * Receptionner (action=livraison) + */ + print '
'; + print '
'; + print ''; + print ''; + print ''; + print ''; + print '\n"; + + print "'; + print ''; + print ''; + print "
'.$langs->trans("Receive").'
'.$langs->trans("DeliveryDate").''; + print $form->select_date('','','','','',"commande"); + print "
".$langs->trans("Delivery")."\n"; + $liv = array(); + $liv[''] = ' '; + $liv['tot'] = $langs->trans("TotalWoman"); + $liv['par'] = $langs->trans("PartialWoman"); + $liv['nev'] = $langs->trans("NeverReceived"); + $liv['can'] = $langs->trans("Canceled"); + + print $form->selectarray("type",$liv); + + print '
'.$langs->trans("Comment").'
\n"; + print "
\n"; + } + + // List of actions on element + /* Hidden because" available into "Log" tab + print '
'; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions=new FormActions($db); + $somethingshown=$formactions->showactions($object,'order_supplier',$socid); + */ + + print '
'; + } print '
'; } diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index 8311e8bfc9f..b8eabb9be6c 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -69,11 +69,11 @@ if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer) if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); } else { - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } } @@ -126,7 +126,6 @@ $userstatic=new User($db); /* Mode vue et edition */ /* */ /* *************************************************************************** */ -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { @@ -147,7 +146,7 @@ if ($id > 0 || ! empty($ref)) */ print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index 02666e1c855..bea467340e6 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -120,12 +120,9 @@ if ($_POST["action"] == 'dispatch' && $user->rights->fournisseur->commande->rece if (! $notrigger) { global $conf, $langs, $user; - // Appel des triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($db); - $result_trigger=$interface->run_triggers('ORDER_SUPPLIER_DISPATCH',$commande,$user,$langs,$conf); - if ($result_trigger < 0) { $error++; $commande->errors=$interface->errors; } - // Fin appel triggers + // Call trigger + $result=$commande->call_trigger('ORDER_SUPPLIER_DISPATCH',$user); + // End call triggers } if ($result > 0) diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index a3681b8fc02..2949aedcf14 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -110,7 +110,7 @@ if ($object->id > 0) print '
'.$langs->trans("Ref").'
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; diff --git a/htdocs/fourn/commande/history.php b/htdocs/fourn/commande/history.php index e53b3974cf4..c864dce3b88 100644 --- a/htdocs/fourn/commande/history.php +++ b/htdocs/fourn/commande/history.php @@ -76,7 +76,7 @@ if ($id > 0 || ! empty($ref)) print '
'.$langs->trans("Ref").'
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; @@ -160,7 +160,7 @@ if ($id > 0 || ! empty($ref)) print '\n"; // User - print ''; // Comment diff --git a/htdocs/fourn/commande/index.php b/htdocs/fourn/commande/index.php index 85557877d76..0f04ee91eaa 100644 --- a/htdocs/fourn/commande/index.php +++ b/htdocs/fourn/commande/index.php @@ -59,7 +59,7 @@ print ''; -print ''; +print ''; print ''; diff --git a/htdocs/fourn/commande/liste.php b/htdocs/fourn/commande/list.php similarity index 74% rename from htdocs/fourn/commande/liste.php rename to htdocs/fourn/commande/list.php index 4b005a88724..4f0974abd10 100644 --- a/htdocs/fourn/commande/liste.php +++ b/htdocs/fourn/commande/list.php @@ -21,7 +21,7 @@ */ /** - * \file htdocs/fourn/commande/liste.php + * \file htdocs/fourn/commande/list.php * \ingroup fournisseur * \brief List of suppliers orders */ @@ -34,27 +34,41 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php'; $langs->load("orders"); +$langs->load("sendings"); $search_ref=GETPOST('search_ref'); $search_refsupp=GETPOST('search_refsupp'); -$search_nom=GETPOST('search_nom'); +$search_company=GETPOST('search_company'); $search_user=GETPOST('search_user'); $search_ttc=GETPOST('search_ttc'); $sall=GETPOST('search_all'); $search_status=GETPOST('search_status','int'); -if ($search_status == '') $search_status=-1; $page = GETPOST('page','int'); $socid = GETPOST('socid','int'); $sortorder = GETPOST('sortorder','alpha'); $sortfield = GETPOST('sortfield','alpha'); +$viewstatut=GETPOST('viewstatut'); + // Security check $orderid = GETPOST('orderid'); if ($user->societe_id) $socid=$user->societe_id; $result = restrictedArea($user, 'fournisseur', $orderid, '', 'commande'); +// Purge search criteria +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=''; + $search_refsupp=''; + $search_company=''; + $search_user=''; + $search_ttc=''; + $search_status=''; +} + +if ($search_status == '') $search_status=-1; /* * View @@ -65,7 +79,7 @@ if ($socid > 0) { $fourn = new Fournisseur($db); $fourn->fetch($socid); - $title .= ' ('.$fourn->nom.')'; + $title .= ' ('.$fourn->name.')'; } llxHeader('',$title); @@ -84,8 +98,8 @@ $offset = $conf->liste_limit * $page ; * Mode Liste */ -$sql = "SELECT s.rowid as socid, s.nom, cf.date_commande as dc,"; -$sql.= " cf.rowid,cf.ref, cf.ref_supplier, cf.fk_statut, cf.total_ttc, cf.fk_user_author,"; +$sql = "SELECT s.rowid as socid, s.nom as name, cf.date_commande as dc,"; +$sql.= " cf.rowid,cf.ref, cf.ref_supplier, cf.fk_statut, cf.total_ttc, cf.fk_user_author,cf.date_livraison,"; $sql.= " u.login"; $sql.= " FROM (".MAIN_DB_PREFIX."societe as s,"; $sql.= " ".MAIN_DB_PREFIX."commande_fournisseur as cf"; @@ -99,9 +113,9 @@ if ($search_ref) { $sql .= natural_search('cf.ref', $search_ref); } -if ($search_nom) +if ($search_company) { - $sql .= natural_search('s.nom', $search_nom); + $sql .= natural_search('s.nom', $search_company); } if ($search_user) { @@ -109,7 +123,7 @@ if ($search_user) } if ($search_ttc) { - $sql .= " AND total_ttc = ".price2num($search_ttc); + $sql .= " AND total_ttc = '".$db->escape(price2num($search_ttc))."'"; } if ($sall) { @@ -151,13 +165,14 @@ if ($resql) $i = 0; $param=""; - if ($search_ref) $param.="&search_ref=".$search_ref; - if ($search_nom) $param.="&search_nom=".$search_nom; - if ($search_user) $param.="&search_user=".$search_user; - if ($search_ttc) $param.="&search_ttc=".$search_ttc; - if ($search_refsupp) $param.="&search_refsupp=".$search_refsupp; - if ($socid) $param.="&socid=".$socid; - if ($search_status >= 0) $param.="&search_status=".$search_status; + if ($search_ref) $param.="&search_ref=".$search_ref; + if ($search_company) $param.="&search_company=".$search_company; + if ($search_user) $param.="&search_user=".$search_user; + if ($search_ttc) $param.="&search_ttc=".$search_ttc; + if ($search_refsupp) $param.="&search_refsupp=".$search_refsupp; + if ($socid) $param.="&socid=".$socid; + if ($search_status >= 0) $param.="&search_status=".$search_status; + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords); print ''; print '
'.$langs->trans("Ref").''.$commande->LibStatut($obj->fk_statut,4)."'; + print ''; print img_object($langs->trans("ShowUser"),'user').' '.$obj->login.'
'; */ $var=false; print ''; -print ''; +print ''; print ''; print ''; print '"; print ''; - print ''; + print ''; print "\n"; } } @@ -184,7 +184,7 @@ if ($resql) print ""; print ''; - print ''; + print ''; print "\n"; $i++; @@ -204,7 +204,7 @@ else if (! empty($conf->fournisseur->enabled)) { - $sql = "SELECT c.rowid, c.ref, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -232,8 +232,8 @@ if (! empty($conf->fournisseur->enabled)) $obj = $db->fetch_object($resql); print ""; print '"; - print ''; + print "rowid."\">".img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.""; + print ''; $i++; } } @@ -300,7 +300,7 @@ print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -369,7 +369,7 @@ else dol_print_error($db); * Orders to process */ /* - $sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom, s.rowid as socid"; + $sql = "SELECT c.rowid, c.ref, c.fk_statut, s.nom as name, s.rowid as socid"; $sql.=" FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -387,7 +387,7 @@ $num = $db->num_rows($resql); print '
'.$langs->trans("SearchOrder").'
'; @@ -125,7 +125,7 @@ if ($resql) $var=!$var; print "
'.$commandestatic->LibStatut($statut,0).''.(isset($vals[$statut])?$vals[$statut]:0).''.(isset($vals[$statut])?$vals[$statut]:0).'
'.$langs->trans($commandestatic->statuts[$row[1]]).''.$row[0].' '.$commandestatic->LibStatut($row[1],3).''.$row[0].' '.$commandestatic->LibStatut($row[1],3).'
'; - print "rowid."\">".img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref."'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).'
'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,24).'
'; */ $max=5; -$sql = "SELECT c.rowid, c.ref, c.fk_statut, c.tms, s.nom, s.rowid as socid"; +$sql = "SELECT c.rowid, c.ref, c.fk_statut, c.tms, s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -353,7 +353,7 @@ if ($resql) print ''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.dol_print_date($db->jdate($obj->tms),'day').''.$commandestatic->LibStatut($obj->fk_statut,5).'
'; print ''; -print ''; +print ''; if ($num) { @@ -421,7 +421,7 @@ print '
'.$langs->trans("OrdersToProcess").' ('.$num.')
'.$langs->trans("OrdersToProcess").' ('.$num.')
'; print '
'.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->nom,24).''.img_object($langs->trans("ShowCompany"),"company").' '.dol_trunc($obj->name,24).''.$commandestatic->LibStatut($obj->fk_statut,$obj->facture,5).'
'; @@ -168,6 +183,7 @@ if ($resql) print_liste_field_titre($langs->trans("Author"),$_SERVER["PHP_SELF"],"u.login","",$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"total_ttc","",$param,$sortfield,$sortorder); print_liste_field_titre($langs->trans("OrderDate"),$_SERVER["PHP_SELF"],"dc","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('DateDeliveryPlanned'),$_SERVER["PHP_SELF"],'cf.date_livraison','',$param, 'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"cf.fk_statut","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre(''); print "\n"; @@ -176,17 +192,17 @@ if ($resql) print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; + print ''; print ''; - print ''; - print ''; + print '\n"; $var=true; @@ -201,7 +217,7 @@ if ($resql) print ""; // Ref - print ''."\n"; + print ''."\n"; // Author $userstatic->id=$obj->fk_user_author; @@ -238,6 +254,12 @@ if ($resql) } print ''; + // Delivery date + print ''; + + // Statut print ''; @@ -246,6 +268,8 @@ if ($resql) } print "
  '; $formorder->selectSupplierOrderStatus($search_status,1,'search_status'); print ''; - print ''; - print '
'; + print ''; + print "
'.img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.''; + print ''.img_object($langs->trans("ShowOrder"),"order").' '.$obj->ref.''; $filename=dol_sanitizeFileName($obj->ref); $filedir=$conf->fournisseur->dir_output.'/commande' . '/' . dol_sanitizeFileName($obj->ref); print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); @@ -212,8 +228,8 @@ if ($resql) // Company - print ''.img_object($langs->trans("ShowCompany"),"company").' '; - print $obj->nom.''.img_object($langs->trans("ShowCompany"),"company").' '; + print $obj->name.''; + print dol_print_date($db->jdate($obj->date_livraison), 'day'); + print ''.$commandestatic->LibStatut($obj->fk_statut, 5).'
\n"; print "\n"; + + print '
'.img_help(1,'').' '.$langs->trans("ToBillSeveralOrderSelectCustomer", $langs->transnoentitiesnoconv("CreateInvoiceForThisCustomer")).'
'; $db->free($resql); } diff --git a/htdocs/fourn/commande/note.php b/htdocs/fourn/commande/note.php index b9cbf6e33b7..6a1c6cfe80e 100644 --- a/htdocs/fourn/commande/note.php +++ b/htdocs/fourn/commande/note.php @@ -91,7 +91,7 @@ if ($id > 0 || ! empty($ref)) */ print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; // Ref print ''; diff --git a/htdocs/fourn/commande/orderstoinvoice.php b/htdocs/fourn/commande/orderstoinvoice.php new file mode 100644 index 00000000000..3397b18a30b --- /dev/null +++ b/htdocs/fourn/commande/orderstoinvoice.php @@ -0,0 +1,594 @@ + + * Copyright (C) 2004-2013 Laurent Destailleur + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2012 Andreu Bisquerra Gaya + * Copyright (C) 2012 David Rodriguez Martinez + * Copyright (C) 2012 Juanjo Menent + * Copyright (C) 2014 Florian Henry + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/fourn/commande/orderstoinvoice.php + * \ingroup commande + * \brief Page to invoice multiple supplier orders + */ +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php'; +require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.commande.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/report.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/core/modules/supplier_invoice/modules_facturefournisseur.php'; +if (! empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php'; +} + +$langs->load('orders'); +$langs->load('deliveries'); +$langs->load('companies'); + +if (! $user->rights->facture->creer) + accessforbidden(); + +$id = (GETPOST('id') ? GETPOST('id', 'int') : GETPOST("facid")); // For backward compatibility +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm', 'alpha'); +$sref = GETPOST('sref'); +$sref_client = GETPOST('sref_client'); +$sall = GETPOST('sall'); +$socid = GETPOST('socid', 'int'); +$selected = GETPOST('orders_to_invoice'); +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$viewstatut = GETPOST('viewstatut'); + +if (! $sortfield) + $sortfield = 'c.rowid'; +if (! $sortorder) + $sortorder = 'DESC'; + +$now = dol_now(); +$date_start = dol_mktime(0, 0, 0, $_REQUEST["date_startmonth"], $_REQUEST["date_startday"], $_REQUEST["date_startyear"]); // Date for local PHP server +$date_end = dol_mktime(23, 59, 59, $_REQUEST["date_endmonth"], $_REQUEST["date_endday"], $_REQUEST["date_endyear"]); +$date_starty = dol_mktime(0, 0, 0, $_REQUEST["date_start_delymonth"], $_REQUEST["date_start_delyday"], $_REQUEST["date_start_delyyear"]); // Date for local PHP server +$date_endy = dol_mktime(23, 59, 59, $_REQUEST["date_end_delymonth"], $_REQUEST["date_end_delyday"], $_REQUEST["date_end_delyyear"]); + +if ($action == 'create') { + if (is_array($selected) == false) { + $mesgs = array ( + '
' . $langs->trans('Error_OrderNotChecked') . '
' + ); + } else { + $origin = GETPOST('origin'); + $originid = GETPOST('originid'); + } +} + +// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array +include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; +$hookmanager = new HookManager($db); +$hookmanager->initHooks(array('orderstoinvoicesupplier')); + +/* + * Actions + */ + +if (($action == 'create' || $action == 'add') && empty($mesgs)) { + + require_once DOL_DOCUMENT_ROOT . '/core/lib/fourn.lib.php'; + if (! empty($conf->projet->enabled)) + require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php'; + + $langs->load('bills'); + $langs->load('products'); + $langs->load('main'); + if (isset($_GET['orders_to_invoice'])) { + $orders_id = $_GET['orders_to_invoice']; + $n = count($orders_id); + $i = 0; + + $originid = $orders_id[0]; + $_GET['originid'] = $orders_id[0]; + } + if (isset($_POST['orders_to_invoice'])) { + $orders_id = $_POST['orders_to_invoice']; + $nn = count($orders_id); + $ii = 0; + + $originid = $orders_id[0]; + $_POST['originid'] = $orders_id[0]; + } + + $projectid = GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0; + $lineid = GETPOST('lineid', 'int'); + $userid = GETPOST('userid', 'int'); + $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref') : GETPOST('search_ref'); + + // Security check + if ($user->societe_id) + $socid = $user->societe_id; + $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); + + $usehm = $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE; + $object = new FactureFournisseur($db); + + // Insert new invoice in database + if ($action == 'add' && $user->rights->fournisseur->facture->creer) { + $object->socid = GETPOST('socid'); + $db->begin(); + $error = 0; + + // Standard or deposit or proforma invoice + $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']); + if (empty($datefacture)) { + $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y")); + } + if (! $error) { + $object->ref = $_POST['ref']; + $object->ref_supplier = $_POST['ref_supplier']; + $object->socid = $_POST['socid']; + $object->libelle = $_POST['libelle']; + $object->date = $datefacture; + $object->date_echeance = $datedue; + $object->note_public = GETPOST('note_public'); + $object->note_private = GETPOST('note_private'); + $object->cond_reglement_id = GETPOST('cond_reglement_id'); + $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $projectid = GETPOST('projectid'); + if ($projectid > 0) + $object->fk_project = $projectid; + + // Auto calculation of date due if not filled by user + if (empty($object->date_echeance)) + $object->date_echeance = $object->calculate_date_lim_reglement(); + + if ($_POST['origin'] && $_POST['originid']) { + $object->origin = $_POST['origin']; + $object->origin_id = $orders_id[$ii]; + $object->linked_objects = $orders_id; + $id = $object->create($user); + + if ($id > 0) { + foreach ( $orders_id as $origin => $origin_id ) { + $origin_id = (! empty($origin_id) ? $origin_id : $object->origin_id); + $db->begin(); + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element ("; + $sql .= "fk_source"; + $sql .= ", sourcetype"; + $sql .= ", fk_target"; + $sql .= ", targettype"; + $sql .= ") VALUES ("; + $sql .= $origin_id; + $sql .= ", '" . $object->origin . "'"; + $sql .= ", " . $id; + $sql .= ", '" . $object->element . "'"; + $sql .= ")"; + + if ($db->query($sql)) { + $db->commit(); + } else { + $db->rollback(); + } + } + + while ( $ii < $nn ) { + $objectsrc = new CommandeFournisseur($db); + dol_syslog("Try to find source object origin=" . $object->origin . " originid=" . $object->origin_id . " to add lines"); + $result = $objectsrc->fetch($orders_id[$ii]); + if ($result > 0) { + $lines = $objectsrc->lines; + if (empty($lines) && method_exists($objectsrc, 'fetch_lines')) { + $objectsrc->fetch_lines(); + $lines = $objectsrc->lines; + } + $fk_parent_line = 0; + $num = count($lines); + for($i = 0; $i < $num; $i ++) { + $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); + + $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); + $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); + + // Dates + // TODO mutualiser + $date_start = $lines[$i]->date_debut_prevue; + if ($lines[$i]->date_debut_reel) + $date_start = $lines[$i]->date_debut_reel; + if ($lines[$i]->date_start) + $date_start = $lines[$i]->date_start; + $date_end = $lines[$i]->date_fin_prevue; + if ($lines[$i]->date_fin_reel) + $date_end = $lines[$i]->date_fin_reel; + if ($lines[$i]->date_end) + $date_end = $lines[$i]->date_end; + + // Reset fk_parent_line for no child products and special product + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { + $fk_parent_line = 0; + } + // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example. + $result = $object->addline($desc, $lines[$i]->subprice, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->qty, $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, 'HT', $product_type); + + if ($result > 0) { + $lineid = $result; + } else { + $lineid = 0; + $error ++; + break; + } + // Defined the new fk_parent_line + if ($result > 0 && $lines[$i]->product_type == 9) { + $fk_parent_line = $result; + } + } + } else { + $mesgs[] = $objectsrc->error; + $error ++; + } + $ii ++; + } + } else { + $mesgs[] = $object->error; + $error ++; + } + } + } + + // End of object creation, we show it + if ($id > 0 && ! $error) { + $db->commit(); + header('Location: ' . DOL_URL_ROOT . '/fourn/facture/card.php?facid=' . $id); + exit(); + } else { + $db->rollback(); + $action = 'create'; + $_GET["origin"] = $_POST["origin"]; + $_GET["originid"] = $_POST["originid"]; + $mesgs[] = '
' . $object->error . '
'; + } + } +} + +/* + * View + */ + +$html = new Form($db); +$htmlother = new FormOther($db); +$formfile = new FormFile($db); +$companystatic = new Societe($db); + +// Mode creation +if ($action == 'create' && empty($mesgs)) { + + llxHeader(); + print_fiche_titre($langs->trans('NewBill')); + + $soc = new Societe($db); + if ($socid) + $res = $soc->fetch($socid); + if ($res) { + $cond_reglement_id = $soc->cond_reglement_id; + $mode_reglement_id = $soc->mode_reglement_id; + } + $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ? - 1 : ''; + + print '
'; + print ''; + print ''; + print '' . "\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Ref").'
'; + + // Ref + print ''; + + // Ref supplier + print ''; + print ''; + + // Third party + print ''; + print '' . "\n"; + + // Date invoice + print ''; + // Payment term + print ''; + // Payment mode + print ''; + // Project + if (! empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); + + $langs->load('projects'); + print ''; + } + + $objectsrc = new CommandeFournisseur($db); + $listoforders = array (); + foreach ( $selected as $sel ) { + $result = $objectsrc->fetch($sel); + if ($result > 0) { + $listoforders[] = $objectsrc->ref; + } + } + + // Other attributes + $parameters = array ( + 'objectsrc' => $objectsrc, + 'idsrc' => $listoforders, + 'colspan' => ' colspan="3"' + ); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + + // Modele PDF + print ''; + print '"; + + // Public note + print ''; + print ''; + print ''; + // Private note + if (empty($user->societe_id)) { + print ''; + print ''; + print ''; + } + + print '
' . $langs->trans('Ref') . '' . $langs->trans('Draft') . '
' . $langs->trans('RefSupplier') . '
' . $langs->trans('Customer') . ''; + print $soc->getNomUrl(1); + print ''; + print '
' . $langs->trans('Date') . ''; + $html->select_date('', '', '', '', '', "add", 1, 1); + print '
' . $langs->trans('PaymentConditionsShort') . ''; + $html->select_conditions_paiements(isset($_POST['cond_reglement_id']) ? $_POST['cond_reglement_id'] : $cond_reglement_id, 'cond_reglement_id'); + print '
' . $langs->trans('PaymentMode') . ''; + $html->select_types_paiements(isset($_POST['mode_reglement_id']) ? $_POST['mode_reglement_id'] : $mode_reglement_id, 'mode_reglement_id'); + print '
' . $langs->trans('Project') . ''; + $formproject->select_projects($soc->id, $projectid, 'projectid'); + print '
' . $langs->trans('Model') . ''; + $liste = ModelePDFSuppliersInvoices::liste_modeles($db); + print $html->selectarray('model', $liste, $conf->global->INVOICE_SUPPLIER_ADDON_PDF); + print "
' . $langs->trans('NotePublic') . ''; + print '
' . $langs->trans('NotePrivate') . ''; + print '
'; + + while ( $i < $n ) { + print ''; + + $i ++; + } + + // Button "Create Draft" + print '
'; + print "\n"; + + print '
\n"; +} + +// Mode liste +if (($action != 'create' && $action != 'add') || ! empty($mesgs)) { + llxHeader(); + ?> + +rights->societe->client->voir && ! $socid) + $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc"; + $sql .= ' WHERE c.entity = ' . $conf->entity; + $sql .= ' AND c.fk_soc = s.rowid'; + + // Show orders with status validated, shipping started and delivered (well any order we can bill) + $sql .= " AND c.fk_statut IN (5)"; + + // Find order that are not already invoiced + $sql .= " AND c.rowid NOT IN (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE targettype='invoice_supplier')"; + + if ($socid) + $sql .= ' AND s.rowid = ' . $socid; + if (! $user->rights->societe->client->voir && ! $socid) + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . $user->id; + if ($sref) { + $sql .= " AND c.ref LIKE '%" . $db->escape($sref) . "%'"; + } + if ($sall) { + $sql .= " AND (c.ref LIKE '%" . $db->escape($sall) . "%' OR c.note LIKE '%" . $db->escape($sall) . "%')"; + } + + // Date filter + if ($date_start && $date_end) + $sql .= " AND c.date_commande >= '" . $db->idate($date_start) . "' AND c.date_commande <= '" . $db->idate($date_end) . "'"; + if ($date_starty && $date_endy) + $sql .= " AND c.date_livraison >= '" . $db->idate($date_starty) . "' AND c.date_livraison <= '" . $db->idate($date_endy) . "'"; + + if (! empty($sref_client)) { + $sql .= ' AND c.ref_supplier LIKE \'%' . $db->escape($sref_client) . '%\''; + } + $sql .= ' ORDER BY ' . $sortfield . ' ' . $sortorder; + dol_syslog('fourn/commande/ordertoinvoice.php sql=' . $sql); + $resql = $db->query($sql); + + if ($resql) { + if ($socid) { + $soc = new Societe($db); + $soc->fetch($socid); + } + $title = $langs->trans('ListOfSupplierOrders'); + $title .= ' - ' . $langs->trans('StatusOrderReceivedAllShort'); + $num = $db->num_rows($resql); + print_fiche_titre($title); + $i = 0; + $period = $html->select_date($date_start, 'date_start', 0, 0, 1, '', 1, 0, 1) . ' - ' . $html->select_date($date_end, 'date_end', 0, 0, 1, '', 1, 0, 1); + $periodely = $html->select_date($date_starty, 'date_start_dely', 0, 0, 1, '', 1, 0, 1) . ' - ' . $html->select_date($date_endy, 'date_end_dely', 0, 0, 1, '', 1, 0, 1); + + if (! empty($socid)) { + // Company + $companystatic->id = $socid; + $companystatic->nom = $soc->nom; + print '

' . $companystatic->getNomUrl(1, 'customer') . '

'; + } + + print ''; + print ''; + print_liste_field_titre($langs->trans('Ref'), 'orderstoinvoice.php', 'c.ref', '', '&socid=' . $socid, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans('RefSupplier'), 'orderstoinvoice.php', 'c.ref_supplier', '', '&socid=' . $socid, '', $sortfield, $sortorder); + print_liste_field_titre($langs->trans('OrderDate'), 'orderstoinvoice.php', 'c.date_commande', '', '&socid=' . $socid, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans('DeliveryDate'), 'orderstoinvoice.php', 'c.date_livraison', '', '&socid=' . $socid, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre($langs->trans('Status'), '', '', '', '', 'align="right"'); + print_liste_field_titre($langs->trans('GenerateBill'), '', '', '', '', 'align="center"'); + print ''; + + // Lignes des champs de filtre + print ''; + print ''; + print ''; + print ''; + // print ''; + + // DATE DELIVERY + print ''; + + // SEARCH BUTTON + print ''; + + print ''; + print ''; + + print ''; + $var = True; + $generic_commande = new CommandeFournisseur($db); + + while ( $i < $num ) { + $objp = $db->fetch_object($resql); + $var = ! $var; + print ''; + print ''; + + print ''; + + // Order date + print ''; + + // Delivery date + print ''; + + // Statut + print ''; + + // Checkbox + print ''; + + print ''; + + $total = $total + $objp->price; + $subtotal = $subtotal + $objp->price; + $i ++; + } + print '
'; + // REF + print ''; + print ''; + print ''; + print ''; + + // DATE ORDER + print ''; + print $period; + print ''; + print $periodely; + print ''; + print ''; + + // ALL/NONE + print ''; + if ($conf->use_javascript_ajax) + print '' . $langs->trans("All") . ' / ' . $langs->trans("None") . ''; + print '
'; + + $generic_commande->id = $objp->rowid; + $generic_commande->ref = $objp->ref; + + print ''; + print ''; + + print '
'; + print $generic_commande->getNomUrl(1, $objp->fk_statut); + print ''; + $filename = dol_sanitizeFileName($objp->ref); + $filedir = $conf->fournisseur->commande->dir_output . '/' . dol_sanitizeFileName($objp->ref); + $urlsource = $_SERVER['PHP_SELF'] . '?id=' . $objp->rowid; + print $formfile->getDocumentsLink($generic_commande->element, $filename, $filedir); + print '
'; + print '
' . $objp->ref_supplier . ''; + print dol_print_date($db->jdate($objp->date_commande), 'day'); + print ''; + print dol_print_date($db->jdate($objp->date_livraison), 'day'); + print '' . $generic_commande->LibStatut($objp->fk_statut, 5) . ''; + print ''; + print '
'; + + /* + * Boutons actions + */ + print '
'; + print '
'; + print ''; + print ''; + print '
'; + // print ''.$langs->trans("GoBack").''; + print ''; + print '
'; + print ''; + $db->free($resql); + } else { + print dol_print_error($db); + } +} + +dol_htmloutput_mesg($mesg, $mesgs); + +llxFooter(); +$db->close(); diff --git a/htdocs/fourn/commande/tpl/index.html b/htdocs/fourn/commande/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php index fc1942e0f61..3a9d8f5bebe 100644 --- a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php @@ -45,7 +45,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > - trans("ShowOrder"),"order").' '.$object->ref; ?> + trans("ShowOrder"),"order").' '.$object->ref; ?> date,'day'); ?> rights->fournisseur->commande->lire) { diff --git a/htdocs/fourn/contact.php b/htdocs/fourn/contact.php index 70748c8bd57..acdac3ab9a1 100644 --- a/htdocs/fourn/contact.php +++ b/htdocs/fourn/contact.php @@ -94,13 +94,13 @@ if ($result) $num = $db->num_rows($result); $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); - print_barre_liste($title." (".$langs->trans("Suppliers").")",$page, "contact.php", "",$sortfield,$sortorder,"",$num); + print_barre_liste($title." (".$langs->trans("Suppliers").")",$page, $_SERVER["PHP_SELF"], "",$sortfield,$sortorder,"",$num); print ''; print ''; - print_liste_field_titre($langs->trans("Lastname"),"contact.php","p.name", $begin, "", "", $sortfield,$sortorder); - print_liste_field_titre($langs->trans("Firstname"),"contact.php","p.firstname", $begin, "", "", $sortfield,$sortorder); - print_liste_field_titre($langs->trans("Company"),"contact.php","s.nom", $begin, "", "", $sortfield,$sortorder); + print_liste_field_titre($langs->trans("Lastname"),$_SERVER["PHP_SELF"],"p.name", $begin, "", "", $sortfield,$sortorder); + print_liste_field_titre($langs->trans("Firstname"),$_SERVER["PHP_SELF"],"p.firstname", $begin, "", "", $sortfield,$sortorder); + print_liste_field_titre($langs->trans("Company"),$_SERVER["PHP_SELF"],"s.nom", $begin, "", "", $sortfield,$sortorder); print ''; print ''; print "\n"; @@ -114,9 +114,9 @@ if ($result) print ""; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; diff --git a/htdocs/fourn/facture/fiche.php b/htdocs/fourn/facture/card.php similarity index 86% rename from htdocs/fourn/facture/fiche.php rename to htdocs/fourn/facture/card.php index 98522e21342..38a0f79a6ea 100644 --- a/htdocs/fourn/facture/fiche.php +++ b/htdocs/fourn/facture/card.php @@ -7,6 +7,7 @@ * Copyright (C) 2010-2014 Juanjo Menent * Copyright (C) 2013 Philippe Grand * Copyright (C) 2013 Florian Henry + * Copyright (C) 2014 Marcos García * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -23,7 +24,7 @@ */ /** - * \file htdocs/fourn/facture/fiche.php + * \file htdocs/fourn/facture/card.php * \ingroup facture, fournisseur * \brief Page for supplier invoice card (view, edit, validate) */ @@ -52,8 +53,6 @@ $langs->load('companies'); $langs->load('products'); $langs->load('banks'); -$mesg=''; -$errors=array(); $id = (GETPOST('facid','int') ? GETPOST('facid','int') : GETPOST('id','int')); $action = GETPOST("action"); $confirm = GETPOST("confirm"); @@ -70,9 +69,13 @@ if (! empty($user->societe_id)) $socid=$user->societe_id; $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array -$hookmanager->initHooks(array('invoicesuppliercard')); +$hookmanager->initHooks(array('invoicesuppliercard','globalcard')); $object=new FactureFournisseur($db); +$extrafields = new ExtraFields($db); + +// fetch optionals attributes and labels +$extralabels=$extrafields->fetch_name_optionals_label($object->table_element); // Load object if ($id > 0 || ! empty($ref)) @@ -87,17 +90,21 @@ $permissionnote=$user->rights->fournisseur->facture->creer; // Used by the inclu * Actions */ +$parameters=array('socid'=>$socid); +$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes') { - if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) - { - $mesg='
'.$langs->trans("NoCloneOptionsSpecified").'
'; - } - else - { +// if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"])) +// { +// $mesg='
'.$langs->trans("NoCloneOptionsSpecified").'
'; +// } +// else +// { $result=$object->createFromClone($id); if ($result > 0) { @@ -107,10 +114,10 @@ if ($action == 'confirm_clone' && $confirm == 'yes') else { $langs->load("errors"); - $mesg='
'.$langs->trans($object->error).'
'; + setEventMessage($langs->trans($object->error), 'errors'); $action=''; } - } +// } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->fournisseur->facture->valider) @@ -137,7 +144,7 @@ elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->fourni if (! $idwarehouse || $idwarehouse == -1) { $error++; - $errors[]=$langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")); + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse")), 'errors'); $action=''; } } @@ -165,7 +172,7 @@ elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fourn } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } @@ -180,7 +187,7 @@ elseif ($action == 'confirm_delete_line' && $confirm == 'yes' && $user->rights-> } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ $action=''; } @@ -215,6 +222,10 @@ else if ($action == 'setmode' && $user->rights->fournisseur->commande->creer) $result = $object->setPaymentMethods(GETPOST('mode_reglement_id','int')); } +// bank account +else if ($action == 'setbankaccount' && $user->rights->fournisseur->facture->creer) { + $result=$object->setBankAccount(GETPOST('fk_account', 'int')); +} // Set label elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) @@ -254,7 +265,9 @@ elseif ($action == 'deletepaiement' && $user->rights->fournisseur->facture->cree $paiementfourn = new PaiementFourn($db); $result=$paiementfourn->fetch(GETPOST('paiement_id')); if ($result > 0) $result=$paiementfourn->delete(); // If fetch ok and found - if ($result < 0) $mesg='
'.$paiementfourn->error.'
'; + if ($result < 0) { + setEventMessage($paiementfourn->error, 'errors'); + } } } @@ -268,29 +281,35 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) if (GETPOST('socid','int')<1) { - $mesg='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('Supplier')), 'errors'); $action='create'; $error++; } if ($datefacture == '') { - $mesg='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')), 'errors'); $action='create'; $_GET['socid']=$_POST['socid']; $error++; } if (! GETPOST('ref_supplier')) { - $mesg='
'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')).'
'; + setEventMessage($langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')), 'errors'); $action='create'; $_GET['socid']=$_POST['socid']; $error++; } - + + // Fill array 'array_options' with data from add form + if (! $error) { $db->begin(); + + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels, $object); + if ($ret < 0) $error ++; $tmpproject = GETPOST('projectid', 'int'); @@ -305,6 +324,7 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) $object->note_private = GETPOST('note_private'); $object->cond_reglement_id = GETPOST('cond_reglement_id'); $object->mode_reglement_id = GETPOST('mode_reglement_id'); + $object->fk_account = GETPOST('fk_account', 'int'); $object->fk_project = ($tmpproject > 0) ? $tmpproject : null; // Auto calculation of date due if not filled by user @@ -456,7 +476,7 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) { $langs->load("errors"); $db->rollback(); - $mesg='
'.$langs->trans($object->error).'
'; + setEventMessage($langs->trans($object->error), 'errors'); $action='create'; $_GET['socid']=$_POST['socid']; } @@ -466,7 +486,7 @@ elseif ($action == 'add' && $user->rights->fournisseur->facture->creer) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; - $result=supplier_invoice_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -630,14 +650,14 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) // Product not selected $error++; $langs->load("errors"); - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("ProductOrService")), 'errors'); } if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); - $mesg='
'.$langs->trans("ErrorQtyTooLowForThisSupplier").'
'; + setEventMessage($langs->trans("ErrorQtyTooLowForThisSupplier"), 'errors'); } } else if( GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='' ) @@ -679,24 +699,25 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) { $db->commit(); - // Define output language - $outputlangs = $langs; - $newlang=GETPOST('lang_id','alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'invoice_supplier'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $result=supplier_invoice_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } - } unset($_POST ['prod_entry_mode']); @@ -731,10 +752,7 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer) else { $db->rollback(); - if (empty($mesg)) - { - $mesg='
'.$object->error.'
'; - } + setEventMessage($object->error, 'errors'); } $action = ''; @@ -763,20 +781,25 @@ elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer) { $object->set_draft($user); - $outputlangs = $langs; - if (! empty($_REQUEST['lang_id'])) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($_REQUEST['lang_id']); - } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { - $result=supplier_invoice_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result <= 0) - { - dol_print_error($db,$result); - exit; - } - } + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) $newlang = GETPOST('lang_id','alpha'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (! empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model=$object->modelpdf; + if (empty($model)) { + $tmp=getListOfModels($db, 'invoice_supplier'); $keys=array_keys($tmp); $model=$keys[0]; + } + $ret = $object->fetch($id); // Reload to get new records + $result=$object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); + if ($result < 0) dol_print_error($db,$result); + } $action=''; } @@ -797,11 +820,18 @@ elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer) } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } } +// Link invoice to order +if (GETPOST('linkedOrder')) { + $object->fetch($id); + $object->fetch_thirdparty(); + $result = $object->add_object_linked('commande', GETPOST('linkedOrder')); +} + // Add file in email form if (GETPOST('addfile')) { @@ -879,12 +909,13 @@ if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_P if (dol_strlen($_POST['subject'])) $subject=$_POST['subject']; else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref; $actiontypecode='AC_SUP_INV'; - $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n"; + $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; if ($message) { - $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n"; - $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n"; - $actionmsg.=$message; + if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject); + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":"); + $actionmsg = dol_concatdesc($actionmsg, $message); } $actionmsg2=$langs->transnoentities('Action'.$actiontypecode); } @@ -947,7 +978,6 @@ if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_P else { $langs->load("other"); - $mesg='
'; if ($mailfile->error) { $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto); @@ -957,7 +987,7 @@ if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_P { $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS'; } - $mesg.='
'; + setEventMessage($mesg, 'errors'); } } } @@ -965,7 +995,7 @@ if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_P else { $langs->load("other"); - $mesg='
'.$langs->trans('ErrorMailRecipientIsEmpty').'
'; + setEventMessage($langs->trans('ErrorMailRecipientIsEmpty'), 'errors'); dol_syslog('Recipient email is empty'); } /* } @@ -979,7 +1009,7 @@ if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_P else { $langs->load("other"); - $mesg='
'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'
'; + setEventMessage($langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")), 'errors'); dol_syslog('Unable to read data from the invoice. The invoice file has perhaps not been generated.'); } @@ -1004,7 +1034,7 @@ elseif ($action == 'builddoc') $outputlangs = new Translate("",$conf); $outputlangs->setDefaultLang($newlang); } - $result=supplier_invoice_pdf_create($db, $object, $object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument($object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -1041,6 +1071,45 @@ elseif ($action == 'remove_file') } } +elseif ($action == 'update_extras') +{ + // Fill array 'array_options' with data from add form + $extralabels=$extrafields->fetch_name_optionals_label($object->table_element); + $ret = $extrafields->setOptionalsFromPost($extralabels,$object); + + if($ret < 0) $error++; + + if (!$error) + { + // Actions on extra fields (by external module or standard code) + // FIXME le hook fait double emploi avec le trigger !! + $hookmanager->initHooks(array('supplierinvoicedao')); + $parameters=array('id'=>$object->id); + + $reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks + + if (empty($reshook)) + { + if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used + { + + $result=$object->insertExtraFields(); + + if ($result < 0) + { + $error++; + } + + } + } + else if ($reshook < 0) $error++; + } + else + { + $action = 'edit_extras'; + } +} + if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer) { if ($action == 'addcontact') @@ -1063,11 +1132,11 @@ if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fourniss if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); } else { - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } } @@ -1116,9 +1185,11 @@ llxHeader('','',''); // Mode creation if ($action == 'create') { + $facturestatic = new FactureFournisseur($db); + $extralabels = $extrafields->fetch_name_optionals_label($facturestatic->table_element); + print_fiche_titre($langs->trans('NewBill')); - dol_htmloutput_mesg($mesg); dol_htmloutput_events(); $societe=''; @@ -1145,7 +1216,6 @@ if ($action == 'create') $element = $subelement = 'commande'; } if ($element == 'propal') { - dol_htmloutput_errors('',$errors); $element = 'comm/propal'; $subelement = 'propal'; } if ($element == 'contract') { @@ -1168,6 +1238,7 @@ if ($action == 'create') $soc = $objectsrc->thirdparty; $cond_reglement_id = (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_supplier_id)?$soc->cond_reglement_supplier_id:1)); $mode_reglement_id = (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_supplier_id)?$soc->mode_reglement_supplier_id:0)); + $fk_account = (! empty($objectsrc->fk_account)?$objectsrc->fk_account:(! empty($soc->fk_account)?$soc->fk_account:0)); $remise_percent = (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0)); $remise_absolue = (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0)); $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''; @@ -1182,6 +1253,7 @@ if ($action == 'create') { $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; + $fk_account = $societe->fk_account; $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']); $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datetmp); $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']); @@ -1334,6 +1406,11 @@ if ($action == 'create') print '
'; } + // Bank Account + print ''; + // Public note print ''; print ''; // print ''; print ''; + + if (empty($reshook) && ! empty($extrafields->attribute_label)) + { + print $object->showOptionals($extrafields, 'edit'); + } if (is_object($objectsrc)) { @@ -1372,12 +1454,12 @@ if ($action == 'create') print '"; if ($mysoc->country_code=='ES') { - if ($mysoc->localtax1_assuj=="1") //Localtax1 RE + if ($mysoc->localtax1_assuj=="1" || $object->total_localtax1 != 0) //Localtax1 { print '"; } - if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF + if ($mysoc->localtax2_assuj=="1" || $object->total_localtax2 != 0) //Localtax2 { print '"; } @@ -1462,6 +1544,9 @@ else $societe = new Fournisseur($db); $result=$societe->fetch($object->socid); if ($result < 0) dol_print_error($db); + + // fetch optionals attributes and labels + $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); /* * View card @@ -1471,13 +1556,10 @@ else dol_fiche_head($head, 'card', $titre, 0, 'bill'); - dol_htmloutput_mesg($mesg); - dol_htmloutput_errors('',$errors); - // Confirmation de la suppression d'une ligne produit if ($action == 'confirm_delete_line') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$_GET["lineid"], $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_delete_line', '', 1, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$_GET["lineid"], $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_delete_line', '', 1, 1); } // Clone confirmation @@ -1489,7 +1571,7 @@ else //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1) ); // Paiement incomplet. On demande si motif = escompte ou autre - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1); } // Confirmation de la validation @@ -1545,24 +1627,32 @@ else array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1))); } - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1, 240); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1, 240); } // Confirmation set paid if ($action == 'paid') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); } // Confirmation de la suppression de la facture fournisseur if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); } + if (!$formconfirm) { + $parameters=array('lineid'=>$lineid); + $formconfirm=$hookmanager->executeHooks('formConfirm',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + } + + // Print form confirm + print $formconfirm; + /** * Invoice @@ -1635,19 +1725,12 @@ else */ $nbrows=9; $nbcols=2; if (! empty($conf->projet->enabled)) $nbrows++; - if (! empty($conf->banque->enabled)) $nbcols++; + if (! empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } // Local taxes - if ($mysoc->country_code=='ES') - { - if($mysoc->localtax1_assuj=="1") $nbrows++; - if($societe->localtax2_assuj=="1") $nbrows++; - } - else - { - if ($societe->localtax1_assuj=="1") $nbrows++; - if ($societe->localtax2_assuj=="1") $nbrows++; - } + if ($societe->localtax1_assuj=="1") $nbrows++; + if ($societe->localtax2_assuj=="1") $nbrows++; + print ''; - print '\n"; + print '\n"; print ''; @@ -1787,6 +1870,23 @@ else } print ''; + // Bank Account + print '"; + print ''; + // Status $alreadypaid=$object->getSommePaiement(); print ''; @@ -1806,35 +1906,17 @@ else // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($mysoc->country_code=='ES') + if ($societe->localtax1_assuj=="1") //Localtax1 { - if ($mysoc->localtax1_assuj=="1") //Localtax1 RE - { - print ''; - print ''; - print ''; - } - if ($societe->localtax2_assuj=="1") //Localtax2 IRPF - { - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; } - else - { - if ($societe->localtax1_assuj=="1") //Localtax1 RE - { - print ''; - print ''; - print ''; - } - if ($societe->localtax2_assuj=="1") //Localtax2 IRPF - { - print ''; - print ''; - print ''; - } + if ($societe->localtax2_assuj=="1") //Localtax2 + { + print ''; + print ''; + print ''; } print ''; @@ -1869,9 +1951,9 @@ else print ''; } - // Other options - $parameters=array('colspan' => ' colspan="4"'); - $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook + // Other attributes + $cols = 4; + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; print '
'.$langs->trans("Email").''.$langs->trans("Phone").'
'.img_object($langs->trans("ShowContact"),"contact").' '.$obj->lastname.''.img_object($langs->trans("ShowContact"),"contact").' '.$obj->lastname.''.$obj->firstname.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.img_object($langs->trans("ShowCompany"),"company").' '.$obj->name.''.$obj->email.''.$obj->phone.'
'.$langs->trans('BankAccount').''; + $form->select_comptes($fk_account, 'fk_account', 0, '', 1); + print '
'.$langs->trans('NotePublic').''; @@ -1351,6 +1428,11 @@ if ($action == 'create') print '
'.$langs->trans('TotalVAT').''.price($objectsrc->total_tva)."
'.$langs->transcountry("AmountLT1",$mysoc->country_code).''.price($objectsrc->total_localtax1)."
'.$langs->transcountry("AmountLT2",$mysoc->country_code).''.price($objectsrc->total_localtax2)."
'; $sql = 'SELECT p.datep as dp, p.num_paiement, p.rowid, p.fk_bank,'; @@ -1684,7 +1767,7 @@ else $objp = $db->fetch_object($result); $var=!$var; print '
'.img_object($langs->trans('ShowPayment'),'payment').' '.dol_print_date($db->jdate($objp->dp),'day')."'.img_object($langs->trans('ShowPayment'),'payment').' '.dol_print_date($db->jdate($objp->dp),'day')."'; print $form->form_modes_reglement(null, $objp->paiement_type,'none').' '.$objp->num_paiement; print '
'; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->fournisseur->facture->creer) + print 'id.'">'.img_edit($langs->trans('SetBankAccount'),1).'
'; + print '
'; + if ($action == 'editbankaccount') { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); + } else { + $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); + } + print "
'.$langs->trans('Status').''.$object->getLibStatut(4,$alreadypaid).'
'.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->transcountry("AmountLT1",$societe->country_code).''.price($object->total_localtax1,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->transcountry("AmountLT2",$societe->country_code).''.price($object->total_localtax2,1,$langs,0,-1,-1,$conf->currency).' 
'.$langs->trans('AmountTTC').''.price($object->total_ttc,1,$langs,0,-1,-1,$conf->currency).' 
'; @@ -2160,7 +2242,7 @@ else // Make payments if ($action != 'edit' && $object->statut == 1 && $object->paye == 0 && $user->societe_id == 0) { - print ''.$langs->trans('DoPayment').''; // must use facid because id is for payment id not invoice + print ''.$langs->trans('DoPayment').''; // must use facid because id is for payment id not invoice } // Classify paid @@ -2230,6 +2312,75 @@ else */ $somethingshown=$object->showLinkedObjectBlock(); + $linktoelem=''; + + if (empty($somethingshown) && ! empty($conf->fournisseur->enabled)) + { + $linktoelem.=($linktoelem?'   ':'').'' . $langs->trans('LinkedOrder') . ''; + + print ' + + '; + + print ''; + } + + // Show link to elements + if ($linktoelem) print '
'.$linktoelem; + print '
'; //print ''; //print '
'; @@ -2253,21 +2404,25 @@ else $fileparams = dol_most_recent_file($conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref, preg_quote($ref,'/')); $file=$fileparams['fullname']; + // Define output language + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) + $newlang = $_REQUEST['lang_id']; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + $newlang = $object->client->default_lang; + + if (!empty($newlang)) + { + $outputlangs = new Translate('', $conf); + $outputlangs->setDefaultLang($newlang); + $outputlangs->load('bills'); + } + // Build document if it not exists if (! $file || ! is_readable($file)) { - // Define output language - $outputlangs = $langs; - $newlang=''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && ! empty($_REQUEST['lang_id'])) $newlang=$_REQUEST['lang_id']; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang; - if (! empty($newlang)) - { - $outputlangs = new Translate("",$conf); - $outputlangs->setDefaultLang($newlang); - } - - $result=supplier_invoice_pdf_create($db, $object, GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); + $result = $object->generateDocument(GETPOST('model')?GETPOST('model'):$object->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result <= 0) { dol_print_error($db,$result); @@ -2283,6 +2438,7 @@ else // Cree l'objet formulaire mail include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php'; $formmail = new FormMail($db); + $formmail->param['langsmodels']=(empty($newlang)?$langs->defaultlang:$newlang); $formmail->fromtype = 'user'; $formmail->fromid = $user->id; $formmail->fromname = $user->getFullName($langs); @@ -2293,7 +2449,7 @@ else $formmail->withto=GETPOST("sendto")?GETPOST("sendto"):$liste; $formmail->withtocc=$liste; $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC; - $formmail->withtopic=$langs->trans('SendBillRef','__FACREF__'); + $formmail->withtopic=$outputlangs->trans('SendBillRef','__FACREF__'); $formmail->withfile=2; $formmail->withbody=1; $formmail->withdeliveryreceipt=1; diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php index 25361746869..aaee42e9add 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -1,6 +1,6 @@ - * Copyright (C) 2005-2012 Laurent Destailleur + * Copyright (C) 2005-2014 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * * This program is free software; you can redistribute it and/or modify @@ -69,11 +69,11 @@ if ($action == 'addcontact' && $user->rights->fournisseur->facture->creer) if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'
'; + setEventMessage($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), 'errors'); } else { - $mesg = '
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); } } } @@ -125,7 +125,6 @@ $userstatic=new User($db); /* Mode vue et edition */ /* */ /* *************************************************************************** */ -dol_htmloutput_mesg($mesg); if ($id > 0 || ! empty($ref)) { @@ -156,9 +155,54 @@ if ($id > 0 || ! empty($ref)) // Third party print "".$langs->trans("Supplier").""; print ''.$object->thirdparty->getNomUrl(1,'supplier').''; + + // Type + print ''.$langs->trans('Type').''; + print $object->getLibType(); + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) + { + $facreplaced=new FactureFournisseur($db); + $facreplaced->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + { + $facusing=new FactureFournisseur($db); + $facusing->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')'; + } + + $facidavoir=$object->getListIdAvoirFromInvoice(); + if (count($facidavoir) > 0) + { + print ' ('.$langs->transnoentities("InvoiceHasAvoir"); + $i=0; + foreach($facidavoir as $fid) + { + if ($i==0) print ' '; + else print ','; + $facavoir=new FactureFournisseur($db); + $facavoir->fetch($fid); + print $facavoir->getNomUrl(1); + } + print ')'; + } + if ($facidnext > 0) + { + $facthatreplace=new FactureFournisseur($db); + $facthatreplace->fetch($facidnext); + print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')'; + } + print ''; + + // Label + print ''.$form->editfieldkey("Label",'label',$object->label,$object,0).''; + print $form->editfieldval("Label",'label',$object->label,$object,0); + print ''; + print ""; - print '
'; + dol_fiche_end(); print '
'; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 79c826a85e9..c7219c6e415 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -168,8 +168,12 @@ if ($object->id > 0) print $form->editfieldval("Label",'label',$object->label,$object,0); print ''; + print '
'; + + print ''; + // Nb of files - print ''; + print ''; print ''; diff --git a/htdocs/fourn/facture/impayees.php b/htdocs/fourn/facture/impayees.php index 4b2c61c02a5..83d4b830c5f 100644 --- a/htdocs/fourn/facture/impayees.php +++ b/htdocs/fourn/facture/impayees.php @@ -47,6 +47,31 @@ if ($user->societe_id > 0) $socid = $user->societe_id; } +$sortfield = GETPOST("sortfield",'alpha'); +$sortorder = GETPOST("sortorder",'alpha'); + +$search_ref = GETPOST('search_ref','alpha'); +$search_ref_supplier = GETPOST('search_ref_supplier','alpha'); +$search_company = GETPOST('search_company','alpha'); +$search_amount_no_tax = GETPOST('search_amount_no_tax','alpha'); +$search_amount_all_tax = GETPOST('search_amount_all_tax','alpha'); + +$page = GETPOST("page",'int'); +if ($page == -1) { $page = 0; } +$offset = $conf->liste_limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (! $sortfield) $sortfield="f.date_lim_reglement"; +if (! $sortorder) $sortorder="ASC"; + +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $search_ref_supplier=""; + $search_company=""; + $search_amount_no_tax=""; + $search_amount_all_tax=""; +} /* * View @@ -61,34 +86,9 @@ $title=$langs->trans("BillsSuppliersUnpaid"); $facturestatic=new FactureFournisseur($db); $companystatic=new Societe($db); - -/*************************************************************************** -* * -* Mode Liste * -* * -***************************************************************************/ - -$sortfield = GETPOST("sortfield",'alpha'); -$sortorder = GETPOST("sortorder",'alpha'); - -$search_ref = GETPOST('search_ref','alpha'); -$search_ref_supplier = GETPOST('search_ref_supplier','alpha'); -$search_societe = GETPOST('search_societe','alpha'); -$search_montant_ht = GETPOST('search_montant_ht','int'); -$search_montant_ttc = GETPOST('search_montant_ttc','int'); - - -$page = GETPOST("page",'int'); -if ($page == -1) { $page = 0; } -$offset = $conf->liste_limit * $page; -$pageprev = $page - 1; -$pagenext = $page + 1; -if (! $sortfield) $sortfield="f.date_lim_reglement"; -if (! $sortorder) $sortorder="ASC"; - if ($user->rights->fournisseur->facture->lire) { - $sql = "SELECT s.rowid as socid, s.nom,"; + $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql.= " f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc,"; $sql.= " f.datef as df, f.date_lim_reglement as datelimite, "; $sql.= " f.paye as paye, f.rowid as facid, f.fk_statut"; @@ -117,26 +117,26 @@ if ($user->rights->fournisseur->facture->lire) if ($search_ref) { - $sql .= " AND f.rowid LIKE '%".$search_ref."%'"; + $sql .= " AND f.ref LIKE '%".$search_ref."%'"; } if ($search_ref_supplier) { $sql .= " AND f.ref_supplier LIKE '%".$search_ref_supplier."%'"; } - if ($search_societe) + if ($search_company) { - $sql .= " AND s.nom LIKE '%".$search_societe."%'"; + $sql .= " AND s.nom LIKE '%".$search_company."%'"; } - if ($search_montant_ht) + if ($search_amount_no_tax) { - $sql .= " AND f.total_ht = '".$search_montant_ht."'"; + $sql .= " AND f.total_ht = '".$search_amount_no_tax."'"; } - if ($search_montant_ttc) + if ($search_amount_all_tax) { - $sql .= " AND f.total_ttc = '".$search_montant_ttc."'"; + $sql .= " AND f.total_ttc = '".$search_amount_all_tax."'"; } if (dol_strlen(GETPOST('sf_re')) > 0) @@ -144,7 +144,7 @@ if ($user->rights->fournisseur->facture->lire) $sql .= " AND f.ref_supplier LIKE '%".GETPOST('sf_re')."%'"; } - $sql.= " GROUP BY s.rowid, s.nom, f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc, f.datef, f.date_lim_reglement, f.paye, f.fk_statut, s.rowid, s.nom"; + $sql.= " GROUP BY s.rowid, s.nom, f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc, f.datef, f.date_lim_reglement, f.paye, f.fk_statut"; if (! $user->rights->societe->client->voir && ! $socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.=$db->order($sortfield,$sortorder); if (! in_array("f.ref_supplier",explode(',',$sortfield))) $sql.= ", f.ref_supplier DESC"; @@ -165,15 +165,15 @@ if ($user->rights->fournisseur->facture->lire) if ($search_ref) $param.='&search_ref='.urlencode($search_ref); if ($search_ref_supplier) $param.='&search_ref_supplier='.urlencode($search_ref_supplier); - if ($search_societe) $param.='&search_societe='.urlencode($search_societe); - if ($search_montant_ht) $param.='&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_ttc) $param.='&search_montant_ttc='.urlencode($search_montant_ttc); + if ($search_company) $param.='&search_company='.urlencode($search_company); + if ($search_amount_no_tax) $param.='&search_amount_no_tax='.urlencode($search_amount_no_tax); + if ($search_amount_all_tax) $param.='&search_amount_all_tax='.urlencode($search_amount_all_tax); $param.=($option?"&option=".$option:""); if (! empty($late)) $param.='&late='.urlencode($late); $urlsource=str_replace('&','&',$param); - $titre=($socid?$langs->trans("BillsSuppliersUnpaidForCompany",$soc->nom):$langs->trans("BillsSuppliersUnpaid")); + $titre=($socid?$langs->trans("BillsSuppliersUnpaidForCompany",$soc->name):$langs->trans("BillsSuppliersUnpaid")); if ($option == 'late') $titre.=' ('.$langs->trans("Late").')'; else $titre.=' ('.$langs->trans("All").')'; @@ -209,15 +209,15 @@ if ($user->rights->fournisseur->facture->lire) print ''; print ''; print ''; - print "\n"; + print ''; + print "\n"; if ($num > 0) { @@ -241,7 +241,7 @@ if ($user->rights->fournisseur->facture->lire) print $facturestatic->getNomUrl(1); print "\n"; - print '\n"; + print ''; print '\n"; print ''; @@ -258,7 +258,7 @@ if ($user->rights->fournisseur->facture->lire) print ""; print ""; - // Affiche statut de la facture + // Show invoice status print ''; diff --git a/htdocs/fourn/facture/index.html b/htdocs/fourn/facture/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/facture/index.php b/htdocs/fourn/facture/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/fourn/facture/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 673ac3fea6f..357df92a4eb 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -32,6 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (!$user->rights->fournisseur->facture->lire) accessforbidden(); @@ -63,9 +64,28 @@ $pagenext = $page + 1; if (! $sortorder) $sortorder="DESC"; if (! $sortfield) $sortfield="fac.datef,fac.rowid"; -$month = GETPOST('month','int'); -$year = GETPOST('year','int'); +$search_ref = GETPOST("search_ref","int"); +$search_ref_supplier = GETPOST("search_ref_supplier","alpha"); +$search_label = GETPOST("search_label","alpha"); +$search_company = GETPOST("search_company","alpha"); +$search_amount_no_tax = GETPOST("search_amount_no_tax","alpha"); +$search_amount_all_tax = GETPOST("search_amount_all_tax","alpha"); +$month = GETPOST("month","int"); +$year = GETPOST("year","int"); +$filter = GETPOST("filtre"); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test must be present to be compatible with all browsers +{ + $search_ref=""; + $search_ref_supplier=""; + $search_label=""; + $search_company=""; + $search_amount_no_tax=""; + $search_amount_all_tax=""; + $year=""; + $month=""; + $filter=""; +} /* * Actions @@ -92,9 +112,6 @@ if ($mode == 'search') } } - - - /* * View */ @@ -106,11 +123,13 @@ $formfile = new FormFile($db); llxHeader('',$langs->trans("SuppliersInvoices"),'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); -$sql = "SELECT s.rowid as socid, s.nom, "; +$sql = "SELECT s.rowid as socid, s.nom as name, "; $sql.= " fac.rowid as facid, fac.ref, fac.ref_supplier, fac.datef, fac.date_lim_reglement as date_echeance,"; $sql.= " fac.total_ht, fac.total_ttc, fac.paye as paye, fac.fk_statut as fk_statut, fac.libelle"; +if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) $sql.=", p.rowid as project_id, p.ref as project_ref"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as fac"; +if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = fac.fk_projet"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql.= " WHERE fac.entity = ".$conf->entity; $sql.= " AND fac.fk_soc = s.rowid"; @@ -119,9 +138,9 @@ if ($socid) { $sql .= " AND s.rowid = ".$socid; } -if (GETPOST('filtre') && GETPOST('filtre') != -1) // GETPOST('filtre') may be a string +if ($filter && $filter != -1) // GETPOST('filtre') may be a string { - $filtrearr = explode(",", GETPOST('filtre')); + $filtrearr = explode(",", $filter); foreach ($filtrearr as $fil) { $filt = explode(":", $fil); @@ -129,14 +148,14 @@ if (GETPOST('filtre') && GETPOST('filtre') != -1) // GETPOST('filtre') may be a } } -if (GETPOST("search_ref")) +if ($search_ref) { - if (is_numeric(GETPOST("search_ref"))) $sql .= natural_search(array('fac.rowid', 'fac.ref'), GETPOST('search_ref'));// For backward compatibility - else $sql .= natural_search('fac.ref', GETPOST("search_ref")); + if (is_numeric($search_ref)) $sql .= natural_search(array('fac.rowid', 'fac.ref'), $search_ref);// For backward compatibility + else $sql .= natural_search('fac.ref', $search_ref); } -if (GETPOST("search_ref_supplier")) +if (search_ref_supplier) { - $sql .= natural_search('fac.ref_supplier', GETPOST('search_ref_supplier')); + $sql .= natural_search('fac.ref_supplier', $search_ref_supplier); } if ($month > 0) { @@ -149,24 +168,24 @@ else if ($year > 0) { $sql.= " AND fac.datef BETWEEN '".$db->idate(dol_get_first_day($year,1,false))."' AND '".$db->idate(dol_get_last_day($year,12,false))."'"; } -if (GETPOST("search_libelle")) +if ($search_label) { - $sql .= natural_search('fac.libelle', GETPOST('search_libelle')); + $sql .= natural_search('fac.libelle', $search_label); } -if (GETPOST("search_societe")) +if ($search_company) { - $sql .= natural_search('s.nom', GETPOST('search_societe')); + $sql .= natural_search('s.nom', $search_company); } -if (GETPOST("search_montant_ht")) +if ($search_amount_no_tax) { - $sql .= " AND fac.total_ht = '".$db->escape(price2num(GETPOST("search_montant_ht")))."'"; + $sql .= " AND fac.total_ht = '".$db->escape(price2num($search_amount_no_tax))."'"; } -if (GETPOST("search_montant_ttc")) +if ($search_amount_all_tax) { - $sql .= " AND fac.total_ttc = '".$db->escape(price2num(GETPOST("search_montant_ttc")))."'"; + $sql .= " AND fac.total_ttc = '".$db->escape(price2num($search_amount_all_tax))."'"; } $nbtotalofrecords = 0; @@ -192,17 +211,17 @@ if ($resql) } $param='&socid='.$socid; - if ($month) $param.='&month='.urlencode($month); - if ($year) $param.='&year=' .urlencode($year); - if (GETPOST("search_ref")) $param.='&search_ref='.urlencode(GETPOST("search_ref")); - if (GETPOST("search_ref_supplier")) $param.='&search_ref_supplier'.urlencode(GETPOST("search_ref_supplier")); - if (GETPOST("search_libelle")) $param.='&search_libelle='.urlencode(GETPOST("search_libelle")); - if (GETPOST("search_societe")) $param.='&search_societe='.urlencode(GETPOST("search_societe")); - if (GETPOST("search_montant_ht")) $param.='&search_montant_ht='.urlencode(GETPOST("search_montant_ht")); - if (GETPOST("search_montant_ttc")) $param.='&search_montant_ttc='.urlencode(GETPOST("search_montant_ttc")); - if (GETPOST("filtre") && GETPOST('filtre') != -1) $param.='&filtre='.urlencode(GETPOST("filtre")); + if ($month) $param.='&month='.urlencode($month); + if ($year) $param.='&year=' .urlencode($year); + if ($search_ref) $param.='&search_ref='.urlencode($search_ref); + if ($search_ref_supplier) $param.='&search_ref_supplier'.urlencode($search_ref_supplier); + if ($search_label) $param.='&search_label='.urlencode($search_label); + if ($search_company) $param.='&search_company='.urlencode($search_company); + if ($search_amount_no_tax) $param.='&search_amount_no_tax='.urlencode($search_amount_no_tax); + if ($search_amount_all_tax) $param.='&search_amount_all_tax='.urlencode($search_amount_all_tax); + if ($filter && $filter != -1) $param.='&filtre='.urlencode($filter); - print_barre_liste($langs->trans("BillsSuppliers").($socid?" $soc->nom":""),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); + print_barre_liste($langs->trans("BillsSuppliers").($socid?" $soc->name.":""),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num,$nbtotalofrecords); print ''; print '
'.$langs->trans('NbOfAttachedFiles').''.count($filearray).'
'.$langs->trans('NbOfAttachedFiles').''.count($filearray).'
'.$langs->trans('TotalSizeOfAttachedFiles').''.$totalsize.' '.$langs->trans('bytes').'
  '; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; - print '
'.dol_trunc($objp->ref_supplier,12)."'.dol_trunc($objp->ref_supplier,12).''.dol_print_date($db->jdate($objp->df),'day')."'.dol_print_date($db->jdate($objp->datelimite),'day'); @@ -250,7 +250,7 @@ if ($user->rights->fournisseur->facture->lire) print ''; $companystatic->id=$objp->socid; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; print $companystatic->getNomUrl(1,'supplier',32); print '".price($objp->total_ttc)."".price($objp->am)."'; print $facturestatic->LibStatut($objp->paye,$objp->fk_statut,5,$objp->am); print '
'; print ''; @@ -212,19 +231,21 @@ if ($resql) print_liste_field_titre($langs->trans("DateDue"),$_SERVER["PHP_SELF"],"fac.date_lim_reglement","",$param,'align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Label"),$_SERVER["PHP_SELF"],"fac.libelle","",$param,"",$sortfield,$sortorder); print_liste_field_titre($langs->trans("ThirdParty"),$_SERVER["PHP_SELF"],"s.nom","",$param,"",$sortfield,$sortorder); + if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) print_liste_field_titre($langs->trans("Project"),$_SERVER["PHP_SELF"],"p.ref","",$param,'',$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountHT"),$_SERVER["PHP_SELF"],"fac.total_ht","",$param,'align="right"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("AmountTTC"),$_SERVER["PHP_SELF"],"fac.total_ttc","",$param,'align="right"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"fk_statut,paye","",$param,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"fk_statut,paye","",$param,'align="right"',$sortfield,$sortorder); + print ''; print "\n"; // Lignes des champs de filtre print ''; print ''; print ''; print ''; print ''; print ''; print ''; + if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) + { + print ''; + } + print ''; print "\n"; $facturestatic=new FactureFournisseur($db); $supplierstatic=new Fournisseur($db); + $projectstatic=new Project($db); $var=true; $total=0; @@ -279,8 +309,17 @@ if ($resql) print ''; print ''; + if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) + { + $projectstatic->id=$obj->project_id; + $projectstatic->ref=$obj->project_ref; + print ''; + } print ''; print ''; $total+=$obj->total_ht; @@ -293,6 +332,8 @@ if ($resql) print $facturestatic->LibStatut($obj->paye,$obj->fk_statut,5); print ''; + print ''; + print "\n"; $i++; @@ -301,9 +342,11 @@ if ($resql) // Print total print ''; print ''; + if (! empty($conf->global->PROJECT_SHOW_REF_INTO_LISTS)) print ''; print ''; print ''; print ''; + print ''; print "\n"; } } diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index d5654c9215c..7d68a3c5a95 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -21,8 +21,8 @@ /** * \file htdocs/fourn/facture/note.php * \ingroup facture -* \brief Fiche de notes sur une facture fournisseur -*/ + * \brief Fiche de notes sur une facture fournisseur + */ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; @@ -137,7 +137,7 @@ if ($object->id > 0) // Label print ''; + print ''; print "
 
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; @@ -235,23 +256,32 @@ if ($resql) print ' '; - print ''; + print ''; print ''; - print ''; + print ''; + print ''; + print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''; - print ''; - $liststatus=array('paye:0'=>$langs->trans("Unpayed"), 'paye:1'=>$langs->trans("Payed")); - print $form->selectarray('filtre', $liststatus, GETPOST('filtre'), 1); - print ''; + $liststatus=array('paye:0'=>$langs->trans("Unpaid"), 'paye:1'=>$langs->trans("Paid")); + print $form->selectarray('filtre', $liststatus, $filter, 1); + print ''; + print ''; + print ''; print '
'.dol_trunc($obj->libelle,36).''; $supplierstatic->id=$obj->socid; - $supplierstatic->nom=$obj->nom; + $supplierstatic->name=$obj->name; print $supplierstatic->getNomUrl(1,'',12); + print ''; + if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); + print ''.price($obj->total_ht).''.price($obj->total_ttc).' 
'.$langs->trans("Total").''.price($total).''.price($total_ttc).'  
'.$form->editfieldkey("Label",'label',$object->label,$object,0).''; print $form->editfieldval("Label",'label',$object->label,$object,0); - print '
"; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index bb84e279ba9..65428cd138e 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -5,6 +5,7 @@ * Copyright (C) 2004 Christophe Combelles * Copyright (C) 2005 Marc Barilley / Ocebo * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -67,10 +68,13 @@ $hookmanager->initHooks(array('paymentsupplier')); $parameters=array('socid'=>$socid); $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + /* * Actions */ + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes')) { $error = 0; @@ -212,8 +216,8 @@ if ($action == 'confirm_paiement' && $confirm == 'yes') else $invoiceid=$facid; } } - if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/fourn/facture/fiche.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/fourn/paiement/fiche.php?id='.$paiement_id; + if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid; + else $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id; header('Location: '.$loc); exit; } @@ -245,7 +249,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $datefacture=dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $dateinvoice=($datefacture==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:''):$datefacture); - $sql = 'SELECT s.nom, s.rowid as socid,'; + $sql = 'SELECT s.nom as name, s.rowid as socid,'; $sql.= ' f.rowid, f.ref, f.ref_supplier, f.amount, f.total_ttc as total'; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f'; @@ -270,14 +274,14 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; // Ref - print '\n"; // Ref supplier print '\n"; // Third party - print ''; + print ''; // Expected to pay print ''; // Status diff --git a/htdocs/fourn/paiement/index.html b/htdocs/fourn/paiement/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/paiement/index.php b/htdocs/fourn/paiement/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/fourn/paiement/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/fourn/product/categorie.php b/htdocs/fourn/product/categorie.php index ad46210ed3b..448cf19e61e 100644 --- a/htdocs/fourn/product/categorie.php +++ b/htdocs/fourn/product/categorie.php @@ -52,14 +52,14 @@ if ($_GET["id"]) //on veut supprimer une cat�gorie if ($_REQUEST["cat"]) { - $cat = new Categorie($db,$_REQUEST["cat"]); + $cat = new Categorie($db); $cat->del_product($product); } //on veut ajouter une cat�gorie if (isset($_REQUEST["add_cat"]) && $_REQUEST["add_cat"]>=0) { - $cat = new Categorie($db,$_REQUEST["add_cat"]); + $cat = new Categorie($db); $cat->add_product($product); } @@ -72,7 +72,7 @@ if ($_GET["id"]) $h=0; - $head[$h][0] = DOL_URL_ROOT."/fourn/product/fiche.php?id=".$product->id; + $head[$h][0] = DOL_URL_ROOT."/fourn/product/card.php?id=".$product->id; $head[$h][1] = $langs->trans("Card"); $h++; @@ -95,7 +95,7 @@ if ($_GET["id"]) $head[$h][1] = $langs->trans("Photos"); $h++; - $head[$h][0] = DOL_URL_ROOT."/product/stats/fiche.php?id=".$product->id; + $head[$h][0] = DOL_URL_ROOT."/product/stats/card.php?id=".$product->id; $head[$h][1] = $langs->trans('Statistics'); $h++; diff --git a/htdocs/fourn/product/index.php b/htdocs/fourn/product/index.php index 14f4790f5af..28e84e30f6a 100644 --- a/htdocs/fourn/product/index.php +++ b/htdocs/fourn/product/index.php @@ -43,7 +43,7 @@ print '"; - print "\n"; + print "rowid\">$objp->ref\n"; print ""; print "'."\n"; - $companystatic->nom=$objp->nom; + $companystatic->name=$objp->name; $companystatic->id=$objp->socid; print '"; print "\n"; - print "\n"; + print "\n"; print ''; print '\n"; @@ -149,7 +149,7 @@ if ($socid > 0) print '\n"; // Author - print ''; + print ''; print "\n"; @@ -176,7 +176,7 @@ if ($socid > 0) print '\n"; print ''; + print ''.img_object($langs->trans("ShowPayment"),"payment").' '.$langs->trans("Payment").' '.$objp->rowid.''; print "\n"; print "\n"; print ''; @@ -184,7 +184,7 @@ if ($socid > 0) print '\n"; // Auteur - print ''; + print ''; print ''; diff --git a/htdocs/ftp/admin/ftpclient.php b/htdocs/ftp/admin/ftpclient.php index 1ff142f7be7..1b252c480af 100644 --- a/htdocs/ftp/admin/ftpclient.php +++ b/htdocs/ftp/admin/ftpclient.php @@ -58,18 +58,17 @@ if ($action == 'add' || GETPOST('modify','alpha')) $ftp_server = "FTP_SERVER_" . $entry; //$_POST["numero_entry"]; $error=0; - $mesg=''; if (! GETPOST("$ftp_name",'alpha')) { $error=1; - $mesg.='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Label")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Label")), 'errors'); } if (! GETPOST("$ftp_server",'alpha')) { $error=1; - $mesg.='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Server")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Server")), 'errors'); } if (! $error) @@ -91,7 +90,6 @@ if ($action == 'add' || GETPOST('modify','alpha')) if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) { $db->commit(); - //$mesg='
'.$langs->trans("Success").'
'; header("Location: ".$_SERVER["PHP_SELF"]); exit; } @@ -119,7 +117,6 @@ if (GETPOST('delete','alpha')) if ($result1 && $result2 && $result3 && $result4 && $result5 && $result6) { $db->commit(); - //$mesg='
'.$langs->trans("Success").'
'; header("Location: ".$_SERVER["PHP_SELF"]); exit; } @@ -218,7 +215,7 @@ else $sql.=" WHERE name like 'FTP_SERVER_%'"; $sql.=" ORDER BY name"; - dol_syslog("ftpclient select ftp setup sql=".$sql,LOG_DEBUG); + dol_syslog("ftpclient select ftp setup", LOG_DEBUG); $resql=$db->query($sql); if ($resql) { @@ -301,9 +298,6 @@ else } -dol_htmloutput_mesg($mesg); - - llxFooter(); $db->close(); diff --git a/htdocs/ftp/admin/index.html b/htdocs/ftp/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/ftp/index.php b/htdocs/ftp/index.php index 0c72bcc1b1a..f1a051bcf2a 100644 --- a/htdocs/ftp/index.php +++ b/htdocs/ftp/index.php @@ -100,8 +100,6 @@ if ( $_POST["sendit"] && ! empty($conf->global->MAIN_UPLOAD_DOC)) $resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0); if (is_numeric($resupload) && $resupload > 0) { - //$mesg = '
'.$langs->trans("FileTransferComplete").'
'; - //print_r($_FILES); $result=$ecmdir->changeNbOfFiles('+'); } else { @@ -124,7 +122,7 @@ if ( $_POST["sendit"] && ! empty($conf->global->MAIN_UPLOAD_DOC)) { // Echec transfert (fichier depassant la limite ?) $langs->load("errors"); - $mesg = '
'.$langs->trans("ErrorFailToCreateDir",$upload_dir).'
'; + setEventMessage($langs->trans("ErrorFailToCreateDir",$upload_dir), 'errors'); } } @@ -143,7 +141,8 @@ if ($_POST["action"] == 'add' && $user->rights->ftp->setup) } else { - $mesg='
Error '.$langs->trans($ecmdir->error).'
'; + //TODO: Translate + setEventMessage('Error '.$langs->trans($ecmdir->error)); $_GET["action"] = "create"; } } @@ -175,12 +174,12 @@ if ($_REQUEST['action'] == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes' $result=@ftp_delete($conn_id, $newremotefileiso); if ($result) { - $mesg = '
'.$langs->trans("FileWasRemoved",$file).'
'; + setEventMessage($langs->trans("FileWasRemoved",$file)); } else { dol_syslog("ftp/index.php ftp_delete", LOG_ERR); - $mesg = '
'.$langs->trans("FTPFailedToRemoveFile",$file).'
'; + setEventMessage($langs->trans("FTPFailedToRemoveFile",$file), 'errors'); } //ftp_close($conn_id); Close later @@ -225,12 +224,12 @@ if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("De $result=@ftp_delete($conn_id, $newremotefileiso); if ($result) { - $mesg .= '
'.$langs->trans("FileWasRemoved",$file).'
'; + setEventMessage($langs->trans("FileWasRemoved",$file)); } else { dol_syslog("ftp/index.php ftp_delete", LOG_ERR); - $mesg .= '
'.$langs->trans("FTPFailedToRemoveFile",$file).'
'; + setEventMessage($langs->trans("FTPFailedToRemoveFile",$file), 'errors'); } //ftp_close($conn_id); Close later @@ -269,11 +268,11 @@ if ($_REQUEST['action'] == 'confirm_deletesection' && $_REQUEST['confirm'] == 'y $result=@ftp_rmdir($conn_id, $newremotefileiso); if ($result) { - $mesg = '
'.$langs->trans("DirWasRemoved",$file).'
'; + setEventMessage($langs->trans("DirWasRemoved",$file)); } else { - $mesg = '
'.$langs->trans("FTPFailedToRemoveDir",$file).'
'; + setEventMessage($langs->trans("FTPFailedToRemoveDir",$file), 'errors'); } //ftp_close($conn_id); Close later @@ -340,7 +339,8 @@ if ($_REQUEST['action'] == 'download') } else { - $mesg='
Failed to get file '.$remotefile.'
'; + //TODO: Translate + setEventMessage('Failed to get file '.$remotefile, 'errors'); } } @@ -444,9 +444,6 @@ else print '
'; print "
\n"; - if ($mesg) { print $mesg."
"; } - - print ''; print ''; print ''; @@ -596,9 +593,6 @@ else print "
'.$langs->trans('Payment').'
'.$langs->trans('Company').''; $supplierstatic->id=$obj->socid; - $supplierstatic->name=$obj->nom; + $supplierstatic->name=$obj->name; print $supplierstatic->getNomUrl(1,'supplier'); print '
'.$langs->trans('Date').''; @@ -328,9 +332,19 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie { $i = 0; print '
'; - print $langs->trans('Invoices').'
'; - print ''; + + if(!empty($conf->global->FAC_AUTO_FILLJS)){ + //Add js for AutoFill + print "\n".''."\n"; + } + print '
'; print ''; print ''; print ''; @@ -370,8 +384,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print ''; print '\n"; + print "\n"; $total+=$objp->total_ht; $total_ttc+=$objp->total_ttc; $totalrecu+=$objp->am; @@ -442,9 +458,18 @@ if (empty($action)) $search_paymenttype=GETPOST('search_paymenttype'); $search_amount=GETPOST('search_amount'); $search_company=GETPOST('search_company'); + + if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers + { + $search_ref=""; + $search_account=""; + $search_paymenttype=""; + $search_amount=""; + $search_company=""; + } $sql = 'SELECT p.rowid as pid, p.datep as dp, p.amount as pamount, p.num_paiement,'; - $sql.= ' s.rowid as socid, s.nom,'; + $sql.= ' s.rowid as socid, s.nom as name,'; $sql.= ' c.libelle as paiement_type,'; $sql.= ' ba.rowid as bid, ba.label,'; if (!$user->rights->societe->client->voir) $sql .= ' sc.fk_soc, sc.fk_user,'; @@ -478,7 +503,7 @@ if (empty($action)) } if (! empty($search_amount)) { - $sql .= " AND p.amount=".price2num($search_amount); + $sql .= " AND p.amount='".price2num($search_amount)."'"; } if (! empty($search_company)) { @@ -499,33 +524,31 @@ if (empty($action)) $paramlist=''; $paramlist.=(! empty($search_ref)?"&search_ref=".$search_ref:""); $paramlist.=(! empty($search_company)?"&search_company=".$search_company:""); - $paramlist.=(! empty($search_amount)?"&search_amount=".$search_amount:""); + $paramlist.=(! empty($search_amount)?"&search_amount='".$search_amount:""); - print_barre_liste($langs->trans('SupplierPayments'), $page, 'paiement.php',$paramlist,$sortfield,$sortorder,'',$num); - - if ($mesg) dol_htmloutput_mesg($mesg); - if ($errmsg) dol_htmloutput_errors($errmsg); + print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER["PHP_SELF"],$paramlist,$sortfield,$sortorder,'',$num); print ''; print '
'.$langs->trans('Ref').''.$langs->trans('RefSupplier').''.price($objp->total_ttc - $objp->am).''; $namef = 'amount_'.$objp->facid; + if(!empty($conf->global->FAC_AUTO_FILLJS)) + print img_picto("Auto fill",'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($objp->total_ttc - $objp->am)."'"); print ''; - print "
'; print ''; - print_liste_field_titre($langs->trans('RefPayment'),'paiement.php','p.rowid','',$paramlist,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Date'),'paiement.php','dp','',$paramlist,'align="center"',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('ThirdParty'),'paiement.php','s.nom','',$paramlist,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Type'),'paiement.php','c.libelle','',$paramlist,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Account'),'paiement.php','ba.label','',$paramlist,'',$sortfield,$sortorder); - print_liste_field_titre($langs->trans('Amount'),'paiement.php','f.amount','',$paramlist,'align="right"',$sortfield,$sortorder); - //print_liste_field_titre($langs->trans('Invoice'),'paiement.php','ref_supplier','',$paramlist,'',$sortfield,$sortorder); - print "\n"; + print_liste_field_titre($langs->trans('RefPayment'),$_SERVER["PHP_SELF"],'p.rowid','',$paramlist,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Date'),$_SERVER["PHP_SELF"],'dp','',$paramlist,'align="center"',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('ThirdParty'),$_SERVER["PHP_SELF"],'s.nom','',$paramlist,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Type'),$_SERVER["PHP_SELF"],'c.libelle','',$paramlist,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Account'),$_SERVER["PHP_SELF"],'ba.label','',$paramlist,'',$sortfield,$sortorder); + print_liste_field_titre($langs->trans('Amount'),$_SERVER["PHP_SELF"],'p.amount','',$paramlist,'align="right"',$sortfield,$sortorder); + //print_liste_field_titre($langs->trans('Invoice'),$_SERVER["PHP_SELF"],'ref_supplier','',$paramlist,'',$sortfield,$sortorder); + print ''; + print "\n"; // Lines for filters fields print ''; print ''; print ''; print ''; print ''; print ''; + print ''; + print ''; print "\n"; while ($i < min($num,$limit)) @@ -546,13 +571,13 @@ if (empty($action)) print ''; // Ref payment - print ''; + print ''; // Date print '\n"; print ''; @@ -571,7 +596,8 @@ if (empty($action)) print '';*/ - + + print ''; print ''; $i++; } diff --git a/htdocs/fourn/facture/tpl/index.html b/htdocs/fourn/facture/tpl/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php index c10fea8bb8a..a6d9164a91c 100644 --- a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php @@ -32,6 +32,7 @@ echo '
'; if ($num > 1) print_titre($langs->trans("RelatedBills")); else print_titre($langs->trans("RelatedBill")); ?> +
 
'; - print ''; + print ''; print ' '; - print ''; + print ''; print ''; $form->select_types_paiements($search_paymenttype,'search_paymenttype','',2,1,1); @@ -534,9 +557,11 @@ if (empty($action)) $form->select_comptes($search_account,'search_account',0,'',1); print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print '
'.img_object($langs->trans('ShowPayment'),'payment').' '.$objp->pid.''.img_object($langs->trans('ShowPayment'),'payment').' '.$objp->pid.''.dol_print_date($db->jdate($objp->dp),'day')."'; - if ($objp->socid) print ''.img_object($langs->trans('ShowCompany'),'company').' '.dol_trunc($objp->nom,32).''; + if ($objp->socid) print ''.img_object($langs->trans('ShowCompany'),'company').' '.dol_trunc($objp->name,32).''; else print ' '; print ''; print $invoicesupplierstatic->getNomUrl(1); print ' 
@@ -46,7 +47,7 @@ foreach($linkedObjectBlock as $object) $var=!$var; ?> > + trans("ShowBill"),"bill").' '.$object->ref; ?>"; print ''; print ''; - print ''; + print ''; print "\n"; $i++; @@ -106,8 +106,8 @@ if (! empty($conf->fournisseur->enabled)) { $langs->load("orders"); - $sql = "SELECT cf.rowid, cf.ref, cf.total_ttc"; - $sql.= ", s.nom, s.rowid as socid"; + $sql = "SELECT cf.rowid, cf.ref, cf.total_ttc,"; + $sql.= " s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; @@ -141,7 +141,7 @@ if (! empty($conf->fournisseur->enabled)) print ''; print ''; @@ -164,7 +164,7 @@ if (! empty($conf->fournisseur->enabled)) if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) { $sql = "SELECT ff.ref_supplier, ff.rowid, ff.total_ttc, ff.type"; - $sql.= ", s.nom, s.rowid as socid"; + $sql.= ", s.nom as name, s.rowid as socid"; $sql.= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql.= ", ".MAIN_DB_PREFIX."societe as s"; if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; @@ -199,7 +199,7 @@ if (! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture- print ''; print ''; @@ -233,7 +233,7 @@ print '
'; * List last modified supliers */ $max=10; -$sql = "SELECT s.rowid as socid, s.nom, s.town, s.datec, s.tms, s.prefix_comm, s.code_fournisseur, s.code_compta_fournisseur"; +$sql = "SELECT s.rowid as socid, s.nom as name, s.town, s.datec, s.tms, s.prefix_comm, s.code_fournisseur, s.code_compta_fournisseur"; $sql.= ", st.libelle as stcomm"; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st"; @@ -266,8 +266,8 @@ if ($resql) $var=!$var; print "
"; - print '\n"; + print '\n"; print ''; print ''; print "\n"; diff --git a/htdocs/fourn/liste.php b/htdocs/fourn/list.php similarity index 73% rename from htdocs/fourn/liste.php rename to htdocs/fourn/list.php index 81837feb41f..b0d7caf8695 100644 --- a/htdocs/fourn/liste.php +++ b/htdocs/fourn/list.php @@ -20,7 +20,7 @@ */ /** - * \file htdocs/fourn/liste.php + * \file htdocs/fourn/list.php * \ingroup fournisseur * \brief Home page of supplier area */ @@ -32,15 +32,15 @@ $langs->load("suppliers"); $langs->load("orders"); $langs->load("companies"); -$socname = GETPOST("socname"); -$search_nom = GETPOST("search_nom"); -$search_zipcode = GETPOST("search_zipcode"); -$search_town = GETPOST("search_town"); -$search_code_fournisseur = GETPOST("search_code_fournisseur"); -$search_compta_fournisseur = GETPOST("search_compta_fournisseur"); -$search_datec = GETPOST("search_datec"); -$search_categ = GETPOST('search_categ','int'); -$catid = GETPOST("catid",'int'); +$socname = GETPOST("socname"); +$search_name = GETPOST("search_name"); +$search_zipcode = GETPOST("search_zipcode"); +$search_town = GETPOST("search_town"); +$search_supplier_code = GETPOST("search_supplier_code"); +$search_supplier_accounting = GETPOST("search_supplier_accounting"); +$search_datec = GETPOST("search_datec"); +$search_categ = GETPOST('search_categ','int'); +$catid = GETPOST("catid",'int'); // Security check $socid = GETPOST('socid','int'); @@ -60,12 +60,26 @@ if (! $sortfield) $sortfield="nom"; // Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('supplierlist')); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $socname=""; + $search_name=""; + $search_zipcode=""; + $search_town=""; + $search_supplier_code=""; + $search_supplier_accounting=""; + $search_datec=""; + $search_categ=""; + $catid=""; +} + /* * Actions */ $parameters=array(); $reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); /* @@ -78,7 +92,7 @@ $thirdpartystatic=new Societe($db); $help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('',$langs->trans("ThirdParty"),$help_url); -$sql = "SELECT s.rowid as socid, s.nom, s.zip, s.town, s.datec, st.libelle as stcomm, s.prefix_comm, s.status as status, "; +$sql = "SELECT s.rowid as socid, s.nom as name, s.zip, s.town, s.datec, st.libelle as stcomm, s.prefix_comm, s.status as status, "; $sql.= "code_fournisseur, code_compta_fournisseur"; if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; $sql.= " FROM ".MAIN_DB_PREFIX."societe as s"; @@ -94,15 +108,15 @@ if ($socname) { $sortfield = "s.nom"; $sortorder = "ASC"; } -if ($search_nom) { - $sql .= natural_search('s.nom', $search_nom); +if ($search_name) { + $sql .= natural_search('s.nom', $search_name); } if ($search_zipcode) $sql .= " AND s.zip LIKE '".$db->escape($search_zipcode)."%'"; if ($search_town) { $sql .= natural_search('s.town', $search_town); } -if ($search_code_fournisseur) $sql .= " AND s.code_fournisseur LIKE '%".$db->escape($search_code_fournisseur)."%'"; -if ($search_compta_fournisseur) $sql .= " AND s.code_compta_fournisseur LIKE '%".$db->escape($search_compta_fournisseur)."%'"; +if ($search_supplier_code) $sql .= " AND s.code_fournisseur LIKE '%".$db->escape($search_supplier_code)."%'"; +if ($search_supplier_accounting) $sql .= " AND s.code_compta_fournisseur LIKE '%".$db->escape($search_supplier_accounting)."%'"; if ($search_datec) $sql .= " AND s.datec LIKE '%".$db->escape($search_datec)."%'"; if ($catid > 0) $sql.= " AND cf.fk_categorie = ".$catid; if ($catid == -2) $sql.= " AND cf.fk_categorie IS NULL"; @@ -118,14 +132,14 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= $db->order($sortfield,$sortorder); $sql.= $db->plimit($conf->liste_limit+1, $offset); -dol_syslog('fourn/liste.php: sql='.$sql,LOG_DEBUG); +dol_syslog('fourn/list.php:', LOG_DEBUG); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); $i = 0; - $param = "&search_nom=".$search_nom."&search_code_fournisseur=".$search_code_fournisseur."&search_zipcode=".$search_zipcode."&search_town=".$search_town; + $param = "&search_name=".$search_name."&search_supplier_code=".$search_supplier_code."&search_zipcode=".$search_zipcode."&search_town=".$search_town; if ($search_categ != '') $param.='&search_categ='.$search_categ; print_barre_liste($langs->trans("ListOfSuppliers"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords); @@ -165,26 +179,28 @@ if ($resql) print ''; - print ''; + print ''; - print ''; + print ''; - print ''; + print ''; print ''; print ''; print ''; - print ''; - + print '\n"; + $parameters=array(); $formconfirm=$hookmanager->executeHooks('printFieldListOption',$parameters); // Note that $action and $object may have been modified by hook @@ -198,7 +214,7 @@ if ($resql) $var=!$var; $thirdpartystatic->id=$obj->socid; - $thirdpartystatic->nom=$obj->nom; + $thirdpartystatic->name=$obj->name; $thirdpartystatic->status=$obj->status; print ""; diff --git a/htdocs/fourn/paiement/fiche.php b/htdocs/fourn/paiement/card.php similarity index 90% rename from htdocs/fourn/paiement/fiche.php rename to htdocs/fourn/paiement/card.php index 0a2f3ad207f..179e810d182 100644 --- a/htdocs/fourn/paiement/fiche.php +++ b/htdocs/fourn/paiement/card.php @@ -19,10 +19,10 @@ */ /** - * \file htdocs/fourn/paiement/fiche.php + * \file htdocs/fourn/paiement/card.php * \ingroup facture, fournisseur * \brief Tab to show a payment of a supplier invoice - * \remarks Fichier presque identique a compta/paiement/fiche.php + * \remarks Fichier presque identique a compta/paiement/card.php */ require '../../main.inc.php'; @@ -36,8 +36,6 @@ $langs->load('banks'); $langs->load('companies'); $langs->load("suppliers"); -$mesg=''; - $id = GETPOST('id','int'); $action = GETPOST('action','alpha'); $confirm = GETPOST('confirm','alpha'); @@ -61,7 +59,7 @@ if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); $db->rollback(); } } @@ -80,7 +78,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); $db->rollback(); } } @@ -98,7 +96,7 @@ if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->fournisse } else { - $mesg='
'.$object->error.'
'; + setEventMessage($object->error, 'errors'); $db->rollback(); } } @@ -109,11 +107,11 @@ if ($action == 'setnum_paiement' && ! empty($_POST['num_paiement'])) $res = $object->update_num($_POST['num_paiement']); if ($res === 0) { - $mesg = '
'.$langs->trans('PaymentNumberUpdateSucceeded').'
'; + setEventMessage($langs->trans('PaymentNumberUpdateSucceeded')); } else { - $mesg = '
'.$langs->trans('PaymentNumberUpdateFailed').'
'; + setEventMessage($langs->trans('PaymentNumberUpdateFailed'), 'errors'); } } @@ -124,11 +122,11 @@ if ($action == 'setdatep' && ! empty($_POST['datepday'])) $res = $object->update_date($datepaye); if ($res === 0) { - $mesg = '
'.$langs->trans('PaymentDateUpdateSucceeded').'
'; + setEventMessage($langs->trans('PaymentDateUpdateSucceeded')); } else { - $mesg = '
'.$langs->trans('PaymentDateUpdateFailed').'
'; + setEventMessage($langs->trans('PaymentDateUpdateFailed'), 'errors'); } } @@ -230,15 +228,13 @@ if ($result > 0) print '
trans("Ref"); ?>
- trans("ShowBill"),"bill").' '.$object->ref; ?> date,'day'); ?> rights->fournisseur->facture->lire) { diff --git a/htdocs/fourn/index.php b/htdocs/fourn/index.php index bfdf1b1ce45..9da28281779 100644 --- a/htdocs/fourn/index.php +++ b/htdocs/fourn/index.php @@ -86,7 +86,7 @@ if ($resql) print "
'.$langs->trans($commande->statuts[$row[1]]).''.$row[0].''.$commande->LibStatut($row[1],3).''.$commande->LibStatut($row[1],3).'
'; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=0; print $companystatic->getNomUrl(1,'',16); print ''; $companystatic->id=$obj->socid; - $companystatic->nom=$obj->nom; + $companystatic->name=$obj->name; $companystatic->client=0; print $companystatic->getNomUrl(1,'',16); print '
'.img_object($langs->trans("ShowSupplier"),"company").''; - print " socid."\">".$obj->nom."'.img_object($langs->trans("ShowSupplier"),"company").''; + print " socid."\">".$obj->name."'.$obj->code_fournisseur.' '.dol_print_date($db->jdate($obj->tms),'day').'
'; - print ''; + print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; + print ''; + print "
'; - dol_htmloutput_mesg($mesg); - print '
'; /** * Liste des factures */ $allow_delete = 1 ; - $sql = 'SELECT f.rowid, f.ref, f.ref_supplier, f.total_ttc, pf.amount, f.rowid as facid, f.paye, f.fk_statut, s.nom, s.rowid as socid'; + $sql = 'SELECT f.rowid, f.ref, f.ref_supplier, f.total_ttc, pf.amount, f.rowid as facid, f.paye, f.fk_statut, s.nom as name, s.rowid as socid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf,'.MAIN_DB_PREFIX.'facture_fourn as f,'.MAIN_DB_PREFIX.'societe as s'; $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid'; $sql .= ' AND pf.fk_paiementfourn = '.$object->id; @@ -272,13 +268,13 @@ if ($result > 0) $var=!$var; print '
'.img_object($langs->trans('ShowBill'),'bill').' '; + print ''.img_object($langs->trans('ShowBill'),'bill').' '; print ($objp->ref?$objp->ref:$objp->rowid); print "'.$objp->ref_supplier."'.img_object($langs->trans('ShowCompany'),'company').' '.$objp->nom.''.img_object($langs->trans('ShowCompany'),'company').' '.$objp->name.''.price($objp->total_ttc).'
'; /* * Zone recherche produit/service */ -print ''; +print ''; print ''; print ''; print "\n"; @@ -81,13 +81,13 @@ print '"; - print ''; + print ''; print ""; } if (! empty($conf->service->enabled)) { print ""; - print ''; + print ''; print ""; } print '
'.$langs->trans("Statistics").'product->enabled)) { print "
'.$langs->trans("Products").''.round($prodser[0]).''.$langs->trans("Products").''.round($prodser[0]).'
'.$langs->trans("Services").''.round($prodser[1]).''.$langs->trans("Services").''.round($prodser[1]).'
'; @@ -125,10 +125,10 @@ if ($resql) $objp = $db->fetch_object($resql); $var=!$var; print "
rowid\">"; + print "rowid\">"; if ($objp->fk_product_type==1) print img_object($langs->trans("ShowService"),"service"); else print img_object($langs->trans("ShowProduct"),"product"); - print " rowid\">$objp->ref $objp->label"; if ($objp->fk_product_type==1) print $langs->trans('ShowService'); diff --git a/htdocs/fourn/product/liste.php b/htdocs/fourn/product/list.php similarity index 91% rename from htdocs/fourn/product/liste.php rename to htdocs/fourn/product/list.php index ffd413cbf2f..afaf4c8e796 100644 --- a/htdocs/fourn/product/liste.php +++ b/htdocs/fourn/product/list.php @@ -21,7 +21,7 @@ */ /** - * \file htdocs/fourn/product/liste.php + * \file htdocs/fourn/product/list.php * \ingroup produit * \brief Page liste des produits ou services */ @@ -88,7 +88,7 @@ if ($fourn_id) $sql = "SELECT p.rowid, p.label, p.ref, p.fk_product_type,"; $sql.= " ppf.fk_soc, ppf.ref_fourn, ppf.price as price, ppf.quantity as qty, ppf.unitprice,"; -$sql.= " s.rowid as socid, s.nom"; +$sql.= " s.rowid as socid, s.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."product as p"; if ($catid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = p.rowid"; $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as ppf ON p.rowid = ppf.fk_product"; @@ -108,7 +108,7 @@ if ($sref) } if ($snom) { - $sql .= natural_search('p.label', $snom); + $sql .= natural_search('s.nom', $snom); } if($catid) { @@ -118,10 +118,17 @@ if ($fourn_id > 0) { $sql .= " AND ppf.fk_soc = ".$fourn_id; } +// Count total nb of records without orderby and limit +$nbtotalofrecords = 0; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) +{ + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); +} $sql .= " ORDER BY ".$sortfield." ".$sortorder; $sql .= $db->plimit($limit + 1, $offset); -dol_syslog("fourn/product/liste.php: sql=".$sql); +dol_syslog("fourn/product/list.php:", LOG_DEBUG); $resql = $db->query($sql); if ($resql) { @@ -132,25 +139,25 @@ if ($resql) if ($num == 1 && (GETPOST("mode") == 'search')) { $objp = $db->fetch_object($resql); - header("Location: ".DOL_URL_ROOT."/product/fiche.php?id=".$objp->rowid); + header("Location: ".DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); exit; } - if (! empty($supplier->id)) $texte = $langs->trans("ListOfSupplierProductForSupplier",$supplier->nom); + if (! empty($supplier->id)) $texte = $langs->trans("ListOfSupplierProductForSupplier",$supplier->name); else $texte = $langs->trans("List"); llxHeader("","",$texte); $param="&tobuy=".$tobuy."&sref=".$sref."&snom=".$snom."&fourn_id=".$fourn_id.(isset($type)?"&type=".$type:"").(empty($sRefSupplier)?"":"&srefsupplier=".$sRefSupplier); - print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder,'',$num); + print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords); if (isset($catid)) { print "
"; - $c = new Categorie($db, $catid); - $ways = $c->print_all_ways(' > ','fourn/product/liste.php'); + $c = new Categorie($db); + $ways = $c->print_all_ways(' > ','fourn/product/list.php'); print " > ".$ways[0]."
\n"; print "

"; } @@ -212,7 +219,7 @@ if ($resql) print '
'.$objp->label.''; if ($companystatic->id > 0) print $companystatic->getNomUrl(1,'supplier'); diff --git a/htdocs/fourn/product/photos.php b/htdocs/fourn/product/photos.php index d60a4aab4d0..f20c360de6c 100644 --- a/htdocs/fourn/product/photos.php +++ b/htdocs/fourn/product/photos.php @@ -65,7 +65,7 @@ if ($id) $h=0; - $head[$h][0] = DOL_URL_ROOT."/fourn/product/fiche.php?id=".$object->id; + $head[$h][0] = DOL_URL_ROOT."/fourn/product/card.php?id=".$object->id; $head[$h][1] = $langs->trans("Card"); $h++; @@ -89,7 +89,7 @@ if ($id) $h++; } - $head[$h][0] = DOL_URL_ROOT."/product/fiche.php?id=".$object->id; + $head[$h][0] = DOL_URL_ROOT."/product/card.php?id=".$object->id; $head[$h][1] = $langs->trans("CommercialCard"); $h++; diff --git a/htdocs/fourn/recap-fourn.php b/htdocs/fourn/recap-fourn.php index 3d3fd9f2dcb..c09f52b8407 100644 --- a/htdocs/fourn/recap-fourn.php +++ b/htdocs/fourn/recap-fourn.php @@ -139,7 +139,7 @@ if ($socid > 0) print "
".dol_print_date($fac->date)."id\">".img_object($langs->trans("ShowBill"),"bill")." ".$fac->ref."id\">".img_object($langs->trans("ShowBill"),"bill")." ".$fac->ref."'.$fac->getLibStatut(2,$totalpaye).''.price($fac->total_ttc)."'.price($solde)."'.img_object($langs->trans("ShowUser"),'user').' '.$objf->login.''.img_object($langs->trans("ShowUser"),'user').' '.$objf->login.'
'.dol_print_date($db->jdate($objp->dp))."'; print '      '; // Decalage - print ''.img_object($langs->trans("ShowPayment"),"payment").' '.$langs->trans("Payment").' '.$objp->rowid.'  '.price($objp->amount).''.price($solde)."'.img_object($langs->trans("ShowUser"),'user').' '.$objp->login.''.img_object($langs->trans("ShowUser"),'user').' '.$objp->login.'
"; - - if (! $ok && $mesg) print $mesg; - // Actions /* if ($user->rights->ftp->write && ! empty($section)) diff --git a/htdocs/holiday/admin/holiday.php b/htdocs/holiday/admin/holiday.php index 2b265711fa1..1986ae1cdf7 100644 --- a/htdocs/holiday/admin/holiday.php +++ b/htdocs/holiday/admin/holiday.php @@ -59,7 +59,6 @@ $cp = new Holiday($db); // Contrôle du formulaire if ($action == "add") { - $message = ''; $error = 0; // Option du groupe de validation @@ -142,9 +141,9 @@ if ($action == "add") if ($error) { - $message = '
'.$langs->trans('ErrorUpdateConfCP').'
'; + setEventMessage($langs->trans('ErrorUpdateConfCP'), 'errors'); } else { - $message = '
'.$langs->trans('UpdateConfCPOK').'
'; + setEventMessage($langs->trans('UpdateConfCPOK')); } // Si première mise à jour, prévenir l'utilisateur de mettre à jour le solde des congés payés @@ -156,12 +155,9 @@ if ($action == "add") if($num < 1) { $cp->createCPusers(); - $message.= '
'.$langs->trans('AddCPforUsers').'
'; + setEventMessage($langs->trans('AddCPforUsers'), 'warnings'); } - dol_htmloutput_mesg($message); - - // Si il s'agit de créer un event } elseif ($action == 'create_event') @@ -173,12 +169,12 @@ elseif ($action == 'create_event') if (! $optName) { - $message='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Name")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Name")), 'errors'); $error++; } if (! $optValue > 0) { - $message='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Value")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Value")), 'errors'); $error++; } @@ -190,17 +186,15 @@ elseif ($action == 'create_event') $result = $cp->createEventCP($user); if($result > 0) { - $message = 'OkCreateEventCP'; + setEventMessage('OkCreateEventCP'); $optName=''; $optValue=''; } else { - $message = '
'.$cp->error.'
'; + setEventMessage($cp->error, 'errors'); } } - - dol_htmloutput_mesg($message); } elseif($action == 'event' && isset($_POST['update_event'])) { @@ -234,15 +228,13 @@ elseif($action == 'event' && isset($_POST['update_event'])) // Mise à jour des congés de l'utilisateur $update = $cp->updateEventCP($eventId,$eventName,$eventValue); if(!$update) { - $message='ErrorUpdateEventCP'; + setEventMessage('ErrorUpdateEventCP', 'errors'); } else { - $message='UpdateEventOkCP'; + setEventMessage('UpdateEventOkCP'); } } else { - $message='ErrorUpdateEventCP'; + setEventMessage('ErrorUpdateEventCP', 'errors'); } - - dol_htmloutput_mesg($message); } elseif($action && isset($_POST['delete_event'])) { @@ -365,15 +357,15 @@ if($cp_events == 1) { print ''."\n"; - foreach($cp->events as $infos_event) { - + foreach($cp->events as $infos_event) + { $var=!$var; print ''."\n"; print ''."\n"; print ' '.$langs->trans('DurationDays').''."\n"; print ''."\n"; - print ''."\n"; + print ''."\n"; print ''; $i++; diff --git a/htdocs/holiday/admin/index.html b/htdocs/holiday/admin/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/holiday/admin/tomergewithholiday.php b/htdocs/holiday/admin/tomergewithholiday.php new file mode 100644 index 00000000000..c301e1ba348 --- /dev/null +++ b/htdocs/holiday/admin/tomergewithholiday.php @@ -0,0 +1,225 @@ + + * Copyright (C) 2011 Dimitri Mouillard + * Copyright (C) 2012 Regis Houssin + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * Page module configuration paid holiday. + * + * \file holiday.php + * \ingroup holiday + * \brief Page module configuration paid holiday. + */ + +require '../../main.inc.php'; +require DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; +require_once DOL_DOCUMENT_ROOT. '/core/class/html.form.class.php'; +require_once DOL_DOCUMENT_ROOT. '/user/class/user.class.php'; +require_once DOL_DOCUMENT_ROOT. '/user/class/usergroup.class.php'; + +// Si pas administrateur +if (! $user->admin) accessforbidden(); + + +/* + * View + */ + +// Vérification si module activé +if (empty($conf->holiday->enabled)) print $langs->trans('NotActiveModCP'); + +llxheader('',$langs->trans('TitleAdminCP')); + +print_fiche_titre($langs->trans('MenuCPTypes')); + +echo '
'; + +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; + +$types = $db->query( + "SELECT * + FROM llx_congespayes_types + WHERE deleteAt IS NULL + ORDER BY label" +); + +while($type = $db->fetch_array($types)) +{ + echo' + + + + + + + + + + + + + '; +} + +echo ' + + + + + + +
' . $langs->trans('TypeLabel') . '' . $langs->trans('TypeDescription') . '' . $langs->trans('TypeAffect') . '' . $langs->trans('TypeDelay') . '' . $langs->trans('nbCongesDeductedCPMini') . '' . $langs->trans('nbCongesEveryMonthCPMini') . '
'.$type['label'].''.($type['description']?$type['description']:'N/A').' + '.($type['affect']?$langs->trans('TypeAffectYes'):$langs->trans('TypeAffectNo')).' + '.$type['delay'].''.$type['nbCongesDeducted'].''.$type['nbCongesEveryMonth'].' + + +
+ +
+ +'; + +echo '
'; + +llxFooter(); + +$db->close(); diff --git a/htdocs/holiday/fiche.php b/htdocs/holiday/card.php similarity index 88% rename from htdocs/holiday/fiche.php rename to htdocs/holiday/card.php index d66d1c8cfbd..bbffe26cf9c 100644 --- a/htdocs/holiday/fiche.php +++ b/htdocs/holiday/card.php @@ -3,6 +3,7 @@ * Copyright (C) 2012-2013 Laurent Destailleur * Copyright (C) 2012 Regis Houssin * Copyright (C) 2013 Juanjo Menent + * Copyright (C) 2014 Ferran Marcet * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -19,7 +20,7 @@ */ /** - * \file htdocs/holiday/fiche.php + * \file htdocs/holiday/card.php * \ingroup holiday * \brief Form and file creation of paid holiday. */ @@ -83,21 +84,21 @@ if ($action == 'create') // Si pas de date de début if (empty($date_debut)) { - header('Location: fiche.php?action=request&error=nodatedebut'); + header('Location: card.php?action=request&error=nodatedebut'); exit; } // Si pas de date de fin if (empty($date_fin)) { - header('Location: fiche.php?action=request&error=nodatefin'); + header('Location: card.php?action=request&error=nodatefin'); exit; } // Si date de début après la date de fin if ($date_debut > $date_fin) { - header('Location: fiche.php?action=request&error=datefin'); + header('Location: card.php?action=request&error=datefin'); exit; } @@ -105,22 +106,22 @@ if ($action == 'create') $verifCP = $cp->verifDateHolidayCP($userID, $date_debut, $date_fin, $halfday); if (! $verifCP) { - header('Location: fiche.php?action=request&error=alreadyCP'); + header('Location: card.php?action=request&error=alreadyCP'); exit; } // Si aucun jours ouvrés dans la demande $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if($nbopenedday < 1) + if($nbopenedday < 0.5) { - header('Location: fiche.php?action=request&error=DureeHoliday'); + header('Location: card.php?action=request&error=DureeHoliday'); exit; } // Si pas de validateur choisi if ($valideur < 1) { - header('Location: fiche.php?action=request&error=Valideur'); + header('Location: card.php?action=request&error=Valideur'); exit; } @@ -136,13 +137,13 @@ if ($action == 'create') // Si pas d'erreur SQL on redirige vers la fiche de la demande if ($verif > 0) { - header('Location: fiche.php?id='.$verif); + header('Location: card.php?id='.$verif); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?action=request&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?action=request&error=SQL_Create&msg='.$cp->error); exit; } } @@ -164,7 +165,7 @@ if ($action == 'update') // Si pas le droit de modifier une demande if (! $user->rights->holiday->write) { - header('Location: fiche.php?action=request&error=CantUpdate'); + header('Location: card.php?action=request&error=CantUpdate'); exit; } @@ -184,33 +185,33 @@ if ($action == 'update') // Si pas de date de début if (empty($_POST['date_debut_'])) { - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=nodatedebut'); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=nodatedebut'); exit; } // Si pas de date de fin if (empty($_POST['date_fin_'])) { - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=nodatefin'); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=nodatefin'); exit; } // Si date de début après la date de fin if ($date_debut > $date_fin) { - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=datefin'); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=datefin'); exit; } // Si pas de valideur choisi if ($valideur < 1) { - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=Valideur'); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=Valideur'); exit; } // Si pas de jours ouvrés dans la demande $nbopenedday=num_open_day($date_debut_gmt, $date_fin_gmt, 0, 1, $halfday); - if ($nbopenedday < 1) + if ($nbopenedday < 0.5) { - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=DureeHoliday'); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=DureeHoliday'); exit; } @@ -224,18 +225,18 @@ if ($action == 'update') $verif = $cp->update($user->id); if ($verif > 0) { - header('Location: fiche.php?id='.$_POST['holiday_id']); + header('Location: card.php?id='.$_POST['holiday_id']); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?id='.$_POST['holiday_id'].'&action=edit&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?id='.$_POST['holiday_id'].'&action=edit&error=SQL_Create&msg='.$cp->error); exit; } } } else { - header('Location: fiche.php?id='.$_POST['holiday_id']); + header('Location: card.php?id='.$_POST['holiday_id']); exit; } } @@ -304,7 +305,7 @@ if ($action == 'confirm_send') if (!$emailTo) { - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } @@ -353,7 +354,7 @@ if ($action == 'confirm_send') $message.= "\n"; $message.= "- ".$langs->transnoentitiesnoconv("Name")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; $message.= "- ".$langs->transnoentitiesnoconv("Period")." : ".dol_print_date($cp->date_debut,'day')." ".$langs->transnoentitiesnoconv("To")." ".dol_print_date($cp->date_fin,'day')."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/fiche.php?id=".$cp->rowid."\n\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$cp->rowid."\n\n"; $message.= "\n"; $mail = new CMailFile($subject,$emailTo,$emailFrom,$message); @@ -363,16 +364,16 @@ if ($action == 'confirm_send') if (!$result) { - header('Location: fiche.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); + header('Location: card.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); exit; } - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); exit; } } @@ -398,7 +399,7 @@ if($action == 'confirm_valid') if ($verif > 0) { // Calculcate number of days consummed - $nbopenedday=num_open_day($cp->date_debut_gmt,$cp->date_fin_gmt,0,1); + $nbopenedday=num_open_day($cp->date_debut_gmt,$cp->date_fin_gmt,0,1,$cp->halfday); $soldeActuel = $cp->getCpforUser($cp->fk_user); $newSolde = $soldeActuel - ($nbopenedday * $cp->getConfCP('nbHolidayDeducted')); @@ -416,7 +417,7 @@ if($action == 'confirm_valid') if (!$emailTo) { - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } @@ -438,7 +439,7 @@ if($action == 'confirm_valid') $message.= "- ".$langs->transnoentitiesnoconv("ValidatedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/fiche.php?id=".$cp->rowid."\n\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$cp->rowid."\n\n"; $message.= "\n"; $mail = new CMailFile($subject,$emailTo,$emailFrom,$message); @@ -447,15 +448,15 @@ if($action == 'confirm_valid') $result=$mail->sendfile(); if(!$result) { - header('Location: fiche.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); + header('Location: card.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); exit; } - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); exit; } @@ -490,7 +491,7 @@ if ($action == 'confirm_refuse') if (!$emailTo) { - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } @@ -513,7 +514,7 @@ if ($action == 'confirm_refuse') $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/fiche.php?id=".$cp->rowid."\n\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$cp->rowid."\n\n"; $message.= "\n"; $mail = new CMailFile($subject,$emailTo,$emailFrom,$message); @@ -522,22 +523,22 @@ if ($action == 'confirm_refuse') $result=$mail->sendfile(); if(!$result) { - header('Location: fiche.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); + header('Location: card.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); exit; } - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); exit; } } } else { - header('Location: fiche.php?id='.$_GET['id'].'&error=NoMotifRefuse'); + header('Location: card.php?id='.$_GET['id'].'&error=NoMotifRefuse'); exit; } } @@ -599,7 +600,7 @@ if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') if (!$emailTo) { - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } @@ -621,7 +622,7 @@ if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') $message.= $langs->transnoentities("HolidaysCanceledBody", dol_print_date($cp->date_debut,'day'), dol_print_date($cp->date_fin,'day'))."\n"; $message.= "- ".$langs->transnoentitiesnoconv("ModifiedBy")." : ".dolGetFirstLastname($expediteur->firstname, $expediteur->lastname)."\n"; - $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/fiche.php?id=".$cp->rowid."\n\n"; + $message.= "- ".$langs->transnoentitiesnoconv("Link")." : ".$dolibarr_main_url_root."/holiday/card.php?id=".$cp->rowid."\n\n"; $message.= "\n"; $mail = new CMailFile($subject,$emailTo,$emailFrom,$message); @@ -631,17 +632,17 @@ if ($action == 'confirm_cancel' && GETPOST('confirm') == 'yes') if(!$result) { - header('Location: fiche.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); + header('Location: card.php?id='.$_GET['id'].'&error=mail&error_content='.$mail->error); exit; } - header('Location: fiche.php?id='.$_GET['id']); + header('Location: card.php?id='.$_GET['id']); exit; } else { // Sinon on affiche le formulaire de demande avec le message d'erreur SQL - header('Location: fiche.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); + header('Location: card.php?id='.$_GET['id'].'&error=SQL_Create&msg='.$cp->error); exit; } @@ -704,7 +705,7 @@ if (empty($id) || $action == 'add' || $action == 'request' || $action == 'create break; } - dol_htmloutput_mesg('',$errors,'error'); + setEventMessage($errors, 'errors'); } @@ -761,7 +762,7 @@ if (empty($id) || $action == 'add' || $action == 'request' || $action == 'create } else print $form->select_users(GETPOST('userid')?GETPOST('userid'):$user->id,'userid',0,'',0); $nb_holiday = $cp->getCPforUser($user->id) / $cp->getConfCP('nbHolidayDeducted'); - print '   '.$langs->trans('SoldeCPUser', round($nb_holiday,0)).''; + print '   '.$langs->trans('SoldeCPUser', round($nb_holiday,2)).''; print ''; print ''; print ''; @@ -889,7 +890,7 @@ else break; } - dol_htmloutput_mesg('',$errors,'error'); + setEventMessage($errors, 'errors'); } // On vérifie si l'utilisateur à le droit de lire cette demande @@ -899,33 +900,33 @@ else { if($user->rights->holiday->delete) { - print $form->formconfirm("fiche.php?id=".$id,$langs->trans("TitleDeleteCP"),$langs->trans("ConfirmDeleteCP"),"confirm_delete", '', 0, 1); + print $form->formconfirm("card.php?id=".$id,$langs->trans("TitleDeleteCP"),$langs->trans("ConfirmDeleteCP"),"confirm_delete", '', 0, 1); } } // Si envoi en validation if ($action == 'sendToValidate' && $cp->statut == 1 && $user->id == $cp->fk_user) { - print $form->formconfirm("fiche.php?id=".$id,$langs->trans("TitleToValidCP"),$langs->trans("ConfirmToValidCP"),"confirm_send", '', 1, 1); + print $form->formconfirm("card.php?id=".$id,$langs->trans("TitleToValidCP"),$langs->trans("ConfirmToValidCP"),"confirm_send", '', 1, 1); } // Si validation de la demande if ($action == 'valid') { - print $form->formconfirm("fiche.php?id=".$id,$langs->trans("TitleValidCP"),$langs->trans("ConfirmValidCP"),"confirm_valid", '', 1, 1); + print $form->formconfirm("card.php?id=".$id,$langs->trans("TitleValidCP"),$langs->trans("ConfirmValidCP"),"confirm_valid", '', 1, 1); } // Si refus de la demande if ($action == 'refuse') { $array_input = array(array('type'=>"text",'label'=> $langs->trans('DetailRefusCP'),'name'=>"detail_refuse",'size'=>"50",'value'=>"")); - print $form->formconfirm("fiche.php?id=".$id."&action=confirm_refuse", $langs->trans("TitleRefuseCP"), $langs->trans('ConfirmRefuseCP'), "confirm_refuse", $array_input, 1, 0); + print $form->formconfirm("card.php?id=".$id."&action=confirm_refuse", $langs->trans("TitleRefuseCP"), $langs->trans('ConfirmRefuseCP'), "confirm_refuse", $array_input, 1, 0); } // Si annulation de la demande if ($action == 'cancel') { - print $form->formconfirm("fiche.php?id=".$id,$langs->trans("TitleCancelCP"),$langs->trans("ConfirmCancelCP"),"confirm_cancel", '', 1, 1); + print $form->formconfirm("card.php?id=".$id,$langs->trans("TitleCancelCP"),$langs->trans("ConfirmCancelCP"),"confirm_cancel", '', 1, 1); } $head=holiday_prepare_head($cp); @@ -1069,7 +1070,7 @@ else // Liste des utiliseurs du groupes choisi dans la config $idGroupValid = $cp->getConfCP('userGroup'); - $validator = new UserGroup($db,$idGroupValid); + $validator = new UserGroup($db); $valideur = $validator->listUsersForGroup('',1); print ''; @@ -1124,26 +1125,26 @@ else // Boutons d'actions if ($canedit && $cp->statut == 1) { - print '
'.$langs->trans("EditCP").''; + print ''.$langs->trans("EditCP").''; } if ($canedit && $cp->statut == 1) { - print ''.$langs->trans("Validate").''; + print ''.$langs->trans("Validate").''; } if ($user->rights->holiday->delete && $cp->statut == 1) // If draft { - print ''.$langs->trans("DeleteCP").''; + print ''.$langs->trans("DeleteCP").''; } if ($user->id == $cp->fk_validator && $cp->statut == 2) { - print ''.$langs->trans("Approve").''; - print ''.$langs->trans("ActionRefuseCP").''; + print ''.$langs->trans("Approve").''; + print ''.$langs->trans("ActionRefuseCP").''; } if (($user->id == $cp->fk_validator || $user->id == $cp->fk_user) && ($cp->statut == 2 || $cp->statut == 3)) // Status validated or approved { - if (($cp->date_debut > dol_now()) || $user->admin) print ''.$langs->trans("ActionCancelCP").''; + if (($cp->date_debut > dol_now()) || $user->admin) print ''.$langs->trans("ActionCancelCP").''; else print ''.$langs->trans("ActionCancelCP").''; } diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index 5398b398e6c..2ecf8edfce3 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -137,7 +137,7 @@ class Holiday extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -200,7 +200,7 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."holiday as cp"; $sql.= " WHERE cp.rowid = ".$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -238,7 +238,6 @@ class Holiday extends CommonObject else { $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR); return -1; } } @@ -294,7 +293,7 @@ class Holiday extends CommonObject $sql.= $order; } - dol_syslog(get_class($this)."::fetchByUser sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchByUser", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -351,7 +350,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchByUser ".$this->error, LOG_ERR); return -1; } } @@ -405,7 +403,7 @@ class Holiday extends CommonObject $sql.= $order; } - dol_syslog(get_class($this)."::fetchAll sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchAll", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -461,7 +459,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchAll ".$this->error, LOG_ERR); return -1; } } @@ -473,7 +470,7 @@ class Holiday extends CommonObject * @param int $notrigger 0=launch triggers after, 1=disable triggers * @return int <0 if KO, >0 if OK */ - function update($user=0, $notrigger=0) + function update($user=null, $notrigger=0) { global $conf, $langs; $error=0; @@ -544,7 +541,7 @@ class Holiday extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -591,7 +588,7 @@ class Holiday extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -662,7 +659,7 @@ class Holiday extends CommonObject $result=''; - $lien = ''; + $lien = ''; $lienfin=''; $picto='holiday'; @@ -783,11 +780,11 @@ class Holiday extends CommonObject $groupe = $objet->value; // On liste les groupes de Dolibarr - $sql = "SELECT u.rowid, u.nom"; + $sql = "SELECT u.rowid, u.nom as name"; $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as u"; $sql.= " ORDER BY u.rowid"; - dol_syslog(get_class($this)."::selectUserGroup sql=".$sql,LOG_DEBUG); + dol_syslog(get_class($this)."::selectUserGroup", LOG_DEBUG); $result = $this->db->query($sql); // Si pas d'erreur SQL @@ -801,9 +798,9 @@ class Holiday extends CommonObject while ($obj = $this->db->fetch_object($result)) { if($groupe==$obj->rowid) { - $selectGroup.= ''."\n"; + $selectGroup.= ''."\n"; } else { - $selectGroup.= ''."\n"; + $selectGroup.= ''."\n"; } } $selectGroup.= ''."\n"; @@ -813,7 +810,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::selectUserGroup ".$this->error, LOG_ERR); return -1; } @@ -824,7 +820,7 @@ class Holiday extends CommonObject /** * Met à jour une option du module Holiday Payés * - * @param string $name nom du paramètre de configuration + * @param string $name name du paramètre de configuration * @param string $value vrai si mise à jour OK sinon faux * @return boolean ok or ko */ @@ -834,7 +830,7 @@ class Holiday extends CommonObject $sql.= " value = '".$value."'"; $sql.= " WHERE name = '".$name."'"; - dol_syslog(get_class($this).'::updateConfCP name='.$name.' sql='.$sql); + dol_syslog(get_class($this).'::updateConfCP name='.$name.'', LOG_DEBUG); $result = $this->db->query($sql); if($result) { return true; @@ -846,7 +842,7 @@ class Holiday extends CommonObject /** * Retourne la valeur d'un paramètre de configuration * - * @param string $name nom du paramètre de configuration + * @param string $name name du paramètre de configuration * @return string retourne la valeur du paramètre */ function getConfCP($name) @@ -855,7 +851,7 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."holiday_config"; $sql.= " WHERE name = '".$name."'"; - dol_syslog(get_class($this).'::getConfCP name='.$name.' sql='.$sql); + dol_syslog(get_class($this).'::getConfCP name='.$name.'', LOG_DEBUG); $result = $this->db->query($sql); // Si pas d'erreur @@ -869,7 +865,6 @@ class Holiday extends CommonObject // Erreur SQL $this->error=$this->db->lasterror(); - dol_syslog(get_class($this)."::getConfCP ".$this->error, LOG_ERR); return -1; } } @@ -903,7 +898,7 @@ class Holiday extends CommonObject $sql.= " value = '".dol_print_date($now,'%Y%m%d%H%M%S')."'"; $sql.= " WHERE name = 'lastUpdate'"; - dol_syslog(get_class($this).'::updateSoldeCP sql='.$sql); + dol_syslog(get_class($this).'::updateSoldeCP', LOG_DEBUG); $result = $this->db->query($sql); // On ajoute x jours à chaque utilisateurs @@ -929,7 +924,7 @@ class Holiday extends CommonObject $sql2 = "UPDATE ".MAIN_DB_PREFIX."holiday_users SET"; $sql2.= " nb_holiday = nb_holiday + ".$nb_holiday; - dol_syslog(get_class($this).'::updateSoldeCP sql='.$sql2); + dol_syslog(get_class($this).'::updateSoldeCP', LOG_DEBUG); $result= $this->db->query($sql2); if ($result) return 1; @@ -948,7 +943,7 @@ class Holiday extends CommonObject $sql.= " nb_holiday = ".$nbHoliday; $sql.= " WHERE fk_user = '".$userID."'"; - dol_syslog(get_class($this).'::updateSoldeCP sql='.$sql); + dol_syslog(get_class($this).'::updateSoldeCP', LOG_DEBUG); $result = $this->db->query($sql); if ($result) return 1; @@ -960,7 +955,7 @@ class Holiday extends CommonObject /** * Retourne un checked si vrai * - * @param string $name nom du paramètre de configuration + * @param string $name name du paramètre de configuration * @return string retourne checked si > 0 */ function getCheckOption($name) { @@ -1046,11 +1041,12 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users"; $sql.= " WHERE fk_user = '".$user_id."'"; - dol_syslog(get_class($this).'::getCPforUser sql='.$sql); + dol_syslog(get_class($this).'::getCPforUser', LOG_DEBUG); $result = $this->db->query($sql); if($result) { $obj = $this->db->fetch_object($result); - return number_format($obj->nb_holiday,2); + //return number_format($obj->nb_holiday,2); + return $obj->nb_holiday; } else { return '0'; } @@ -1077,7 +1073,7 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE statut > 0"; - dol_syslog(get_class($this)."::fetchUsers sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1107,7 +1103,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchUsers ".$this->error, LOG_ERR); return -1; } @@ -1115,7 +1110,7 @@ class Holiday extends CommonObject $sql = "SELECT u.fk_user"; $sql.= " FROM ".MAIN_DB_PREFIX."holiday_users as u"; - dol_syslog(get_class($this)."::fetchUsers sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1145,7 +1140,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchUsers ".$this->error, LOG_ERR); return -1; } } @@ -1159,7 +1153,7 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE statut > 0"; - dol_syslog(get_class($this)."::fetchUsers sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1187,7 +1181,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchUsers ".$this->error, LOG_ERR); return -1; } @@ -1199,7 +1192,7 @@ class Holiday extends CommonObject $sql.= " ".MAIN_DB_PREFIX."user as u"; $sql.= " WHERE cpu.fk_user = u.rowid"; - dol_syslog(get_class($this)."::fetchUsers sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchUsers", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1227,7 +1220,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchUsers ".$this->error, LOG_ERR); return -1; } } @@ -1382,7 +1374,7 @@ class Holiday extends CommonObject $sql.= " FROM ".MAIN_DB_PREFIX."holiday_events as cpe"; - dol_syslog(get_class($this)."::fetchEventsCP sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchEventsCP", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1416,7 +1408,6 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchEventsCP ".$this->error, LOG_ERR); return -1; } } @@ -1447,7 +1438,7 @@ class Holiday extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::createEventCP sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::createEventCP", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -1640,7 +1631,7 @@ class Holiday extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::addLogCP sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::addLogCP", LOG_DEBUG); $resql=$this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); @@ -1703,7 +1694,7 @@ class Holiday extends CommonObject $sql.= " ".$order; } - dol_syslog(get_class($this)."::fetchLog sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetchLog", LOG_DEBUG); $resql=$this->db->query($sql); // Si pas d'erreur SQL @@ -1741,11 +1732,34 @@ class Holiday extends CommonObject { // Erreur SQL $this->error="Error ".$this->db->lasterror(); - dol_syslog(get_class($this)."::fetchLog ".$this->error, LOG_ERR); return -1; } } + + /** + * Tous les types + * + * @return boolean Return array with list of types + */ + function getTypes() + { + $result = $this->db->query("SELECT rowid, type, affect FROM " . MAIN_DB_PREFIX . "holiday_types"); + $num = $this->db->num_rows($result); + if ($num) + { + while ($obj = $this->db->fetch_object($result)) + { + $types[] = array('rowid'=> $obj->rowid, 'type'=> $obj->type, 'affect'=>$obj->affect); + } + + return $types; + } + + return array(); + } + + /** * Initialise an instance with random values. * Used to build previews or test instances. diff --git a/htdocs/holiday/class/index.html b/htdocs/holiday/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/holiday/define_holiday.php b/htdocs/holiday/define_holiday.php index c432d37007b..fa3f745de81 100644 --- a/htdocs/holiday/define_holiday.php +++ b/htdocs/holiday/define_holiday.php @@ -84,13 +84,10 @@ if ($action == 'update' && isset($_POST['update_cp'])) $sql = "UPDATE ".MAIN_DB_PREFIX."holiday_config SET"; $sql.= " value = '".dol_print_date($now,'%Y%m%d%H%M%S')."'"; $sql.= " WHERE name = 'lastUpdate' and value IS NULL"; // Add value IS NULL to be sure to update only at init. - dol_syslog('define_holiday update lastUpdate entry sql='.$sql); + dol_syslog('define_holiday update lastUpdate entry', LOG_DEBUG); $result = $db->query($sql); - $mesg='
'.$langs->trans('UpdateConfCPOK').'
'; - - dol_htmloutput_mesg($mesg); - + setEventMessage($langs->trans('UpdateConfCPOK')); } elseif($action == 'add_event') { @@ -108,7 +105,7 @@ elseif($action == 'add_event') if ($error) { - $message = '
'.$langs->trans('ErrorAddEventToUserCP').'
'; + setEventMessage($langs->trans('ErrorAddEventToUserCP'), 'errors'); } else { @@ -121,10 +118,8 @@ elseif($action == 'add_event') $holiday->updateSoldeCP($userCP,$new_holiday); - $message = $langs->trans('AddEventToUserOkCP'); + setEventMessage($langs->trans('AddEventToUserOkCP')); } - - dol_htmloutput_mesg($message); } $langs->load('users'); @@ -149,17 +144,14 @@ if($cp_events == 1) print '
'; } -dol_fiche_head(); - print '
'."\n"; print ''; print ''; print ""; -print ''; -print ''; +print ''; print ''; print ''; -print ''; +print ''; print ''; foreach($listUsers as $users) @@ -168,7 +160,6 @@ foreach($listUsers as $users) $var=!$var; print ''; - print ''; print '
'.$langs->trans('ID').''.$langs->trans('Employee').''.$langs->trans('Employee').''.$langs->trans('Available').''.$langs->trans('Note').''.$langs->trans('UpdateButtonCP').'
'.$users['rowid'].''; $userstatic->id=$users['rowid']; $userstatic->lastname=$users['name']; @@ -188,10 +179,6 @@ foreach($listUsers as $users) print '
'; print '
'; -dol_fiche_end(); - - llxFooter(); $db->close(); - diff --git a/htdocs/holiday/img/add.png b/htdocs/holiday/img/add.png new file mode 100755 index 00000000000..d15cb50d835 Binary files /dev/null and b/htdocs/holiday/img/add.png differ diff --git a/htdocs/holiday/img/delete.png b/htdocs/holiday/img/delete.png new file mode 100755 index 00000000000..e22ed6f43fc Binary files /dev/null and b/htdocs/holiday/img/delete.png differ diff --git a/htdocs/holiday/img/edit.png b/htdocs/holiday/img/edit.png new file mode 100755 index 00000000000..c74571fde8a Binary files /dev/null and b/htdocs/holiday/img/edit.png differ diff --git a/htdocs/holiday/img/index.html b/htdocs/holiday/img/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/holiday/index.php b/htdocs/holiday/index.php index 26f413a4e43..86c4eca49eb 100644 --- a/htdocs/holiday/index.php +++ b/htdocs/holiday/index.php @@ -64,6 +64,19 @@ $search_employe = GETPOST('search_employe'); $search_valideur = GETPOST('search_valideur'); $search_statut = GETPOST('select_statut'); +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter")) // Both test are required to be compatible with all browsers +{ + $search_ref=""; + $month_create=""; + $year_create=""; + $month_start=""; + $year_start=""; + $month_end=""; + $year_end=""; + $search_employe=""; + $search_valideur=""; + $search_statut=""; +} /* * Actions @@ -71,8 +84,6 @@ $search_statut = GETPOST('select_statut'); // None - - /* * View */ @@ -257,7 +268,7 @@ print_liste_field_titre($langs->trans("Employe"),$_SERVER["PHP_SELF"],"cp.fk_use print_liste_field_titre($langs->trans("ValidatorCP"),$_SERVER["PHP_SELF"],"cp.fk_validator","",'','',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateDebCP"),$_SERVER["PHP_SELF"],"cp.date_debut","",'','align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("DateFinCP"),$_SERVER["PHP_SELF"],"cp.date_fin","",'','align="center"',$sortfield,$sortorder); -print_liste_field_titre($langs->trans("Duration")); +print_liste_field_titre($langs->trans("Duration"),$_SERVER["PHP_SELF"],'','','','align="center"',$sortfield,$sortorder); print_liste_field_titre($langs->trans("Status"),$_SERVER["PHP_SELF"],"cp.statut","",'','align="center"',$sortfield,$sortorder); print ''; print "\n"; @@ -323,7 +334,8 @@ print ''; // ACTION print ''; -print ''; +print ''; +print ''; print ''; print "\n"; @@ -386,7 +398,7 @@ if ($user_id == $user->id) { print '
'; print ''; } diff --git a/htdocs/holiday/tomergewithdefine_holiday.php b/htdocs/holiday/tomergewithdefine_holiday.php new file mode 100644 index 00000000000..4bf904528a0 --- /dev/null +++ b/htdocs/holiday/tomergewithdefine_holiday.php @@ -0,0 +1,125 @@ + + * Copyright (C) 2011 Dimitri Mouillard + * + * 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 2 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, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/** + * \file define_congespayes.php + * \ingroup congespayes + * \brief File that defines the balance of paid leave of users. + * \version $Id: define_congespayes.php,v 1.00 2011/09/15 11:00:00 dmouillard Exp $ + * \author dmouillard@teclib.com + * \remarks File that defines the balance of paid leave of users. + */ + +require('../main.inc.php'); +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; + +// Protection if external user +if ($user->societe_id > 0) accessforbidden(); + +// If the user does not have perm to read the page +if(!$user->rights->holiday->define_holiday) accessforbidden(); + + +/* + * View + */ + +llxHeader(array(),$langs->trans('CPTitreMenu')); + + +print_fiche_titre($langs->trans('MenuConfCP')); + +$congespayes = new Holidays($db); +$listUsers = $congespayes->fetchUsers(false, true); + +// Si il y a une action de mise à jour +if (isset($_POST['action']) && $_POST['action'] == 'update') { + + $fk_type = $_POST['fk_type']; + + foreach ($_POST['nb_conges'] as $user_id => $compteur) { + if (!empty($compteur)) { + $userValue = str_replace(',', '.', $compteur); + $userValue = number_format($userValue, 2, '.', ''); + } else { + $userValue = '0.00'; + } + $congespayes->updateSoldeCP($user_id,$userValue,$fk_type); + } + + print '
'; + print $langs->trans('UpdateConfCPOK'); + print '
'; + +} + +$var = true; +$i = 0; + +foreach($congespayes->getTypes() as $type) +{ + if($type['affect']==1) + { + print '
'; + + print '

'.$type['label'].'

'; + + print '
' . "\n"; + print ''; + print ''; + + print ''; + print ""; + print ''; + print ''; + print ''; + + foreach ($listUsers as $users) { + $var = !$var; + print ''; + print ''; + print '' . "\n"; + print ''; + + $i++; + } + + echo ""; + print ''; + echo ""; + + print '
' . $langs->trans('Employee') . '' . $langs->trans('Counter') . '
' . $users['name'] . ' ' . $users['firstname'] . ''; + print ''; + print ' jours
'; + print '
'; + + print '
'; + } +} + +// Fin de page +$db->close(); +llxFooter(); diff --git a/htdocs/holiday/view_log.php b/htdocs/holiday/view_log.php index dba8969adca..5f18a524acc 100644 --- a/htdocs/holiday/view_log.php +++ b/htdocs/holiday/view_log.php @@ -26,6 +26,7 @@ require('../main.inc.php'); require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT.'/holiday/common.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; // Protection if external user if ($user->societe_id > 0) accessforbidden(); @@ -33,6 +34,12 @@ if ($user->societe_id > 0) accessforbidden(); // Si l'utilisateur n'a pas le droit de lire cette page if(!$user->rights->holiday->view_log) accessforbidden(); +$year=GETPOST('year'); +if (empty($year)) +{ + $tmpdate=dol_getdate(dol_now()); + $year=$tmpdate['year']; +} /* @@ -41,14 +48,14 @@ if(!$user->rights->holiday->view_log) accessforbidden(); $langs->load('users'); -llxHeader(array(),$langs->trans('CPTitreMenu')); +llxHeader(array(),$langs->trans('CPTitreMenu').' ('.$langs->trans("Year").' '.$year.')'); $cp = new Holiday($db); // Recent changes are more important than old changes -$log_holiday = $cp->fetchLog('ORDER BY cpl.rowid DESC',''); +$log_holiday = $cp->fetchLog('ORDER BY cpl.rowid DESC', " AND date_action BETWEEN '".$db->idate(dol_get_first_day($year,1,1))."' AND '".$db->idate(dol_get_last_day($year,12,1))."'"); // Load $cp->logs -print_fiche_titre($langs->trans('LogCP')); +print_fiche_titre($langs->trans('LogCP'),''.img_previous().' '.$langs->trans("Year").':'.$year.' '.img_next().''); print ''; print ''; diff --git a/htdocs/imports/class/import.class.php b/htdocs/imports/class/import.class.php index b1fa3552d9a..58a1bf3e931 100644 --- a/htdocs/imports/class/import.class.php +++ b/htdocs/imports/class/import.class.php @@ -233,7 +233,7 @@ class Import $sql.= ')'; $sql.= " VALUES (".($user->id > 0 ? $user->id : 0).", '".$this->db->escape($this->model_name)."', '".$this->datatoimport."', '".$this->hexa."')"; - dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql=$this->db->query($sql); if ($resql) { @@ -244,7 +244,6 @@ class Import { $this->error=$this->db->lasterror(); $this->errno=$this->db->lasterrno(); - dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR); $this->db->rollback(); return -1; } @@ -262,7 +261,7 @@ class Import $sql.= ' FROM '.MAIN_DB_PREFIX.'import_model as em'; $sql.= ' WHERE em.rowid = '.$id; - dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); if ($result) { @@ -306,7 +305,7 @@ class Import $this->db->begin(); - dol_syslog(get_class($this)."::delete sql=".$sql); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); } @@ -314,12 +313,10 @@ class Import { if (! $notrigger) { - // Call triggers - include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php'; - $interface=new Interfaces($this->db); - $result=$interface->run_triggers('IMPORT_DELETE',$this,$user,$langs,$conf); - if ($result < 0) { $error++; $this->errors=$interface->errors; } - // End call triggers + // Call trigger + $result=$this->call_trigger('IMPORT_DELETE',$user); + if ($result < 0) $error++; + // End call triggers } } diff --git a/htdocs/imports/class/index.html b/htdocs/imports/class/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/imports/import.php b/htdocs/imports/import.php index f40bcd3e061..125b8dc0285 100644 --- a/htdocs/imports/import.php +++ b/htdocs/imports/import.php @@ -138,11 +138,11 @@ if ($action == 'builddoc') $result=$objimport->build_file($user, GETPOST('model','alpha'), $datatoimport, $array_match_file_to_database); if ($result < 0) { - $mesg='
'.$objimport->error.'
'; + setEventMessage($objimport->error, 'errors'); } else { - $mesg='
'.$langs->trans("FileSuccessfullyBuilt").'
'; + setEventMessage($langs->trans("FileSuccessfullyBuilt")); } } @@ -175,21 +175,23 @@ if ($action == 'add_import_model') $result = $objimport->create($user); if ($result >= 0) { - $mesg='
'.$langs->trans("ImportModelSaved",$objimport->model_name).'
'; + setEventMessage($langs->trans("ImportModelSaved",$objimport->model_name)); } else { $langs->load("errors"); if ($objimport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $mesg='
'.$langs->trans("ErrorImportDuplicateProfil").'
'; + setEventMessage($langs->trans("ErrorImportDuplicateProfil"), 'errors'); + } + else { + setEventMessage($objimport->error, 'errors'); } - else $mesg='
'.$objimport->error.'
'; } } else { - $mesg='
'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("ImportModelName")).'
'; + setEventMessage($langs->trans("ErrorFieldRequired",$langs->transnoentities("ImportModelName")), 'errors'); } } @@ -385,8 +387,6 @@ if ($step == 1 || ! $datatoimport) dol_fiche_end(); - if ($mesg) print $mesg; - } @@ -461,7 +461,6 @@ if ($step == 2 && $datatoimport) dol_fiche_end(); - if ($mesg) print $mesg; } @@ -597,10 +596,7 @@ if ($step == 3 && $datatoimport) print '
'; - dol_fiche_end(); - - if ($mesg) print $mesg; } @@ -1010,9 +1006,6 @@ if ($step == 4 && $datatoimport) print ''."\n"; } - - if ($mesg) print $mesg; - /* * Barre d'action */ @@ -1438,8 +1431,6 @@ if ($step == 5 && $datatoimport) } print '
'; } - - if ($mesg) print $mesg; } @@ -1679,8 +1670,6 @@ if ($step == 6 && $datatoimport) print $langs->trans("FileWasImported",$importid).'
'; print $langs->trans("YouCanUseImportIdToFindRecord",$importid).'
'; print '
'; - - if ($mesg) print $mesg; } diff --git a/htdocs/includes/adodbtime/index.html b/htdocs/includes/adodbtime/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/includes/adodbtime/index.php b/htdocs/includes/adodbtime/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/includes/adodbtime/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/includes/index.html b/htdocs/includes/index.html new file mode 100644 index 00000000000..e69de29bb2d diff --git a/htdocs/includes/index.php b/htdocs/includes/index.php deleted file mode 100644 index 7db0dd9ebf9..00000000000 --- a/htdocs/includes/index.php +++ /dev/null @@ -1 +0,0 @@ -Url not available \ No newline at end of file diff --git a/htdocs/includes/jquery/plugins/multiselect/MIT-LICENSE.txt b/htdocs/includes/jquery/plugins/multiselect/MIT-LICENSE.txt deleted file mode 100644 index 1076f8b4b2b..00000000000 --- a/htdocs/includes/jquery/plugins/multiselect/MIT-LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Michael Aufreiter, http://www.quasipartikel.at - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/htdocs/includes/jquery/plugins/multiselect/css/ui.multiselect.css b/htdocs/includes/jquery/plugins/multiselect/css/ui.multiselect.css deleted file mode 100644 index 7d3a44801d2..00000000000 --- a/htdocs/includes/jquery/plugins/multiselect/css/ui.multiselect.css +++ /dev/null @@ -1,31 +0,0 @@ -/* Multiselect -----------------------------------*/ - -.ui-multiselect { border: solid 1px; font-size: 0.8em; } -.ui-multiselect ul { -moz-user-select: none; } -.ui-multiselect li { margin: 0; padding: 0; cursor: default; line-height: 20px; height: 20px; font-size: 11px; list-style: none; padding-right: 18px; overflow: hidden; } -.ui-multiselect li a { color: #999; text-decoration: none; padding: 0; display: block; float: left; cursor: pointer;} -.ui-multiselect li.ui-draggable-dragging { padding-left: 10px; } - -.ui-multiselect div.selected { position: relative; padding: 0; margin: 0; border: 0; float:left; } -.ui-multiselect ul.selected { position: relative; padding: 0; overflow: auto; overflow-x: hidden; background: #fff; margin: 0; list-style: none; border: 0; position: relative; width: 100%; } - -.ui-multiselect div.available { position: relative; padding: 0; margin: 0; border: 0; float:left; } -.ui-multiselect ul.available { position: relative; padding: 0; overflow: auto; overflow-x: hidden; background: #fff; margin: 0; list-style: none; border: 0; width: 100%; } -.ui-multiselect ul.available li { padding-left: 10px; } - -.ui-multiselect div.right-column { border-left: 1px solid; } - -.ui-multiselect .ui-state-default { border: none; margin-bottom: 1px; position: relative; padding-left: 20px;} -.ui-multiselect .ui-state-hover { border: none; } -.ui-multiselect .ui-widget-header {border: none; font-size: 11px; margin-bottom: 1px;} - -.ui-multiselect .add-all { float: right; padding: 7px;} -.ui-multiselect .remove-all { float: right; padding: 7px;} -.ui-multiselect .search { float: left; padding: 4px;} -.ui-multiselect .count { float: left; padding: 7px;} - -.ui-multiselect li span.ui-icon-arrowthick-2-n-s { position: absolute; left: 2px; } -.ui-multiselect li a.action { position: absolute; right: 2px; top: 2px; } - -.ui-multiselect input.search { height: 14px; padding: 1px; opacity: 0.5; margin: 4px; width: 100px; } \ No newline at end of file diff --git a/htdocs/includes/jquery/plugins/multiselect/js/ui.multiselect.js b/htdocs/includes/jquery/plugins/multiselect/js/ui.multiselect.js deleted file mode 100644 index eb4578fc782..00000000000 --- a/htdocs/includes/jquery/plugins/multiselect/js/ui.multiselect.js +++ /dev/null @@ -1,480 +0,0 @@ -/* - * jQuery UI Multiselect - * - * Authors: - * Michael Aufreiter (quasipartikel.at) - * Yanick Rochon (yanick.rochon[at]gmail[dot]com) - * - * Dual licensed under the MIT (MIT-LICENSE.txt) - * and GPL (GPL-LICENSE.txt) licenses. - * - * http://www.quasipartikel.at/multiselect/ - * - * - * Depends: - * ui.core.js - * ui.sortable.js - * - * Optional: - * localization (http://plugins.jquery.com/project/localisation) - * scrollTo (http://plugins.jquery.com/project/ScrollTo) - * - * Todo: - * Make batch actions faster - * Implement dynamic insertion through remote calls - */ - - -(function($) { - -$.widget("ui.multiselect", { - options: { - sortable: true, - dragToAdd: true, - searchable: true, - doubleClickable: true, - animated: 'fast', - show: 'slideDown', - hide: 'slideUp', - dividerLocation: 0.6, - selectedContainerOnLeft: true, - width: null, - height: null, - nodeComparator: function(node1,node2) { - var text1 = node1.text(), - text2 = node2.text(); - return text1 == text2 ? 0 : (text1 < text2 ? -1 : 1); - }, - includeRemoveAll: true, - includeAddAll: true, - pressEnterKeyToAddAll: false - }, - _create: function() { - this.element.hide(); - this.id = this.element.attr("id"); - this.container = $('
').insertAfter(this.element); - this.count = 0; // number of currently selected options - this.selectedContainer = $('
'); - if (this.options.selectedContainerOnLeft) { - this.selectedContainer.appendTo(this.container); - this.availableContainer = $('
').appendTo(this.container); - this.availableContainer.addClass('right-column'); - } - else - { - this.availableContainer = $('
').appendTo(this.container); - this.selectedContainer.appendTo(this.container); - this.selectedContainer.addClass('right-column'); - } - this.selectedActions = $('
0 '+$.ui.multiselect.locale.itemsCount+''+(this.options.includeRemoveAll?''+$.ui.multiselect.locale.removeAll+'':' ')+'
').appendTo(this.selectedContainer); - this.availableActions = $('
'+(this.options.includeAddAll?''+$.ui.multiselect.locale.addAll+'':' ')+'
').appendTo(this.availableContainer); - this.selectedList = $('
').bind('selectstart', function(){return false;}).appendTo(this.selectedContainer); - this.availableList = $('
').bind('selectstart', function(){return false;}).appendTo(this.availableContainer); - - var that = this; - - var width = this.options.width; - if (!width) { - width = this.element.width(); - } - var height = this.options.height; - if (!height) { - height = this.element.height(); - } - - // set dimensions - this.container.width(width-2); - if (this.options.selectedContainerOnLeft) { - this.selectedContainer.width(Math.floor(width*this.options.dividerLocation)-1); - this.availableContainer.width(Math.floor(width*(1-this.options.dividerLocation))-2); - } - else - { - this.selectedContainer.width(Math.floor(width*this.options.dividerLocation)-2); - this.availableContainer.width(Math.floor(width*(1-this.options.dividerLocation))-1); - } - - // fix list height to match