diff --git a/.gitignore b/.gitignore index b49fdf8dc86..371c8be2f5e 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ default.properties .DS_Store .idea *.iml +*.orig Thumbs.db /dolibarr_genesis.mp4 # Log files diff --git a/.travis.yml b/.travis.yml index c1bed319447..733e997bdf3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -38,8 +38,8 @@ env: jobs: fast_finish: true - allow_failures: - - php: nightly + #allow_failures: + #- php: nightly include: - if: type = push php: '5.6' @@ -73,13 +73,6 @@ before_install: phpenv config-rm xdebug.ini echo -- | - if [ "$DB" = 'postgresql' ]; then - echo "Check pgloader version" - pgloader --version - echo - fi - install: - | echo "Updating Composer" @@ -178,6 +171,10 @@ before_script: mysql --version | head - mysql -e "SELECT VERSION();" | head - psql --version + if [ "$DB" = 'postgresql' ]; then + echo "Check pgloader version" + pgloader --version + fi echo - | diff --git a/ChangeLog b/ChangeLog index 8b9edc38f2c..e84bef00e83 100644 --- a/ChangeLog +++ b/ChangeLog @@ -3,11 +3,82 @@ English Dolibarr ChangeLog -------------------------------------------------------------- +***** ChangeLog for 14.0.0 compared to 13.0.0 ***** + +For users: +---------- + + +For developers: +--------------- + + + +WARNING: + +Following changes may create regressions for some external modules, but were necessary to make Dolibarr better: +* The ICS value for direct debit or credit transfer is now store on each bank account instead of into the global setup. + + + +***** ChangeLog for 13.0.1 compared to 13.0.0 ***** + +FIX: 10.0 before crediting a withdrawal receipt, check whether it has been credited already. +FIX: 11.0 when a mandatory extrafield of type sellist contains '0' it should be considered empty and trigger an error message upon insertion +FIX: 11.0 when a new intervention is created from an object, a new $extrafields object is instantiated but not initialized +FIX: create MO, Column 'tms' cannot be null +FIX: #14290 #15900 +FIX: #16076 +FIX: #16077 +FIX: #16079 +FIX: #16080 +FIX: 16084 +FIX: #16107 +FIX: #16118 Timezone problem on some fields +FIX: #16131 +FIX: #16135 +FIX: #16143 +FIX: #16156 +FIX: #16160 +FIX: #16185 +FIX: #16189, fix download/see check deposit PDF +FIX: #16215 +FIX: Accountancy - label_operation is used instead of label_compte +FIX: Add critical price patch +FIX: Assignement of actors on tasks +FIX: Bad dates on info tabs +FIX: cash fence for takepos with multientity +FIX: CSRF errors on margin forms +FIX: encoding status in graph of vendor proposals +FIX: Fix detect dispached product and set to received completely when the supplier order have services (support STOCK_SUPPORTS_SERVICES) +FIX: Hide/Unhide external ICSS calendars +FIX: link to create event when task is in a project with a thirdparty +FIX: Localtax must be converted with price2num +FIX: manage price min for PRODUIT_CUSTOMER_PRICES +FIX: Missing language ico +FIX: Must not be able to edit vat of all lines if not draft +FIX: Bad "htdocs" found into a path +FIX: removed no more used proc update_modified_column_date_m on pgsql (its presence triggered errors) +FIX: Vulnerability report by Ricardo Matias +FIX: select default mail template +FIX: Select transport mode function when creating a supplier invoice and add unique key to the table llx_c_transport_mode in migrate sql +FIX: Merge of thirdparties : "unknow column fk_soc" + "Delivery" label +FIX: SQL Error in group by with postgres or mysql strict mode +FIX: takepos : load date function +FIX: Timeout during import +FIX: Trigger on expense report was not fired +FIX: User creation of expense report not visible +FIX: warning when adding a line if $remise_percent is an empty string +FIX: status late on purchase orders +FIX: ODT generation very slow + + ***** ChangeLog for 13.0.0 compared to 12.0.0 ***** For users: ---------- -NEW: Add module "Credit transfer SEPA" to manage payment of vendors using bank credit transfer SEPA files. +NEW: Module "Credit transfer SEPA" to manage payment of vendors using bank credit transfer SEPA files. +NEW: Module Intracomm report NEW: Module Reception (for a more accurate management of your receptions) moved from experimental to stable. NEW: Module Recruitment to manage Job position and applications. NEW: Several security issues after a private bug bounty campaign. @@ -22,7 +93,6 @@ NEW: Solve blocking feature. Can increase stock of a Kit without changing subpro NEW: add a widget to show the customers with outstanding limits reached NEW: add 2 rules for emailcollector: Message send/not sent from Dolibarr NEW: add a counter of number of words for pages in website module -NEW: add alert before changing thirdparty in TakePOS NEW: add a page to list Stock at a given date in the past NEW: add a start date to begin binding in accountancy NEW: add a statistics page to list popularity of products on invoices @@ -34,12 +104,12 @@ NEW: add column vat rate in page to define accounting account on product/service NEW: add costprice in fields of products list NEW: add an import profile for CUSTOMER ORDER, PO, PROPOSAL MODULE, SUPPLIER INVOICE NEW: add employee link in expense report binding page -NEW: add EORI No. as ProfID5 +NEW: add EORI No. as ProfID5 #15382 NEW: add export for various payments NEW: add Extrafields labels and values in mail on create ticket NEW: add Extrafields support on ECM module NEW: add filter rules "is answer" and "is not answer" in email collector -NEW: add focus when editing on product/stock/product.php Close #14548 +NEW: add focus when editing on product/stock/product.php -> close #14548 NEW: add free text on each terminal of cash desk NEW: add global search for customer payments and vendor payments NEW: add global search for miscellaneous payments @@ -67,7 +137,6 @@ NEW: add search param for close date on order list NEW: add show preview for mail attachement on form mail NEW: add State/Province origin for products NEW: add the workflow interaction close intervention on closing ticket -NEW: add third order printer to TakePOS NEW: add tracking number in list and search_all items NEW: add vcard for adherent and user NEW: add week number for month view in agenda @@ -75,7 +144,6 @@ NEW: Algeria data (VAT and forme_juridique) NEW: allow click on all header numbers on commerce area NEW: allow to reopen interventions (green button) NEW: allow zero quantity on supplier/vendor order line -NEW: appearance tab in TakePOS with more visual parameters NEW: better currency rate editor NEW: can build vendor invoice from vendor orders NEW: can change a product in lines of a recurring invoice or contract @@ -88,21 +156,16 @@ NEW: can edit the list of sending email profiles NEW: can enable/disable users in bulk actions NEW: can filter on accounting system ref in export of chart of account NEW: can filter on container type, language and tags in the list of web pages -NEW: can hide eatby, sellby dates with option PRODUCT_DISABLE_SELLBY and PRODUCT_DISABLE_EATBY +NEW: can hide eatby, sellby dates with option PRODUCT_DISABLE_EATBY and PRODUCT_DISABLE_SELLBY NEW: can import proposals, sales orders, supplier invoices NEW: can set a dedicated SMTP config for sending email from public ticket interface NEW: can set tags/categories to website pages NEW: can set type of price without tax per default for new sale price creation NEW: can use desired stock of a given warehouse for replenishment -NEW: change thirdparty with barcode scan in TakePOS NEW: common behavior for monthly leave list view NEW: convert all subscription in datetime -NEW: can create a thirdparty customer from TakePOS NEW: date shipment from order accepts hours NEW: price level compatibility for variant -NEW: delayed payment in TakePOS -NEW: display date range if exist in TakePOS -NEW: display resiliate status in TakePOS for member NEW: display stat for BOM on "object referent"/linked Object product tab NEW: Email configuration - allow auto signed certificate when smtp ssl activated NEW: enable free emails input with select2 @@ -124,29 +187,24 @@ NEW: link on balance to the ledger NEW: MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER const in email collector NEW: manage errors on update extra fields in ticket card NEW: mass-actions for the event list view -NEW: Module Intracomm report NEW: more filter for "View change logs" -NEW: multicurrency total in TakePOS NEW: multiselect type and date to date filter -NEW: Nature of product is now a dictionay NEW: new line template: hidden conf to fill service dates from the last service line NEW: PDF model storm for delivery NEW: possibilty to group payments by mode and show their subtotal -NEW: Print payment method and change in TakePOS NEW: Priority and transparency from external calendar events +NEW: Products - Nature of product is now a dictionary #13287 NEW: Products Import/Export 'default warehouse' and 'use batch number' fields NEW: Purchase price table: added filterable table columns NEW: rate editor for multicurrency NEW: ref_ext field for Commande lines, order lines, Attributes and Combinations, Invoice lines, payments, order lines NEW: remove new lines in mail on add ticket message -NEW: restrict thirdparty to customer in TakePOS NEW: Rule "email to" accept wildcard * -NEW: Save filter of the project homepage +NEW: save filter of the project homepage NEW: select-able columns on customer and supplier invoice paymnet list NEW: select-able columns on miscellaneous payments + more data columns NEW: select-able columns on social taxes list NEW: send context and remove new lines on create ticket -NEW: show available stock in TakePOS NEW: show category filter on lists only when user have rights to read categories NEW: show header number and make it clickable in warehouse area, payment area, shipment area NEW: show image of user in the combo select of users @@ -159,15 +217,27 @@ NEW: show tags and status in search list of website pages NEW: show user on external calender events (when found) NEW: subject title with company name instead of application title in ticket message NEW: Support for Samba4 AD +NEW: TakePOS appearance tab with more visual parameters +NEW: TakePOS add alert before changing thirdparty +NEW: TakePOS add third order printer +NEW: TakePOS can change thirdparty with barcode scan +NEW: TakePOS can create a thirdparty customer from TakePOS frontend NEW: TakePOS connector compatibility with RECEIPT PRINTERS module +NEW: TakePOS add delayed payment +NEW: TakePOS display date range if exist +NEW: TakePOS display resiliate status for members NEW: TakePOS Gift Receipt -NEW: TakePOS Multicurrency compatibility +NEW: TakePOS multicurrency compatibility +NEW: TakePOS multicurrency total +NEW: TakePOS print payment method and change +NEW: TakePOS restrict thirdparty to customer +NEW: TakePOS show available stock NEW: TakePOS Weighing Scale compatibility with TakePOS connector #14725 -NEW: Third-Party Import new fields: mother company,outstanding debt limit,bank account,incoterms +NEW: Thirdparty Import new fields: mother company,outstanding debt limit,bank account,incoterms NEW: Thirdparty module : box on customer/supplier tab for invoice outsantding amount late -NEW: ticket classification on create from email collector +NEW: Ticket classification on create from email collector NEW: Ticket message notifications when edited from public interface -NEW: translate classification labels in ticket +NEW: Ticket translate classification labels in ticket NEW: VAT rate for Angola #15606 NEW: VAT and juridical status for Algeria NEW: VAT report - Invert constant to show by default zero VAT in reports @@ -181,11 +251,10 @@ NEW: add option "If the feature to manage kits of module Stock is used, show det For developers: --------------- -NEW: add substitution key __MEMBER_TYPE__ -NEW: add substitution key __TYPE__ +NEW: add __MEMBER_TYPE__ and __TYPE__ substitution key NEW: add function dolButtonToOpenUrlInDialogPopup() to be able to open page into a popup NEW: show line number on intervention card (via MAIN_VIEW_LINE_NUMBER) -NEW: Add some fields to link website page to an other object +NEW: add some fields to link website page to an other object NEW: fill ECM src object fields in dol_add_file_process NEW: conf to allow to show the full tree in warehouse popup NEW: can use parameter ?THEME_DARKMODEENABLED=2 for a preview of theme in dark mode @@ -194,14 +263,11 @@ NEW: can add event to log into blockedlog module with a constant NEW: add property cssview when declaring fields of an object NEW: can use dynamic code into the 'enabled' property of DAO fields NEW: field ref_ext in llx_commandedet -NEW: field ref_ext for Attributes and Combinations +NEW: fields ref_ext for Attributes and Combinations NEW: OAuth SCOPE for Admin SDK -NEW: retrieve discount from invoice from API NEW: standardizes API thirdparties by email like other object -NEW: Thirdparty REST API: endpoint to set price level -NEW: use new category API for project list view NEW: Triggers Attributes and Attributes values -NEW: added incoterms data into the substitution array +NEW: add incoterms data into the substitution array NEW: add send context for ticket NEW: add a message in error_log after detection of SQL or script injection NEW: add validation of MX domain for emails @@ -211,19 +277,20 @@ NEW: add param to not show links when output tags APIs NEW: API get contacts list of a given order -NEW: API endpoint getContacts and Clean results +NEW: API endpoint getContacts and clean results NEW: API can update a payment NEW: API get member by thirdparty NEW: API get thirdparty by barcode NEW: API get users by email / login -NEW: allow to edit field "demand reason" through API NEW: fetch contact by email with REST API -NEW: get state by REST API -NEW: get state dictionary by REST API -NEW: improve Product API for product variants +NEW: get state dictionnary by REST API +NEW: improve Product API for variant products +NEW: retrieve discount from invoice from API +NEW: Thirdparty REST API: endpoint to set price level +NEW: use new category API for project list view HOOKs -NEW: Hook on propal card +NEW: add hook on propal card NEW: add hooks on newpayment page to allow external payment modules NEW: add hooks on stats pages NEW: add formConfirm hook on product page @@ -238,7 +305,7 @@ Following changes may create regressions for some external modules, but were nec * All properties ->titre have been renamed into ->title * Property $paiementid in API 'api_supplier_invoices.php' has been renamed into into $payment_mode_id * Property 'num_paiement' has been renamed 'num_payment' everywhere for better code consistency. -* The deprecated subsitution key __SIGNATURE__ has been removed. Use __USER_SIGNATURE__ if you used the old syntax in your email templates. +* The deprecated subsitution key __SIGNATURE__ has been removed. Replace it with __USER_SIGNATURE__ if you used the old syntax in your email templates. * The hidden option HOLIDAY_MORE_PUBLIC_HOLIDAYS has been removed. Use instead the dictionary table if you need to define custom days of holiday. * If you build a class that implement CommonObject to use the incoterm properties or methods (->fk_incoterm, ->label_incoterm, ->location_incoterm), you must now also include declaration of the Trait 'CommonIncoterm' in your class. All incoterm functions were moved into this Trait. @@ -250,7 +317,9 @@ Following changes may create regressions for some external modules, but were nec * Function showStripePaymentUrl, getStripePaymentUrl, showPaypalPaymentUrl and getPaypalPaymentUrl has been removed. The generic one showOnlinePaymentUrl and getOnlinePaymentUrl are always used. * Context for hook showSocinfoOnPrint has been moved from "showsocinfoonprint" to "main" * Library htdocs/includes/phpoffice/phpexcel as been removed (replaced with htdocs/includes/phpoffice/PhpSpreadsheet) - +* Database transaction in your triggers must be correctly balanced (one close for one open). If not, an error will be returned by the trigger, even if trigger did return error code. +* Dolibarr v13 is still compatible with any PHP version between 5.6.0 and 7.4.*; Unit tests are OK with PHP 8.0 but some warnings or troubles may appears with PHP 8.0. +* All your Ajax services must contains such a line at begin of file: if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal ***** ChangeLog for 12.0.4 compared to 12.0.3 ***** FIX: make formConfirm an addreplace-type hook diff --git a/build/README b/build/README index 14f2b92ae39..626953f9376 100644 --- a/build/README +++ b/build/README @@ -7,6 +7,9 @@ Building packages ################################################## All sub-directories of "build" directory contains files (setup or binary tools) required to build automatically Dolibarr packages. +The build directory and all its contents is absolutely not required to make Dolibarr working. +It is here only to build Dolibarr packages, and those generated packages will not contains this "build" directory. + There are several tools: @@ -17,8 +20,7 @@ There are several tools: -------------------------------------------------------------------------------------------------- -Prerequisites to build tgz, debian, rpm package: - +Prerequisites to build tgz, debian and rpm packages: > apt-get install tar dpkg dpatch p7zip-full rpm zip @@ -58,10 +60,6 @@ Prerequisites to build autoexe DoliWamp package: -------------------------------------------------------------------------------------------------- -Note: -The build directory and all its contents is absolutely not required to make Dolibarr working. -It is here only to build Dolibarr packages, and those generated packages will not contains this "build" directory. - You can find in "build", following sub-directories: diff --git a/build/debian/control b/build/debian/control index 0ef5367072f..eed54669555 100755 --- a/build/debian/control +++ b/build/debian/control @@ -4,7 +4,7 @@ Priority: optional Maintainer: Laurent Destailleur (eldy) # Uploaders: Laurent Destailleur (eldy) # Only if differs from Maintainer Standards-Version: 3.9.6 -Homepage: http://www.dolibarr.org +Homepage: https://www.dolibarr.org Build-Depends: debhelper (>= 9), po-debconf # This package need at least debian 7 or ubuntu 13.04 or any distribution based on this version diff --git a/build/debian/dolibarr.postinst b/build/debian/dolibarr.postinst index 7684d02ff3d..26a08a55826 100644 --- a/build/debian/dolibarr.postinst +++ b/build/debian/dolibarr.postinst @@ -23,7 +23,7 @@ setup_empty_conf() { mkdir -p /etc/dolibarr touch /etc/dolibarr/conf.php chown root:www-data /etc/dolibarr/conf.php - chmod 664 /etc/dolibarr/conf.php + chmod 660 /etc/dolibarr/conf.php } is_new_upstream_version() { diff --git a/build/generate_filelist_xml.php b/build/generate_filelist_xml.php index 41c20740d78..50eb6c84def 100755 --- a/build/generate_filelist_xml.php +++ b/build/generate_filelist_xml.php @@ -105,8 +105,8 @@ if (empty($includecustom)) { } } -print "Release : ".$release."\n"; print "Working on files into : ".DOL_DOCUMENT_ROOT."\n"; +print "Release : ".$release."\n"; print "Include custom in signature : ".$includecustom."\n"; print "Include constants in signature : "; foreach ($includeconstants as $countrycode => $tmp) { diff --git a/dev/README b/dev/README index 337928507fc..78666d77f3a 100644 --- a/dev/README +++ b/dev/README @@ -1,13 +1,14 @@ README (English) -------------------------------- -This directory contains sub-directories to provide tools or -documentation for developers. -Note: All files in this directory are in VCS only and are not -provided with a standard release. +This directory contains sub-directories to provide tools or documentation for developers. + +Note: All files in this directory are in the source repository only and are not provided with a standard release. They are useless to make Dolibarr working. + +You may find a more complete documentation on Dolibarr on the wiki: -There is also some documentation on Dolibarr Wiki: https://wiki.dolibarr.org/ -and -https://doxygen.dolibarr.org/ +and on + +https://doxygen.dolibarr.org/ diff --git a/dev/examples/code/create_invoice.php b/dev/examples/code/create_invoice.php index 1acf181a4ba..1d231a7fd7a 100755 --- a/dev/examples/code/create_invoice.php +++ b/dev/examples/code/create_invoice.php @@ -29,8 +29,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Global variables @@ -49,7 +49,10 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result=$user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (! $result > 0) { dol_print_error('', $user->error); exit; } +if (! $result > 0) { + dol_print_error('', $user->error); + exit; +} $user->getrights(); @@ -82,12 +85,12 @@ $obj->lines[]=$line1; // Create invoice $idobject=$obj->create($user); -if ($idobject > 0) -{ +if ($idobject > 0) { // Change status to validated $result=$obj->validate($user); - if ($result > 0) print "OK Object created with id ".$idobject."\n"; - else { + if ($result > 0) { + print "OK Object created with id ".$idobject."\n"; + } else { $error++; dol_print_error($db, $obj->error); } @@ -99,8 +102,7 @@ if ($idobject > 0) // -------------------- END OF YOUR CODE -------------------- -if (! $error) -{ +if (! $error) { $db->commit(); print '--- end ok'."\n"; } else { diff --git a/dev/examples/code/create_order.php b/dev/examples/code/create_order.php index 7fe1a82251a..a851ac3cbc5 100755 --- a/dev/examples/code/create_order.php +++ b/dev/examples/code/create_order.php @@ -29,8 +29,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Global variables @@ -49,7 +49,10 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result=$user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (! $result > 0) { dol_print_error('', $user->error); exit; } +if (! $result > 0) { + dol_print_error('', $user->error); + exit; +} $user->getrights(); @@ -80,12 +83,12 @@ $com->lines[]=$orderline1; // Create order $idobject=$com->create($user); -if ($idobject > 0) -{ +if ($idobject > 0) { // Change status to validated $result=$com->valid($user); - if ($result > 0) print "OK Object created with id ".$idobject."\n"; - else { + if ($result > 0) { + print "OK Object created with id ".$idobject."\n"; + } else { $error++; dol_print_error($db, $com->error); } @@ -97,8 +100,7 @@ if ($idobject > 0) // -------------------- END OF YOUR CODE -------------------- -if (! $error) -{ +if (! $error) { $db->commit(); print '--- end ok'."\n"; } else { diff --git a/dev/examples/code/create_product.php b/dev/examples/code/create_product.php index 20b898a92aa..8f742065f2f 100755 --- a/dev/examples/code/create_product.php +++ b/dev/examples/code/create_product.php @@ -29,8 +29,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Global variables @@ -49,7 +49,10 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result=$user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (! $result > 0) { dol_print_error('', $user->error); exit; } +if (! $result > 0) { + dol_print_error('', $user->error); + exit; +} $user->getrights(); @@ -79,8 +82,7 @@ $myproduct->weight_units = 0; // Create product in database $idobject = $myproduct->create($user); -if ($idobject > 0) -{ +if ($idobject > 0) { print "OK Object created with id ".$idobject."\n"; } else { $error++; @@ -89,8 +91,7 @@ if ($idobject > 0) // -------------------- END OF YOUR CODE -------------------- -if (! $error) -{ +if (! $error) { $db->commit(); print '--- end ok'."\n"; } else { diff --git a/dev/examples/code/create_user.php b/dev/examples/code/create_user.php index d585b490a9c..e374fec531d 100755 --- a/dev/examples/code/create_user.php +++ b/dev/examples/code/create_user.php @@ -29,8 +29,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Global variables @@ -49,7 +49,10 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result=$user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (! $result > 0) { dol_print_error('', $user->error); exit; } +if (! $result > 0) { + dol_print_error('', $user->error); + exit; +} $user->getrights(); @@ -69,18 +72,17 @@ $obj->nom = 'ABCDEF'; // Create user $idobject=$obj->create($user); -if ($idobject > 0) -{ +if ($idobject > 0) { // Change status to validated $result=$obj->setStatut(1); - if ($result > 0) print "OK Object created with id ".$idobject."\n"; - else { + if ($result > 0) { + print "OK Object created with id ".$idobject."\n"; + } else { $error++; dol_print_error($db, $obj->error); } -} elseif ($obj->error == 'ErrorLoginAlreadyExists') -{ - print "User with login ".$obj->login." already exists\n"; +} elseif ($obj->error == 'ErrorLoginAlreadyExists') { + print "User with login ".$obj->login." already exists\n"; } else { $error++; dol_print_error($db, $obj->error); @@ -89,8 +91,7 @@ if ($idobject > 0) // -------------------- END OF YOUR CODE -------------------- -if (! $error) -{ +if (! $error) { $db->commit(); print '--- end ok'."\n"; } else { diff --git a/dev/examples/code/get_contracts.php b/dev/examples/code/get_contracts.php index aec246e9480..40bee133d11 100755 --- a/dev/examples/code/get_contracts.php +++ b/dev/examples/code/get_contracts.php @@ -29,8 +29,8 @@ $path=dirname(__FILE__).'/'; // Test if batch mode if (substr($sapi_type, 0, 3) == 'cgi') { - echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; - exit; + echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; + exit; } // Global variables @@ -49,14 +49,17 @@ $langs->load("main"); // To load language file for default language // Load user and its permissions $result=$user->fetch('', 'admin'); // Load user for login 'admin'. Comment line to run as anonymous user. -if (! $result > 0) { dol_print_error('', $user->error); exit; } +if (! $result > 0) { + dol_print_error('', $user->error); + exit; +} $user->getrights(); print "***** ".$script_file." (".$version.") *****\n"; if (! isset($argv[1])) { // Check parameters - print "Usage: ".$script_file." id_thirdparty ...\n"; - exit; + print "Usage: ".$script_file." id_thirdparty ...\n"; + exit; } print '--- start'."\n"; print 'Argument id_thirdparty='.$argv[1]."\n"; diff --git a/dev/examples/git/pre-commit b/dev/examples/git/pre-commit new file mode 100644 index 00000000000..f89d662ae65 --- /dev/null +++ b/dev/examples/git/pre-commit @@ -0,0 +1,49 @@ +#!/bin/sh + +PROJECT=`php -r "echo dirname(dirname(dirname(realpath('$0'))));"` +STAGED_FILES_CMD=`git diff --cached --name-only --diff-filter=ACMR HEAD | grep \\\\.php` + +# Determine if a file list is passed +if [ "$#" -eq 1 ] +then + oIFS=$IFS + IFS=' + ' + SFILES="$1" + IFS=$oIFS +fi +SFILES=${SFILES:-$STAGED_FILES_CMD} + +echo "Checking PHP Lint..." +for FILE in $SFILES +do + php -l -d display_errors=0 $PROJECT/$FILE + if [ $? != 0 ] + then + echo "Fix the error before commit." + exit 1 + fi + FILES="$FILES $PROJECT/$FILE" +done + +if [ "$FILES" != "" ] +then + echo "Running PHPCS Code Sniffer..." + #~/vendor/bin/phpcs --version + #phpcs --standard=PSR2 --encoding=utf-8 -n -p $FILES + # Check Dolibarr standard + ~/vendor/bin/phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + # Check your own standard + #~/vendor/bin/phpcs -s -p -d memory_limit=-1 --parallel=2 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + + if [ $? != 0 ] + then + # fix standard errors + ~/vendor/bin/phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=dev/setup/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + #~/vendor/bin/phpcbf -s -p -d memory_limit=-1 --extensions=php --colors --tab-width=4 --standard=htdocs/custom/codesniffer/ruleset.xml --encoding=utf-8 --runtime-set ignore_warnings_on_exit true $FILES + echo "Fix the error before commit." + exit 1 + fi +fi + +exit $? diff --git a/dev/resources/dbmodel/dolibarr_schema.mwb b/dev/resources/dbmodel/dolibarr_schema.mwb index 27bc4ab2403..37929762bab 100644 Binary files a/dev/resources/dbmodel/dolibarr_schema.mwb and b/dev/resources/dbmodel/dolibarr_schema.mwb differ diff --git a/dev/resources/iso-normes/barcode_EAN13.txt b/dev/resources/iso-normes/barcode_EAN13.txt index 69194625126..f4496327ee4 100644 --- a/dev/resources/iso-normes/barcode_EAN13.txt +++ b/dev/resources/iso-normes/barcode_EAN13.txt @@ -1,3 +1,7 @@ +Barcode EAN 13 + +FR +== Signification des chiffres. - 2 chiffres pour le code pays ou code systeme @@ -9,6 +13,24 @@ Cette regle subit de nombreuses entorses pour ameliorer l'usage des chiffres dis Voici la liste des codes pays ou systeme : + +EN +== +Meaning of the numbers. + +- 2 digits for the country code or system code +- 5 digits for the company identifier +- 5 digits for item identifier +- 1 digit for checksum + +This rule has been twisted many times to improve the use of the available numbers. +Here is the list of country codes or system: + + + +List +==== + 00 � 13 UCC (Etats-Unis et Canada) 20 � 29 Codification interne en magasin 30 � 37 GENCOD-EAN France @@ -104,4 +126,4 @@ Voici la liste des codes pays ou systeme : 978 - 979 Livres (ISBN) 980 Refus de remboursement 981 - 982 Coupons (monnaie courante) -99 Coupons \ No newline at end of file +99 Coupons diff --git a/dev/resources/licence/Links on GPL.txt b/dev/resources/licence/Links on GPL.txt index 0fb3b63c851..d8a5f790458 100644 --- a/dev/resources/licence/Links on GPL.txt +++ b/dev/resources/licence/Links on GPL.txt @@ -1,5 +1,6 @@ * Page with license compatibility -https://www.gnu.org/licenses/quick-guide-gplv3.fr.html +[EN] https://www.gnu.org/licenses/quick-guide-gplv3.en.html +[FR] https://www.gnu.org/licenses/quick-guide-gplv3.fr.html * FAQ on GPL license https://www.fsf.org/licensing/licenses/gpl-faq.html diff --git a/dev/setup/nginx/dolibarr b/dev/setup/nginx/dolibarr index 82b8d2dc7bf..ffda5fae609 100644 --- a/dev/setup/nginx/dolibarr +++ b/dev/setup/nginx/dolibarr @@ -5,13 +5,13 @@ server { root /path/to/your/htdocs; - # Optionnal + # Optional error_log /path/to/your/log/directory/nginx.error.log; access_log /path/to/your/log/directory/nginx.access.log; index index.php index.html index.htm; - # Optionnal + # Optional server_name your-fqdn.tld; location / { @@ -23,6 +23,6 @@ server { fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_read_timeout 600; include fastcgi_params; - fastcgi_pass unix:/var/run/php5-fpm.sock; + fastcgi_pass unix:/var/run/php5-fpm.sock; // /var/run/php/php7.0-fpm.sock } } diff --git a/doc/index.html b/doc/index.html index 5c655136e3e..333f96099c3 100644 --- a/doc/index.html +++ b/doc/index.html @@ -6,18 +6,15 @@ -This directory contains several subdirectories with entries for -informations on Dolibarr.
-But if you are looking for other resources (downloads, documentation, addons, ...), you can find this -on Internet on web following sites:
-
-* Dolibarr wiki (documentation)
+This directory contains several subdirectories with entries for informations on Dolibarr.
+But if you are looking for other resources (downloads, documentation, addons, ...), you can find this on Internet on web following sites:
+
* Dolibarr portal (official website)

-* Dolibarr demo (online)
+* Dolibarr wiki (documentation)

-* DoliWamp, the Dolibarr for Windows
+* Dolibarr demo (online)

* DoliStore (official addons/plugins market place)
diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 6d621a7e101..3c3489185f4 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -444,9 +444,6 @@ if ($id) // Form to add a new line if ($tabname[$id]) { - $alabelisused = 0; - $var = false; - $fieldlist = explode(',', $tabfield[$id]); // Line for title @@ -481,7 +478,6 @@ if ($id) } print ''; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; @@ -612,7 +608,7 @@ if ($id) print ' '; } else { $tmpaction = 'view'; - $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; diff --git a/htdocs/accountancy/admin/card.php b/htdocs/accountancy/admin/card.php index 029550192f0..23ebde7e230 100644 --- a/htdocs/accountancy/admin/card.php +++ b/htdocs/accountancy/admin/card.php @@ -32,7 +32,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; $error = 0; // Load translation files required by the page -$langs->loadLangs(array("bills", "accountancy")); +$langs->loadLangs(array("bills", "accountancy", "compta")); $mesg = ''; $action = GETPOST('action', 'aZ09'); @@ -41,7 +41,9 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $rowid = GETPOST('rowid', 'int'); $cancel = GETPOST('cancel', 'alpha'); -$accountingaccount = GETPOST('accountingaccount', 'alpha'); + +$account_number = GETPOST('account_number', 'string'); +$label = GETPOST('label', 'alpha'); // Security check if ($user->socid > 0) accessforbidden(); @@ -65,104 +67,118 @@ if (GETPOST('cancel', 'alpha')) if ($action == 'add' && $user->rights->accounting->chartofaccount) { if (!$cancel) { - $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); - - // Clean code - - // To manage zero or not at the end of the accounting account - if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) + if (!$account_number) { - $account_number = GETPOST('account_number', 'string'); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountNumber")), null, 'errors'); + $action = 'create'; + } elseif (!$label) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); + $action = 'create'; } else { - $account_number = clean_account(GETPOST('account_number', 'string')); - } + $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid='.((int) $conf->global->CHARTOFACCOUNTS); - if (GETPOST('account_parent', 'int') <= 0) - { - $account_parent = 0; - } else { - $account_parent = GETPOST('account_parent', 'int'); - } + dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + $result = $db->query($sql); + $obj = $db->fetch_object($result); - $object->fk_pcg_version = $obj->pcg_version; - $object->pcg_type = GETPOST('pcg_type', 'alpha'); - $object->account_number = $account_number; - $object->account_parent = $account_parent; - $object->account_category = GETPOST('account_category', 'alpha'); - $object->label = GETPOST('label', 'alpha'); - $object->labelshort = GETPOST('labelshort', 'alpha'); - $object->active = 1; + // Clean code - $res = $object->create($user); - if ($res == - 3) { - $error = 1; - $action = "create"; - setEventMessages($object->error, $object->errors, 'errors'); - } elseif ($res == - 4) { - $error = 2; - $action = "create"; - setEventMessages($object->error, $object->errors, 'errors'); - } elseif ($res < 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; - } - if (!$error) - { - setEventMessages("RecordCreatedSuccessfully", null, 'mesgs'); - $urltogo = $backtopage ? $backtopage : dol_buildpath('/accountancy/admin/account.php', 1); - header("Location: ".$urltogo); - exit; + // To manage zero or not at the end of the accounting account + if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) { + $account_number = $account_number; + } else { + $account_number = clean_account($account_number); + } + + if (GETPOST('account_parent', 'int') <= 0) { + $account_parent = 0; + } else { + $account_parent = GETPOST('account_parent', 'int'); + } + + $object->fk_pcg_version = $obj->pcg_version; + $object->pcg_type = GETPOST('pcg_type', 'alpha'); + $object->account_number = $account_number; + $object->account_parent = $account_parent; + $object->account_category = GETPOST('account_category', 'alpha'); + $object->label = $label; + $object->labelshort = GETPOST('labelshort', 'alpha'); + $object->active = 1; + + $res = $object->create($user); + if ($res == -3) { + $error = 1; + $action = "create"; + setEventMessages($object->error, $object->errors, 'errors'); + } elseif ($res == -4) { + $error = 2; + $action = "create"; + setEventMessages($object->error, $object->errors, 'errors'); + } elseif ($res < 0) { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + $action = "create"; + } + if (!$error) { + setEventMessages("RecordCreatedSuccessfully", null, 'mesgs'); + $urltogo = $backtopage ? $backtopage : dol_buildpath('/accountancy/admin/account.php', 1); + header("Location: " . $urltogo); + exit; + } } } } elseif ($action == 'edit' && $user->rights->accounting->chartofaccount) { if (!$cancel) { - $result = $object->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); - - // Clean code - - // To manage zero or not at the end of the accounting account - if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) + if (!$account_number) { - $account_number = GETPOST('account_number', 'string'); - } else { - $account_number = clean_account(GETPOST('account_number', 'string')); - } - - if (GETPOST('account_parent', 'int') <= 0) + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountNumber")), null, 'errors'); + $action = 'update'; + } elseif (!$label) { - $account_parent = 0; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")), null, 'errors'); + $action = 'update'; } else { - $account_parent = GETPOST('account_parent', 'int'); - } + $result = $object->fetch($id); - $object->fk_pcg_version = $obj->pcg_version; - $object->pcg_type = GETPOST('pcg_type', 'alpha'); - $object->account_number = $account_number; - $object->account_parent = $account_parent; - $object->account_category = GETPOST('account_category', 'alpha'); - $object->label = GETPOST('label', 'alpha'); - $object->labelshort = GETPOST('labelshort', 'alpha'); + $sql = 'SELECT pcg_version FROM ' . MAIN_DB_PREFIX . 'accounting_system WHERE rowid=' . $conf->global->CHARTOFACCOUNTS; - $result = $object->update($user); + dol_syslog('accountancy/admin/card.php:: $sql=' . $sql); + $result2 = $db->query($sql); + $obj = $db->fetch_object($result2); - if ($result > 0) { - $urltogo = $backtopage ? $backtopage : ($_SERVER["PHP_SELF"]."?id=".$id); - header("Location: ".$urltogo); - exit(); - } else { - $mesg = $object->error; + // Clean code + + // To manage zero or not at the end of the accounting account + if ($conf->global->ACCOUNTING_MANAGE_ZERO == 1) { + $account_number = $account_number; + } else { + $account_number = clean_account($account_number); + } + + if (GETPOST('account_parent', 'int') <= 0) { + $account_parent = 0; + } else { + $account_parent = GETPOST('account_parent', 'int'); + } + + $object->fk_pcg_version = $obj->pcg_version; + $object->pcg_type = GETPOST('pcg_type', 'alpha'); + $object->account_number = $account_number; + $object->account_parent = $account_parent; + $object->account_category = GETPOST('account_category', 'alpha'); + $object->label = $label; + $object->labelshort = GETPOST('labelshort', 'alpha'); + + $result = $object->update($user); + + if ($result > 0) { + $urltogo = $backtopage ? $backtopage : ($_SERVER["PHP_SELF"] . "?id=" . $id); + header("Location: " . $urltogo); + exit(); + } else { + $mesg = $object->error; + } } } else { $urltogo = $backtopage ? $backtopage : ($_SERVER["PHP_SELF"]."?id=".$id); @@ -222,7 +238,7 @@ if ($action == 'create') { // Account number print ''.$langs->trans("AccountNumber").''; - print ''; + print ''; // Label print ''.$langs->trans("Label").''; diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 53dfb1cd5f9..e3a39c5d8b1 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -438,8 +438,6 @@ if ($id) // Form to add a new line if ($tabname[$id]) { - $alabelisused = 0; - $fieldlist = explode(',', $tabfield[$id]); // Line for title @@ -496,7 +494,6 @@ if ($id) else print $valuetoshow; print ''; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index ae36f0f7fa6..a7bf28d9091 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -100,7 +100,7 @@ if ($action == 'update') { 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) { + if (!($res > 0)) { $error++; } @@ -114,9 +114,10 @@ if ($action == 'setlistsorttodo') { 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) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -127,9 +128,10 @@ if ($action == 'setlistsortdone') { if ($action == 'setmanagezero') { $setmanagezero = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_MANAGE_ZERO", $setmanagezero, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -140,9 +142,10 @@ if ($action == 'setmanagezero') { if ($action == 'setdisabledirectinput') { $setdisabledirectinput = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "BANK_DISABLE_DIRECT_INPUT", $setdisabledirectinput, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -153,9 +156,10 @@ if ($action == 'setdisabledirectinput') { if ($action == 'setenabledraftexport') { $setenabledraftexport = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL", $setenabledraftexport, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -166,9 +170,10 @@ if ($action == 'setenabledraftexport') { if ($action == 'setenablesubsidiarylist') { $setenablesubsidiarylist = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTANCY_COMBO_FOR_AUX", $setenablesubsidiarylist, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -179,9 +184,10 @@ if ($action == 'setenablesubsidiarylist') { if ($action == 'setdisablebindingonsales') { $setdisablebindingonsales = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_SALES", $setdisablebindingonsales, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -192,9 +198,10 @@ if ($action == 'setdisablebindingonsales') { if ($action == 'setdisablebindingonpurchases') { $setdisablebindingonpurchases = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_PURCHASES", $setdisablebindingonpurchases, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -205,9 +212,10 @@ if ($action == 'setdisablebindingonpurchases') { if ($action == 'setdisablebindingonexpensereports') { $setdisablebindingonexpensereports = GETPOST('value', 'int'); $res = dolibarr_set_const($db, "ACCOUNTING_DISABLE_BINDING_ON_EXPENSEREPORTS", $setdisablebindingonexpensereports, 'yesno', 0, '', $conf->entity); - if (!$res > 0) { + if (!($res > 0)) { $error++; } + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -215,9 +223,11 @@ if ($action == 'setdisablebindingonexpensereports') { } } + /* * View */ + $form = new Form($db); $title = $langs->trans('ConfigAccountingExpert'); diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index bb192f0a693..1d3e8bccdd7 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -407,8 +407,6 @@ if ($id) // Form to add a new line if ($tabname[$id]) { - $alabelisused = 0; - $fieldlist = explode(',', $tabfield[$id]); // Line for title @@ -437,7 +435,6 @@ if ($id) else print $valuetoshow; print ''; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; } print ''; diff --git a/htdocs/accountancy/admin/productaccount.php b/htdocs/accountancy/admin/productaccount.php index 2f92cd5842e..b93d82a59c0 100644 --- a/htdocs/accountancy/admin/productaccount.php +++ b/htdocs/accountancy/admin/productaccount.php @@ -372,26 +372,26 @@ if ($result) print ''; print ''.$langs->trans('Options').''.$langs->trans('Description').''; print "\n"; - print ' '.$langs->trans('OptionModeProductSell').''; + print ' '.$langs->trans('OptionModeProductSell').''; print ''.$langs->trans('OptionModeProductSellDesc'); print "\n"; if ($mysoc->isInEEC()) { - print ' '.$langs->trans('OptionModeProductSellIntra').''; + print ' '.$langs->trans('OptionModeProductSellIntra').''; print ''.$langs->trans('OptionModeProductSellIntraDesc'); print "\n"; } - print ' '.$langs->trans('OptionModeProductSellExport').''; + print ' '.$langs->trans('OptionModeProductSellExport').''; print ''.$langs->trans('OptionModeProductSellExportDesc'); print "\n"; - print ' '.$langs->trans('OptionModeProductBuy').''; + print ' '.$langs->trans('OptionModeProductBuy').''; print ''.$langs->trans('OptionModeProductBuyDesc')."\n"; if ($mysoc->isInEEC()) { - print ' '.$langs->trans('OptionModeProductBuyIntra').''; + print ' '.$langs->trans('OptionModeProductBuyIntra').''; print ''.$langs->trans('OptionModeProductBuyDesc')."\n"; } - print ' '.$langs->trans('OptionModeProductBuyExport').''; + print ' '.$langs->trans('OptionModeProductBuyExport').''; print ''.$langs->trans('OptionModeProductBuyDesc')."\n"; print "\n"; diff --git a/htdocs/accountancy/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index 1547983da0c..de60bd09897 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -16,7 +16,6 @@ * * You should have received a copy of the GNU General Public License * along with this program. If not, see . - * */ /** @@ -37,7 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page -$langs->loadLangs(array("accountancy")); +$langs->loadLangs(array("accountancy", "compta")); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $sortorder = GETPOST("sortorder", 'alpha'); @@ -88,6 +87,7 @@ if (empty($search_date_start) && !GETPOSTISSET('formfilteraction')) } else { $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); $year_start = dol_print_date(dol_now(), '%Y'); + if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year $year_end = $year_start + 1; $month_end = $month_start - 1; if ($month_end < 1) @@ -306,7 +306,7 @@ if ($action != 'export_csv') $accountingaccountstatic->fetch(null, $line->numero_compte, true); if (!empty($accountingaccountstatic->account_number)) { - $accounting_account = $accountingaccountstatic->getNomUrl(0, 1); + $accounting_account = $accountingaccountstatic->getNomUrl(0, 1, 0, '', 0, -1, 0, 'accountcard'); } else { $accounting_account = length_accountg($line->numero_compte); } @@ -321,8 +321,19 @@ if ($action != 'export_csv') $root_account_description = $tmparrayforrootaccount['label']; $root_account_number = $tmparrayforrootaccount['account_number']; + //var_dump($tmparrayforrootaccount); + //var_dump($accounting_account); + //var_dump($accountingaccountstatic); if (empty($accountingaccountstatic->label) && $accountingaccountstatic->id > 0) { - $link = ''.img_edit().''; + $link = '' . img_edit() . ''; + } elseif ($accounting_account == 'NotDefined') { + $link = '' . img_edit_add() . ''; + } elseif (empty($tmparrayforrootaccount['label'])) { + // $tmparrayforrootaccount['label'] not defined = the account has not parent with a parent. + // This is useless, we should not create a new account when an account has no parent, we must edit it to fix its parent. + // BUG 1: Accounts on level root or level 1 must not have a parent 2 level higher, so shoule not show a link to create another account. + // BUG 2: Adding a link to create a new accounting account here is useless because it is not add as parent of the orphelin. + //$link = '' . img_edit_add() . ''; } if (!empty($show_subgroup)) @@ -360,8 +371,22 @@ if ($action != 'export_csv') print ''; print ''.$accounting_account.''; if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) print ''.price($opening_balance).''; - print ''.price($line->debit).''; - print ''.price($line->credit).''; + + $urlzoom = ''; + if ($line->numero_compte) { + $urlzoom = DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?search_accountancy_code_start='.urlencode($line->numero_compte).'&search_accountancy_code_end='.urlencode($line->numero_compte); + if (GETPOSTISSET('date_startmonth')) { + $urlzoom .= '&search_date_startmonth='.GETPOST('date_startmonth', 'int').'&search_date_startday='.GETPOST('date_startday', 'int').'&search_date_startyear='.GETPOST('date_startyear', 'int'); + } + if (GETPOSTISSET('date_endmonth')) { + $urlzoom .= '&search_date_endmonth='.GETPOST('date_endmonth', 'int').'&search_date_endday='.GETPOST('date_endday', 'int').'&search_date_endyear='.GETPOST('date_endyear', 'int'); + } + } + // Debit + print ''.price($line->debit).''; + // Credit + print ''.price($line->credit).''; + if (!empty($conf->global->ACCOUNTANCY_SHOW_OPENING_BALANCE)) { print ''.price(price2num($opening_balance + $line->debit - $line->credit, 'MT')).''; } else { diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index d0f43cfe3dd..e5a061d34bd 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -63,9 +63,11 @@ $accountingjournal->fetch(null, $journal_code); $journal_label = $accountingjournal->label; $subledger_account = GETPOST('subledger_account', 'alphanohtml'); -if ($subledger_account == - 1) { +if ($subledger_account == -1) { $subledger_account = null; } +$subledger_label = GETPOST('subledger_label', 'alphanohtml'); + $label_operation = GETPOST('label_operation', 'alphanohtml'); $debit = price2num(GETPOST('debit', 'alpha')); $credit = price2num(GETPOST('credit', 'alpha')); @@ -108,6 +110,7 @@ if ($action == "confirm_update") { } else { $object->numero_compte = $accountingaccount_number; $object->subledger_account = $subledger_account; + $object->subledger_label = $subledger_label; $object->label_compte = $accountingaccount_label; $object->label_operation = $label_operation; $object->debit = $debit; @@ -160,6 +163,7 @@ if ($action == "confirm_update") { $object->numero_compte = $accountingaccount_number; $object->subledger_account = $subledger_account; + $object->subledger_label = $subledger_label; $object->label_compte = $accountingaccount_label; $object->label_operation = $label_operation; $object->debit = $debit; @@ -224,9 +228,10 @@ if ($action == "confirm_update") { $action = 'create'; $error++; } - if (!GETPOST('next_num_mvt', 'alpha')) + if (!GETPOST('doc_ref', 'alpha')) { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NumPiece")), null, 'errors'); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Piece")), null, 'errors'); + $action = 'create'; $error++; } @@ -371,7 +376,7 @@ if ($action == 'create') print ''; print ''; - print ''.$langs->trans("Piece").''; + print ''.$langs->trans("Piece").''; print ''; print ''; @@ -577,7 +582,7 @@ if ($action == 'create') print '
'; - $result = $object->fetchAllPerMvt($piece_num, $mode); + $result = $object->fetchAllPerMvt($piece_num, $mode); // This load $object->linesmvt if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { @@ -594,7 +599,8 @@ if ($action == 'create') print ''."\n"; print ''."\n"; - print ""; + print '
'; + if (count($object->linesmvt) > 0) { $total_debit = 0; $total_credit = 0; @@ -616,18 +622,22 @@ if ($action == 'create') $total_credit += $line->credit; if ($action == 'update' && $line->id == $id) { + print ''; print ''; print ''; print ''; print ''; @@ -639,20 +649,24 @@ if ($action == 'create') } else { $accountingaccount->fetch(null, $line->numero_compte, true); print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; + print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 830896776b5..065c0b06d08 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -36,7 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("accountancy")); +$langs->loadLangs(array("accountancy", "compta")); $socid = GETPOST('socid', 'int'); @@ -87,7 +87,7 @@ $search_debit = GETPOST('search_debit', 'alpha'); $search_credit = GETPOST('search_credit', 'alpha'); $search_ledger_code = GETPOST('search_ledger_code', 'array'); $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); -$search_not_reconciled = GETPOST('search_reconciled_option', 'alpha'); +$search_not_reconciled = GETPOST('search_not_reconciled', 'alpha'); // Load variable for pagination $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); @@ -140,6 +140,7 @@ if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GE $arrayfields = array( 't.piece_num'=>array('label'=>$langs->trans("TransactionNumShort"), 'checked'=>1), + 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.doc_date'=>array('label'=>$langs->trans("Docdate"), 'checked'=>1), 't.doc_ref'=>array('label'=>$langs->trans("Piece"), 'checked'=>1), 't.numero_compte'=>array('label'=>$langs->trans("AccountAccountingShort"), 'checked'=>1), @@ -148,7 +149,6 @@ $arrayfields = array( 't.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1), 't.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1), 't.lettering_code'=>array('label'=>$langs->trans("LetteringCode"), 'checked'=>1), - 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.date_creation'=>array('label'=>$langs->trans("DateCreation"), 'checked'=>0), 't.tms'=>array('label'=>$langs->trans("DateModification"), 'checked'=>0), 't.date_export'=>array('label'=>$langs->trans("DateExport"), 'checked'=>1), @@ -661,11 +661,11 @@ if (empty($reshook)) { } $newcardbutton .= ''.$langs->trans("IncludeDocsAlreadyExported").''; - $newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export); + if (!empty($user->rights->accounting->mouvements->export)) $newcardbutton .= dolGetButtonTitle($buttonLabel, $langs->trans("ExportFilteredList").' ('.$listofformat[$formatexportset].')', 'fa fa-file-export paddingleft', $_SERVER["PHP_SELF"].'?action=export_file'.($param ? '&'.$param : ''), $user->rights->accounting->mouvements->export); $newcardbutton .= dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly')); - $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly')); $url = './card.php?action=create'; if (!empty($socid)) $url .= '&socid='.$socid; @@ -688,11 +688,17 @@ print '
'; print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->numero_compte), 'accountingaccount_number', 1, array(), 1, 1, ''); print ''; - // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not - // use setup of keypress to select thirdparty and this hang browser on large database. - if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) - { + // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because: + // It does not use the setup of "key pressed" to select a thirdparty and this hang browser on large databases. + // Also, it is not possible to use a value that is not in the list. + // Also, the label is not automatically filled when a value is selected. + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount((GETPOSTISSET("subledger_account") ? GETPOST("subledger_account", "alpha") : $line->subledger_account), 'subledger_account', 1); } else { - print 'subledger_account).'">'; + print 'subledger_account).'" placeholder="'.dol_escape_htmltag($langs->trans("SubledgerAccount")).'">'; } + // Add also input for subledger label + print '
subledger_label).'" placeholder="'.dol_escape_htmltag($langs->trans("SubledgerAccountLabel")).'">'; print '
label_operation).'">debit)).'">'.$accountingaccount->getNomUrl(0, 1, 1, '', 0).''.length_accounta($line->subledger_account).''.length_accounta($line->subledger_account); + if ($line->subledger_label) { + print ' - '.$line->subledger_label.''; + } + print ''.$line->label_operation.''.price($line->debit).''.price($line->credit).''; - print 'id.'&piece_num='.$line->piece_num.'&mode='.$mode.'">'; + print 'id.'&piece_num='.urlencode($line->piece_num).'&mode='.urlencode($mode).'&token='.urlencode(newToken()).'">'; print img_edit('', 0, 'class="marginrightonly"'); print '  '; $actiontodelete = 'delete'; if ($mode == '_tmp' || $action != 'delmouv') $actiontodelete = 'confirm_delete'; - print ''; + print ''; print img_delete(); print ''; @@ -671,18 +685,21 @@ if ($action == 'create') if ($action == "" || $action == 'add') { print '
'; print $formaccounting->select_account('', 'accountingaccount_number', 1, array(), 1, 1, ''); print ''; - // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because it does not - // use setup of keypress to select thirdparty and this hang browser on large database. - if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) - { + // TODO For the moment we keep a free input text instead of a combo. The select_auxaccount has problem because: + // It does not use the setup of "key pressed" to select a thirdparty and this hang browser on large databases. + // Also, it is not possible to use a value that is not in the list. + // Also, the label is not automatically filled when a value is selected. + if (!empty($conf->global->ACCOUNTANCY_COMBO_FOR_AUX)) { print $formaccounting->select_auxaccount('', 'subledger_account', 1); } else { - print ''; + print ''; } + print '
'; print '
'; // Filters lines print ''; + // Movement number if (!empty($arrayfields['t.piece_num']['checked'])) { print ''; } +// Code journal +if (!empty($arrayfields['t.code_journal']['checked'])) +{ + print ''; +} // Date document if (!empty($arrayfields['t.doc_date']['checked'])) { @@ -778,14 +784,7 @@ if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; -} -// Code journal -if (!empty($arrayfields['t.code_journal']['checked'])) -{ - print ''; } @@ -839,6 +838,7 @@ print "\n"; print ''; if (!empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, "", $sortfield, $sortorder); +if (!empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['t.numero_compte']['checked'])) print_liste_field_titre($arrayfields['t.numero_compte']['label'], $_SERVER['PHP_SELF'], "t.numero_compte", "", $param, "", $sortfield, $sortorder); @@ -847,7 +847,6 @@ if (!empty($arrayfields['t.label_operation']['checked'])) print_liste_field_tit if (!empty($arrayfields['t.debit']['checked'])) print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.credit']['checked'])) print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.lettering_code']['checked'])) print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook @@ -913,6 +912,16 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } + // Journal code + if (!empty($arrayfields['t.code_journal']['checked'])) + { + $accountingjournal = new AccountingJournal($db); + $result = $accountingjournal->fetch('', $line->code_journal); + $journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal); + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Document date if (!empty($arrayfields['t.doc_date']['checked'])) { @@ -1040,16 +1049,6 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } - // Journal code - if (!empty($arrayfields['t.code_journal']['checked'])) - { - $accountingjournal = new AccountingJournal($db); - $result = $accountingjournal->fetch('', $line->code_journal); - $journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal); - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Fields from hook $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index 34a6b2d5ffd..9e62f9e0b79 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -48,6 +48,14 @@ $search_date_endday = GETPOST('search_date_endday', 'int'); $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); $search_date_end = dol_mktime(0, 0, 0, $search_date_endmonth, $search_date_endday, $search_date_endyear); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); +$search_date_export_startyear = GETPOST('search_date_export_startyear', 'int'); +$search_date_export_startmonth = GETPOST('search_date_export_startmonth', 'int'); +$search_date_export_startday = GETPOST('search_date_export_startday', 'int'); +$search_date_export_endyear = GETPOST('search_date_export_endyear', 'int'); +$search_date_export_endmonth = GETPOST('search_date_export_endmonth', 'int'); +$search_date_export_endday = GETPOST('search_date_export_endday', 'int'); +$search_date_export_start = dol_mktime(0, 0, 0, $search_date_export_startmonth, $search_date_export_startday, $search_date_export_startyear); +$search_date_export_end = dol_mktime(0, 0, 0, $search_date_export_endmonth, $search_date_export_endday, $search_date_export_endyear); $search_accountancy_code = GETPOST("search_accountancy_code"); $search_accountancy_code_start = GETPOST('search_accountancy_code_start', 'alpha'); @@ -66,7 +74,7 @@ $search_ledger_code = GETPOST('search_ledger_code', 'array'); $search_debit = GETPOST('search_debit', 'alpha'); $search_credit = GETPOST('search_credit', 'alpha'); $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); -$search_not_reconciled = GETPOST('search_reconciled_option', 'alpha'); +$search_not_reconciled = GETPOST('search_not_reconciled', 'alpha'); if (GETPOST("button_delmvt_x") || GETPOST("button_delmvt.x") || GETPOST("button_delmvt")) { $action = 'delbookkeepingyear'; @@ -120,14 +128,15 @@ if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('searc $arrayfields = array( // 't.subledger_account'=>array('label'=>$langs->trans("SubledgerAccount"), 'checked'=>1), - 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.piece_num'=>array('label'=>$langs->trans("TransactionNumShort"), 'checked'=>1), + 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.doc_date'=>array('label'=>$langs->trans("Docdate"), 'checked'=>1), 't.doc_ref'=>array('label'=>$langs->trans("Piece"), 'checked'=>1), 't.label_operation'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 't.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1), 't.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1), 't.lettering_code'=>array('label'=>$langs->trans("LetteringCode"), 'checked'=>1), + 't.date_export'=>array('label'=>$langs->trans("DateExport"), 'checked'=>1), ); if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']); @@ -181,6 +190,14 @@ if (empty($reshook)) $search_date_endyear = ''; $search_date_endmonth = ''; $search_date_endday = ''; + $search_date_export_start = ''; + $search_date_export_end = ''; + $search_date_export_startyear = ''; + $search_date_export_startmonth = ''; + $search_date_export_startday = ''; + $search_date_export_endyear = ''; + $search_date_export_endmonth = ''; + $search_date_export_endday = ''; $search_debit = ''; $search_credit = ''; $search_lettering_code = ''; @@ -253,6 +270,14 @@ if (empty($reshook)) $filter['t.reconciled_option'] = $search_not_reconciled; $param .= '&search_not_reconciled='.urlencode($search_not_reconciled); } + if (!empty($search_date_export_start)) { + $filter['t.date_export>='] = $search_date_export_start; + $param .= '&search_date_export_startmonth='.$search_date_export_startmonth.'&search_date_export_startday='.$search_date_export_startday.'&search_date_export_startyear='.$search_date_export_startyear; + } + if (!empty($search_date_export_end)) { + $filter['t.date_export<='] = $search_date_export_end; + $param .= '&search_date_export_endmonth='.$search_date_export_endmonth.'&search_date_export_endday='.$search_date_export_endday.'&search_date_export_endyear='.$search_date_export_endyear; + } } if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->supprimer) { @@ -403,7 +428,7 @@ $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $obj if (empty($reshook)) { $newcardbutton = dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); - $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly')); $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?action=create'); } @@ -448,6 +473,11 @@ print '
'; print ''; - print '
'.$langs->trans("NotReconciled").''; - print '
'; - print $formaccounting->multi_select_journal($search_ledger_code, 'search_ledger_code', 0, 1, 1, 1); + print '
'.$langs->trans("NotReconciled").''; print '
'.$journaltoshow.''.$journaltoshow.'
'; // Filters lines print ''; +// Movement number +if (!empty($arrayfields['t.piece_num']['checked'])) +{ + print ''; +} // Code journal if (!empty($arrayfields['t.code_journal']['checked'])) { print ''; } -// Movement number -if (!empty($arrayfields['t.piece_num']['checked'])) -{ - print ''; -} // Ref document if (!empty($arrayfields['t.doc_ref']['checked'])) { print ''; @@ -491,7 +516,18 @@ if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; +} +// Date export +if (!empty($arrayfields['t.date_export']['checked'])) { + print ''; } @@ -508,14 +544,15 @@ print ''; print "\n"; print ''; +if (!empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); if (!empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['t.label_operation']['checked'])) print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); if (!empty($arrayfields['t.debit']['checked'])) print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.credit']['checked'])) print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); if (!empty($arrayfields['t.lettering_code']['checked'])) print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.date_export']['checked'])) print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center '); // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook @@ -546,13 +583,12 @@ while ($i < min($num, $limit)) // Is it a break ? if ($accountg != $displayed_account_number || !isset($displayed_account_number)) { - if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { - $colnumber = 3; - $colnumberend = 7; - } else { - $colnumber = 4; - $colnumberend = 7; - } + $colnumber = 5; + $colnumberend = 7; + + if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) $colnumber--; + if (empty($arrayfields['t.date_export']['checked'])) $colnumber--; + $colspan = $totalarray['nbfield'] - $colnumber; $colspanend = $totalarray['nbfield'] - $colnumberend; // Show a subtotal by accounting account @@ -585,7 +621,7 @@ while ($i < min($num, $limit)) // Show the break account print ""; - print ''; @@ -601,6 +637,17 @@ while ($i < min($num, $limit)) print ''; + // Piece number + if (!empty($arrayfields['t.piece_num']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Journal code if (!empty($arrayfields['t.code_journal']['checked'])) { @@ -618,17 +665,6 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } - // Piece number - if (!empty($arrayfields['t.piece_num']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Document ref if (!empty($arrayfields['t.doc_ref']['checked'])) { @@ -735,6 +771,13 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } + // Exported operation date + if (!empty($arrayfields['t.date_export']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + // Fields from hook $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook @@ -763,14 +806,6 @@ while ($i < min($num, $limit)) } if ($num > 0) { - // Show sub-total of last shown account - if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { - $colnumber = 3; - $colnumberend = 7; - } else { - $colnumber = 4; - $colnumberend = 7; - } $colspan = $totalarray['nbfield'] - $colnumber; $colspanend = $totalarray['nbfield'] - $colnumberend; print ''; diff --git a/htdocs/accountancy/bookkeeping/listbysubaccount.php b/htdocs/accountancy/bookkeeping/listbysubaccount.php index e30a9984949..01b1a0a1335 100644 --- a/htdocs/accountancy/bookkeeping/listbysubaccount.php +++ b/htdocs/accountancy/bookkeeping/listbysubaccount.php @@ -3,7 +3,7 @@ * Copyright (C) 2013-2016 Olivier Geffroy * Copyright (C) 2013-2020 Florian Henry * Copyright (C) 2013-2020 Alexandre Spangaro - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2020 Frédéric 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 @@ -39,15 +39,23 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array("accountancy", "compta")); $action = GETPOST('action', 'aZ09'); -$search_date_startyear = GETPOST('search_date_startyear', 'int'); -$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); -$search_date_startday = GETPOST('search_date_startday', 'int'); -$search_date_endyear = GETPOST('search_date_endyear', 'int'); -$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); -$search_date_endday = GETPOST('search_date_endday', 'int'); +$search_date_startyear = GETPOST('search_date_startyear', 'int'); +$search_date_startmonth = GETPOST('search_date_startmonth', 'int'); +$search_date_startday = GETPOST('search_date_startday', 'int'); +$search_date_endyear = GETPOST('search_date_endyear', 'int'); +$search_date_endmonth = GETPOST('search_date_endmonth', 'int'); +$search_date_endday = GETPOST('search_date_endday', 'int'); $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); $search_date_end = dol_mktime(0, 0, 0, $search_date_endmonth, $search_date_endday, $search_date_endyear); $search_doc_date = dol_mktime(0, 0, 0, GETPOST('doc_datemonth', 'int'), GETPOST('doc_dateday', 'int'), GETPOST('doc_dateyear', 'int')); +$search_date_export_startyear = GETPOST('search_date_export_startyear', 'int'); +$search_date_export_startmonth = GETPOST('search_date_export_startmonth', 'int'); +$search_date_export_startday = GETPOST('search_date_export_startday', 'int'); +$search_date_export_endyear = GETPOST('search_date_export_endyear', 'int'); +$search_date_export_endmonth = GETPOST('search_date_export_endmonth', 'int'); +$search_date_export_endday = GETPOST('search_date_export_endday', 'int'); +$search_date_export_start = dol_mktime(0, 0, 0, $search_date_export_startmonth, $search_date_export_startday, $search_date_export_startyear); +$search_date_export_end = dol_mktime(0, 0, 0, $search_date_export_endmonth, $search_date_export_endday, $search_date_export_endyear); $search_accountancy_code = GETPOST("search_accountancy_code"); $search_accountancy_code_start = GETPOST('search_accountancy_code_start', 'alpha'); @@ -66,23 +74,29 @@ $search_ledger_code = GETPOST('search_ledger_code', 'array'); $search_debit = GETPOST('search_debit', 'alpha'); $search_credit = GETPOST('search_credit', 'alpha'); $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); -$search_not_reconciled = GETPOST('search_reconciled_option', 'alpha'); +$search_not_reconciled = GETPOST('search_not_reconciled', 'alpha'); if (GETPOST("button_delmvt_x") || GETPOST("button_delmvt.x") || GETPOST("button_delmvt")) { $action = 'delbookkeepingyear'; } // Load variable for pagination -$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (empty($conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION) ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page < 0) { $page = 0; } +if (empty($page) || $page < 0) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") $sortorder = "ASC"; -if ($sortfield == "") $sortfield = "t.doc_date,t.rowid"; +if ($sortorder == "") { + $sortorder = "ASC"; +} +if ($sortfield == "") { + $sortfield = "t.doc_date,t.rowid"; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new BookKeeping($db); @@ -105,11 +119,12 @@ if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('searc } else { $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); $year_start = dol_print_date(dol_now(), '%Y'); - if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year + if (dol_print_date(dol_now(), '%m') < $month_start) { + $year_start--; // If current month is lower that starting fiscal month, we start last year + } $year_end = $year_start + 1; $month_end = $month_start - 1; - if ($month_end < 1) - { + if ($month_end < 1) { $month_end = 12; $year_end--; } @@ -120,17 +135,20 @@ if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('searc $arrayfields = array( // 't.subledger_account'=>array('label'=>$langs->trans("SubledgerAccount"), 'checked'=>1), - 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.piece_num'=>array('label'=>$langs->trans("TransactionNumShort"), 'checked'=>1), + 't.code_journal'=>array('label'=>$langs->trans("Codejournal"), 'checked'=>1), 't.doc_date'=>array('label'=>$langs->trans("Docdate"), 'checked'=>1), 't.doc_ref'=>array('label'=>$langs->trans("Piece"), 'checked'=>1), 't.label_operation'=>array('label'=>$langs->trans("Label"), 'checked'=>1), 't.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1), 't.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1), 't.lettering_code'=>array('label'=>$langs->trans("LetteringCode"), 'checked'=>1), + 't.date_export'=>array('label'=>$langs->trans("DateExport"), 'checked'=>1), ); -if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) unset($arrayfields['t.lettering_code']); +if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING)) { + unset($arrayfields['t.lettering_code']); +} if ($search_date_start && empty($search_date_startyear)) { $tmparray = dol_getdate($search_date_start); @@ -149,19 +167,23 @@ if ($search_date_end && empty($search_date_endyear)) { /* * Action */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array('socid'=>$socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $search_doc_date = ''; $search_accountancy_code = ''; $search_accountancy_code_start = ''; @@ -180,6 +202,14 @@ if (empty($reshook)) $search_date_endyear = ''; $search_date_endmonth = ''; $search_date_endday = ''; + $search_date_export_start = ''; + $search_date_export_end = ''; + $search_date_export_startyear = ''; + $search_date_export_startmonth = ''; + $search_date_export_startday = ''; + $search_date_export_endyear = ''; + $search_date_export_endmonth = ''; + $search_date_export_endday = ''; $search_debit = ''; $search_credit = ''; $search_lettering_code = ''; @@ -252,6 +282,14 @@ if (empty($reshook)) $filter['t.reconciled_option'] = $search_not_reconciled; $param .= '&search_not_reconciled='.urlencode($search_not_reconciled); } + if (!empty($search_date_export_start)) { + $filter['t.date_export>='] = $search_date_export_start; + $param .= '&search_date_export_startmonth='.$search_date_export_startmonth.'&search_date_export_startday='.$search_date_export_startday.'&search_date_export_startyear='.$search_date_export_startyear; + } + if (!empty($search_date_export_end)) { + $filter['t.date_export<='] = $search_date_export_end; + $param .= '&search_date_export_endmonth='.$search_date_export_endmonth.'&search_date_export_endday='.$search_date_export_endday.'&search_date_export_endyear='.$search_date_export_endyear; + } } if ($action == 'delbookkeeping' && $user->rights->accounting->mouvements->supprimer) { @@ -279,8 +317,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme $deljournal = 0; } - if (!empty($delmonth) || !empty($delyear) || !empty($deljournal)) - { + if (!empty($delmonth) || !empty($delyear) || !empty($deljournal)) { $result = $object->deleteByYearAndJournal($delyear, $deljournal, '', ($delmonth > 0 ? $delmonth : 0)); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -289,7 +326,7 @@ if ($action == 'delbookkeepingyearconfirm' && $user->rights->accounting->mouveme } // Make a redirect to avoid to launch the delete later after a back button - header("Location: listbysubaccount.php".($param ? '?'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"].($param ? '?'.$param : '')); exit; } else { setEventMessages("NoRecordDeleted", null, 'warnings'); @@ -306,7 +343,7 @@ if ($action == 'delmouvconfirm' && $user->rights->accounting->mouvements->suppri setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs'); } - header("Location: listbysubaccount.php?noreset=1".($param ? '&'.$param : '')); + header("Location: ".$_SERVER["PHP_SELF"]."?noreset=1".($param ? '&'.$param : '')); exit; } } @@ -393,7 +430,9 @@ if ($action == 'delbookkeepingyear') { print '
'; print ''; print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -403,14 +442,17 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook if (empty($reshook)) { $newcardbutton = dolGetButtonTitle($langs->trans('ViewFlatList'), '', 'fa fa-list paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/list.php?'.$param); - $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php', '', 1, array('morecss' => 'marginleftonly')); - $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php', '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); - + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupByAccountAccounting'), '', 'fa fa-stream paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbyaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly')); + $newcardbutton .= dolGetButtonTitle($langs->trans('GroupBySubAccountAccounting'), '', 'fa fa-align-left vmirror paddingleft imgforviewmode', DOL_URL_ROOT.'/accountancy/bookkeeping/listbysubaccount.php?'.$param, '', 1, array('morecss' => 'marginleftonly btnTitleSelected')); $newcardbutton .= dolGetButtonTitle($langs->trans('NewAccountingMvt'), '', 'fa fa-plus-circle paddingleft', DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?action=create'); } -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} print_barre_liste($title_page, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $result, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -418,11 +460,16 @@ print info_admin($langs->trans("WarningRecordWithoutSubledgerAreExcluded")); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} // Reverse sort order -if (preg_match('/^asc/i', $sortorder)) $sortorder = "asc"; -else $sortorder = "desc"; +if (preg_match('/^asc/i', $sortorder)) { + $sortorder = "asc"; +} else { + $sortorder = "desc"; +} $moreforfilter = ''; @@ -439,8 +486,11 @@ $moreforfilter .= ''; $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook -if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; -else $moreforfilter = $hookmanager->resPrint; +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} print '
'; print $moreforfilter; @@ -452,6 +502,11 @@ print '
'; @@ -465,11 +495,6 @@ if (!empty($arrayfields['t.doc_date']['checked'])) { print ''; print ''; print ''; - print '
'.$langs->trans("NotReconciled").''; + print '
'.$langs->trans("NotReconciled").''; + print '
'; + print '
'; + print $form->selectDate($search_date_export_start, 'search_date_export_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); + print '
'; + print '
'; + print $form->selectDate($search_date_export_end, 'search_date_export_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); + print '
'; print '
'; + print ''; if ($line->numero_compte != "" && $line->numero_compte != '-1') print length_accountg($line->numero_compte).' : '.$object->get_compte_desc($line->numero_compte); else print ''.$langs->trans("Unknown").''; print '
'; + $object->id = $line->id; + $object->piece_num = $line->piece_num; + print $object->getNomUrl(1, '', 0, '', 1); + print ''; - $object->id = $line->id; - $object->piece_num = $line->piece_num; - print $object->getNomUrl(1, '', 0, '', 1); - print ''.dol_print_date($line->date_export, 'dayhour').'
'; // Filters lines print ''; +// Movement number +if (!empty($arrayfields['t.piece_num']['checked'])) +{ + print ''; +} // Code journal if (!empty($arrayfields['t.code_journal']['checked'])) { print ''; } -// Movement number -if (!empty($arrayfields['t.piece_num']['checked'])) -{ - print ''; -} // Ref document if (!empty($arrayfields['t.doc_ref']['checked'])) { print ''; @@ -491,11 +541,21 @@ if (!empty($arrayfields['t.credit']['checked'])) { print ''; } // Lettering code -if (!empty($arrayfields['t.lettering_code']['checked'])) -{ +if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''; +} +// Date export +if (!empty($arrayfields['t.date_export']['checked'])) { + print ''; } @@ -512,14 +572,33 @@ print ''; print "\n"; print ''; -if (!empty($arrayfields['t.code_journal']['checked'])) print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.doc_date']['checked'])) print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['t.piece_num']['checked'])) print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['t.doc_ref']['checked'])) print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.label_operation']['checked'])) print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['t.debit']['checked'])) print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['t.credit']['checked'])) print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['t.lettering_code']['checked'])) print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['t.piece_num']['checked'])) { + print_liste_field_titre($arrayfields['t.piece_num']['label'], $_SERVER['PHP_SELF'], "t.piece_num", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.code_journal']['checked'])) { + print_liste_field_titre($arrayfields['t.code_journal']['label'], $_SERVER['PHP_SELF'], "t.code_journal", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.doc_date']['checked'])) { + print_liste_field_titre($arrayfields['t.doc_date']['label'], $_SERVER['PHP_SELF'], "t.doc_date", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.doc_ref']['checked'])) { + print_liste_field_titre($arrayfields['t.doc_ref']['label'], $_SERVER['PHP_SELF'], "t.doc_ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.label_operation']['checked'])) { + print_liste_field_titre($arrayfields['t.label_operation']['label'], $_SERVER['PHP_SELF'], "t.label_operation", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['t.debit']['checked'])) { + print_liste_field_titre($arrayfields['t.debit']['label'], $_SERVER['PHP_SELF'], "t.debit", "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['t.credit']['checked'])) { + print_liste_field_titre($arrayfields['t.credit']['label'], $_SERVER['PHP_SELF'], "t.credit", "", $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['t.lettering_code']['checked'])) { + print_liste_field_titre($arrayfields['t.lettering_code']['label'], $_SERVER['PHP_SELF'], "t.lettering_code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['t.date_export']['checked'])) { + print_liste_field_titre($arrayfields['t.date_export']['label'], $_SERVER['PHP_SELF'], "t.date_export", "", $param, '', $sortfield, $sortorder, 'center '); +} // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook @@ -538,8 +617,7 @@ $displayed_account_number = null; // Start with undefined to be able to distingu // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $line = $object->lines[$i]; $total_debit += $line->debit; @@ -550,15 +628,15 @@ while ($i < min($num, $limit)) // Is it a break ? if ($accountg != $displayed_account_number || !isset($displayed_account_number)) { - if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { - $colnumber = 3; - $colnumberend = 7; - } else { - $colnumber = 4; - $colnumberend = 7; - } + $colnumber = 5; + $colnumberend = 7; + + if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) $colnumber--; + if (empty($arrayfields['t.date_export']['checked'])) $colnumber--; + $colspan = $totalarray['nbfield'] - $colnumber; $colspanend = $totalarray['nbfield'] - $colnumberend; + // Show a subtotal by accounting account if (isset($displayed_account_number)) { print ''; @@ -571,8 +649,7 @@ while ($i < min($num, $limit)) $balance = $sous_total_debit - $sous_total_credit; print ''; print ''; - if ($balance > 0) - { + if ($balance > 0) { print ''; @@ -589,14 +666,18 @@ while ($i < min($num, $limit)) // Show the break account print ""; - print ''; - // Journal code - if (!empty($arrayfields['t.code_journal']['checked'])) - { - $accountingjournal = new AccountingJournal($db); - $result = $accountingjournal->fetch('', $line->code_journal); - $journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal); - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Document date - if (!empty($arrayfields['t.doc_date']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - // Piece number - if (!empty($arrayfields['t.piece_num']['checked'])) - { + if (!empty($arrayfields['t.piece_num']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } + } + + // Journal code + if (!empty($arrayfields['t.code_journal']['checked'])) { + $accountingjournal = new AccountingJournal($db); + $result = $accountingjournal->fetch('', $line->code_journal); + $journaltoshow = (($result > 0) ? $accountingjournal->getNomUrl(0, 0, 0, '', 0) : $line->code_journal); + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + // Document date + if (!empty($arrayfields['t.doc_date']['checked'])) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } } // Document ref - if (!empty($arrayfields['t.doc_ref']['checked'])) - { - if ($line->doc_type == 'customer_invoice') - { + if (!empty($arrayfields['t.doc_ref']['checked'])) { + if ($line->doc_type == 'customer_invoice') { $langs->loadLangs(array('bills')); require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; @@ -657,8 +739,7 @@ while ($i < min($num, $limit)) $filedir = $conf->facture->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - } elseif ($line->doc_type == 'supplier_invoice') - { + } elseif ($line->doc_type == 'supplier_invoice') { $langs->loadLangs(array('bills')); require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; @@ -670,8 +751,7 @@ while ($i < min($num, $limit)) $filedir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($line->fk_doc, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref); $subdir = get_exdir($objectstatic->id, 2, 0, 0, $objectstatic, $modulepart).dol_sanitizeFileName($line->doc_ref); $documentlink = $formfile->getDocumentsLink($objectstatic->element, $subdir, $filedir); - } elseif ($line->doc_type == 'expense_report') - { + } elseif ($line->doc_type == 'expense_report') { $langs->loadLangs(array('trips')); require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; @@ -683,8 +763,7 @@ while ($i < min($num, $limit)) $filedir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($line->doc_ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$objectstatic->id; $documentlink = $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); - } elseif ($line->doc_type == 'bank') - { + } elseif ($line->doc_type == 'bank') { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $objectstatic = new AccountLine($db); $objectstatic->fetch($line->fk_doc); @@ -698,8 +777,7 @@ while ($i < min($num, $limit)) // Picto + Ref print '
'; @@ -469,11 +524,6 @@ if (!empty($arrayfields['t.doc_date']['checked'])) { print ''; print ''; print ''; - print '
'.$langs->trans("NotReconciled").''; + print '
'.$langs->trans("NotReconciled").''; + print '
'; + print '
'; + print $form->selectDate($search_date_export_start, 'search_date_export_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); + print '
'; + print '
'; + print $form->selectDate($search_date_export_end, 'search_date_export_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); + print '
'; print '
'.$langs->trans("Balance").':'; print price($sous_total_debit - $sous_total_credit); print '
'; + print ''; if ($line->subledger_account != "" && $line->subledger_account != '-1') { print $object->get_compte_desc($line->numero_compte).' : '.length_accounta($line->subledger_account); } else { // Should not happen: subledger account must be null or a non empty value print ''.$langs->trans("Unknown"); - if ($line->subledger_label) print ' ('.$line->subledger_label.')'; - $htmltext = 'EmptyStringForSubledgerAccountButSubledgerLabelDefined'; + if ($line->subledger_label) { + print ' ('.$line->subledger_label.')'; + $htmltext = 'EmptyStringForSubledgerAccountButSubledgerLabelDefined'; + } else { + $htmltext = 'EmptyStringForSubledgerAccountAndSubledgerLabel'; + } print $form->textwithpicto('', $htmltext); print ''; } @@ -613,39 +694,40 @@ while ($i < min($num, $limit)) print '
'.$journaltoshow.''.dol_print_date($line->doc_date, 'day').''; $object->id = $line->id; $object->piece_num = $line->piece_num; print $object->getNomUrl(1, '', 0, '', 1); print ''.$journaltoshow.''.dol_print_date($line->doc_date, 'day').''; - if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') - { + if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') { print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); print $documentlink; } elseif ($line->doc_type == 'bank') { @@ -712,7 +790,9 @@ while ($i < min($num, $limit)) print '
'; print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label operation @@ -720,30 +800,47 @@ while ($i < min($num, $limit)) // Affiche un lien vers la facture client/fournisseur $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); print strlen(length_accounta($line->subledger_account)) == 0 ? ''.$line->label_operation.'' : ''.$line->label_operation.'
('.length_accounta($line->subledger_account).')'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount debit - if (!empty($arrayfields['t.debit']['checked'])) - { + if (!empty($arrayfields['t.debit']['checked'])) { print ''.($line->debit ? price($line->debit) : '').''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totaldebit'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totaldebit'; + } $totalarray['val']['totaldebit'] += $line->debit; } // Amount credit if (!empty($arrayfields['t.credit']['checked'])) { print ''.($line->credit ? price($line->credit) : '').''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit'; + } $totalarray['val']['totalcredit'] += $line->credit; } // Lettering code - if (!empty($arrayfields['t.lettering_code']['checked'])) - { + if (!empty($arrayfields['t.lettering_code']['checked'])) { print ''.$line->lettering_code.''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + // Exported operation date + if (!empty($arrayfields['t.date_export']['checked'])) + { + print ''.dol_print_date($line->date_export, 'dayhour').''; if (!$i) $totalarray['nbfield']++; } @@ -763,7 +860,9 @@ while ($i < min($num, $limit)) } } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } // Comptabilise le sous-total $sous_total_debit += $line->debit; @@ -775,14 +874,6 @@ while ($i < min($num, $limit)) } if ($num > 0) { - // Show sub-total of last shown account - if (empty($conf->global->ACCOUNTING_ENABLE_LETTERING) || empty($arrayfields['t.lettering_code']['checked'])) { - $colnumber = 3; - $colnumberend = 7; - } else { - $colnumber = 4; - $colnumberend = 7; - } $colspan = $totalarray['nbfield'] - $colnumber; $colspanend = $totalarray['nbfield'] - $colnumberend; print ''; @@ -795,8 +886,7 @@ if ($num > 0) { $balance = $sous_total_debit - $sous_total_credit; print ''; print ''.$langs->trans("Balance").':'; - if ($balance > 0) - { + if ($balance > 0) { print ''; print price($sous_total_debit - $sous_total_credit); print ''; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php index e831e21f814..2d90c9a7b14 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_customer.php @@ -4,7 +4,7 @@ * Copyright (C) 2013 Olivier Geffroy * Copyright (C) 2013 Florian Henry * Copyright (C) 2013-2019 Alexandre Spangaro - * Copyright (C) 2018-2019 Frédéric France + * Copyright (C) 2018-2020 Frédéric 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 @@ -37,14 +37,17 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // Load translation files required by the page $langs->loadLangs(array("compta", "accountancy")); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); -$confirm = GETPOST('confirm', 'alpha'); -$toselect = GETPOST('toselect', 'array'); -$socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('id', 'int'); +$confirm = GETPOST('confirm', 'alpha'); +$toselect = GETPOST('toselect', 'array'); +// $socid = GETPOST('socid', 'int') ?GETPOST('socid', 'int') : GETPOST('id', 'int'); +// Security check +$socid = GETPOSTINT("socid"); +// if ($user->socid) $socid=$user->socid; -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$limit = GETPOSTISSET('limit') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -54,10 +57,12 @@ if (empty($page) || $page == - 1) { $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") +if ($sortorder == "") { $sortorder = "ASC"; -if ($sortfield == "") +} +if ($sortfield == "") { $sortfield = "bk.doc_date"; +} /* $search_date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); @@ -74,23 +79,18 @@ if (!empty($lettering)) { /* if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_date_start = ''; - $search_date_end = ''; + $search_date_start = ''; + $search_date_end = ''; //$search_doc_type = ''; $search_doc_ref = ''; } */ -// Security check -$socid = GETPOST("socid", 'int'); -// if ($user->socid) $socid=$user->socid; - $lettering = new Lettering($db); $object = new Societe($db); $object->id = $socid; $result = $object->fetch($socid); -if ($result < 0) -{ +if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -208,30 +208,30 @@ if ($resql) { print ''."\n"; /* - print ''; - //print ''; + print ''; + //print ''; - // Date - print ''; + // Date + print ''; - // Piece - print ''; + // Piece + print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; */ print ''; @@ -251,7 +251,9 @@ if ($resql) { $tmp = ''; while ($obj = $db->fetch_object($resql)) { - if ($tmp != $obj->lettering_code || empty($tmp)) $tmp = $obj->lettering_code; + if ($tmp != $obj->lettering_code || empty($tmp)) { + $tmp = $obj->lettering_code; + } /*if ($tmp != $obj->lettering_code || empty($obj->lettering_code))*/ $solde += ($obj->credit - $obj->debit); print ''; diff --git a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php index b5620f3ec25..31acb9f0191 100644 --- a/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php +++ b/htdocs/accountancy/bookkeeping/thirdparty_lettering_supplier.php @@ -41,7 +41,11 @@ $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); -$socid = GETPOST('socid', 'int') ? ((int) GETPOST('socid', 'int')) : ((int) GETPOST('id', 'int')); +// $socid = GETPOST('socid', 'int') ? ((int) GETPOST('socid', 'int')) : ((int) GETPOST('id', 'int')); +// Security check +$socid = GETPOSTINT("socid"); +// if ($user->socid) $socid=$user->socid; + $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); @@ -53,10 +57,12 @@ if (empty($page) || $page == - 1) { $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($sortorder == "") +if ($sortorder == "") { $sortorder = "ASC"; -if ($sortfield == "") +} +if ($sortfield == "") { $sortfield = "bk.doc_date"; +} /* $search_date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int')); @@ -73,24 +79,18 @@ if (!empty($lettering)) { /* if (GETPOST('button_removefilter_x','alpha') || GETPOST('button_removefilter.x','alpha') || GETPOST('button_removefilter','alpha')) // All tests are required to be compatible with all browsers { - $search_date_start = ''; - $search_date_end = ''; + $search_date_start = ''; + $search_date_end = ''; //$search_doc_type=''; $search_doc_ref=''; } */ - -// Security check -$socid = GETPOST("socid", 'int'); -// if ($user->socid) $socid=$user->socid; - $lettering = new Lettering($db); $object = new Societe($db); $object->id = $socid; $result = $object->fetch($socid); -if ($result < 0) -{ +if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } @@ -159,8 +159,7 @@ $solde = 0; // Count total nb of records and calc total sum $nbtotalofrecords = ''; $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -206,30 +205,30 @@ if ($resql) { print '
'; - print '
'; - print $langs->trans('From') . ' '; - print $form->selectDate($search_date_start, 'date_creation_start', 0, 0, 1); - print '
'; - print '
'; - print $langs->trans('to') . ' '; - print $form->selectDate($search_date_end, 'date_creation_end', 0, 0, 1); - print '
'; - print '
'; + print '
'; + print $langs->trans('From') . ' '; + print $form->selectDate($search_date_start, 'date_creation_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to') . ' '; + print $form->selectDate($search_date_end, 'date_creation_end', 0, 0, 1); + print '
'; + print '
 '; - $searchpicto = $form->showFilterButtons(); - print $searchpicto; - print '
 '; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'."\n"; /* - print ''; - //print ''; + print ''; + //print ''; - // Date - print ''; + // Date + print ''; - // Piece - print ''; + // Piece + print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; */ print ''; @@ -248,7 +247,9 @@ if ($resql) { $solde = 0; $tmp = ''; while ($obj = $db->fetch_object($resql)) { - if ($tmp != $obj->lettering_code || empty($tmp)) $tmp = $obj->lettering_code; + if ($tmp != $obj->lettering_code || empty($tmp)) { + $tmp = $obj->lettering_code; + } /*if ($tmp != $obj->lettering_code || empty($obj->lettering_code))*/ $solde += ($obj->credit - $obj->debit); print ''; diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 201e3cac95a..382b7ee6f62 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -57,8 +57,8 @@ class AccountancyExport public static $EXPORT_TYPE_OPENCONCERTO = 100; public static $EXPORT_TYPE_LDCOMPTA = 110; public static $EXPORT_TYPE_LDCOMPTA10 = 120; - public static $EXPORT_TYPE_GESTINUMV3 = 130; - public static $EXPORT_TYPE_GESTINUMV5 = 135; + public static $EXPORT_TYPE_GESTIMUMV3 = 130; + public static $EXPORT_TYPE_GESTIMUMV5 = 135; public static $EXPORT_TYPE_FEC = 1000; public static $EXPORT_TYPE_FEC2 = 1010; @@ -119,8 +119,8 @@ class AccountancyExport self::$EXPORT_TYPE_CHARLEMAGNE => $langs->trans('Modelcsv_charlemagne'), self::$EXPORT_TYPE_LDCOMPTA => $langs->trans('Modelcsv_LDCompta'), self::$EXPORT_TYPE_LDCOMPTA10 => $langs->trans('Modelcsv_LDCompta10'), - self::$EXPORT_TYPE_GESTINUMV3 => $langs->trans('Modelcsv_Gestinum_v3'), - self::$EXPORT_TYPE_GESTINUMV5 => $langs->trans('Modelcsv_Gestinum_v5'), + self::$EXPORT_TYPE_GESTIMUMV3 => $langs->trans('Modelcsv_Gestinum_v3'), + self::$EXPORT_TYPE_GESTIMUMV5 => $langs->trans('Modelcsv_Gestinum_v5'), self::$EXPORT_TYPE_FEC => $langs->trans('Modelcsv_FEC'), self::$EXPORT_TYPE_FEC2 => $langs->trans('Modelcsv_FEC2'), ); @@ -154,8 +154,8 @@ class AccountancyExport self::$EXPORT_TYPE_CHARLEMAGNE => 'charlemagne', self::$EXPORT_TYPE_LDCOMPTA => 'ldcompta', self::$EXPORT_TYPE_LDCOMPTA10 => 'ldcompta10', - self::$EXPORT_TYPE_GESTINUMV3 => 'gestinumv3', - self::$EXPORT_TYPE_GESTINUMV5 => 'gestinumv5', + self::$EXPORT_TYPE_GESTIMUMV3 => 'gestimumv3', + self::$EXPORT_TYPE_GESTIMUMV5 => 'gestimumv5', self::$EXPORT_TYPE_FEC => 'fec', self::$EXPORT_TYPE_FEC2 => 'fec2', ); @@ -227,11 +227,13 @@ class AccountancyExport self::$EXPORT_TYPE_LDCOMPTA10 => array( 'label' => $langs->trans('Modelcsv_LDCompta10'), ), - self::$EXPORT_TYPE_GESTINUMV3 => array( + self::$EXPORT_TYPE_GESTIMUMV3 => array( 'label' => $langs->trans('Modelcsv_Gestinumv3'), + 'ACCOUNTING_EXPORT_FORMAT' => 'txt', ), - self::$EXPORT_TYPE_GESTINUMV5 => array( + self::$EXPORT_TYPE_GESTIMUMV5 => array( 'label' => $langs->trans('Modelcsv_Gestinumv5'), + 'ACCOUNTING_EXPORT_FORMAT' => 'txt', ), self::$EXPORT_TYPE_FEC => array( 'label' => $langs->trans('Modelcsv_FEC'), @@ -320,10 +322,10 @@ class AccountancyExport case self::$EXPORT_TYPE_LDCOMPTA10 : $this->exportLDCompta10($TData); break; - case self::$EXPORT_TYPE_GESTINUMV3 : + case self::$EXPORT_TYPE_GESTIMUMV3 : $this->exportGestimumV3($TData); break; - case self::$EXPORT_TYPE_GESTINUMV5 : + case self::$EXPORT_TYPE_GESTIMUMV5 : $this->exportGestimumV5($TData); break; case self::$EXPORT_TYPE_FEC : @@ -820,6 +822,8 @@ class AccountancyExport */ public function exportFEC($objectLines) { + global $langs; + $separator = "\t"; $end_line = "\r\n"; @@ -855,55 +859,55 @@ class AccountancyExport $date_limit_payment = dol_print_date($line->date_lim_reglement, '%Y%m%d'); // FEC:JournalCode - print $line->code_journal.$separator; + print $line->code_journal . $separator; // FEC:JournalLib - print $line->journal_label.$separator; + print dol_string_unaccent($langs->transnoentities($line->journal_label)) . $separator; // FEC:EcritureNum - print $line->piece_num.$separator; + print $line->piece_num . $separator; // FEC:EcritureDate - print $date_document.$separator; + print $date_document . $separator; // FEC:CompteNum - print length_accountg($line->numero_compte).$separator; + print $line->numero_compte . $separator; // FEC:CompteLib - print dol_string_unaccent($line->label_compte).$separator; + print dol_string_unaccent($line->label_compte) . $separator; // FEC:CompAuxNum - print length_accounta($line->subledger_account).$separator; + print $line->subledger_account . $separator; // FEC:CompAuxLib - print dol_string_unaccent($line->subledger_label).$separator; + print dol_string_unaccent($line->subledger_label) . $separator; // FEC:PieceRef - print $line->doc_ref.$separator; + print $line->doc_ref . $separator; // FEC:PieceDate - print $date_creation.$separator; + print dol_string_unaccent($date_creation) . $separator; // FEC:EcritureLib - print dol_string_unaccent($line->label_operation).$separator; + print dol_string_unaccent($line->label_operation) . $separator; // FEC:Debit - print price2fec($line->debit).$separator; + print price2fec($line->debit) . $separator; // FEC:Credit - print price2fec($line->credit).$separator; + print price2fec($line->credit) . $separator; // FEC:EcritureLet - print $line->lettering_code.$separator; + print $line->lettering_code . $separator; // FEC:DateLet - print $date_lettering.$separator; + print $date_lettering . $separator; // FEC:ValidDate - print $date_validation.$separator; + print $date_validation . $separator; // FEC:Montantdevise - print $line->multicurrency_amount.$separator; + print $line->multicurrency_amount . $separator; // FEC:Idevise print $line->multicurrency_code.$separator; @@ -924,6 +928,8 @@ class AccountancyExport */ public function exportFEC2($objectLines) { + global $langs; + $separator = "\t"; $end_line = "\r\n"; @@ -962,7 +968,7 @@ class AccountancyExport print $line->code_journal . $separator; // FEC:JournalLib - print $line->journal_label . $separator; + print dol_string_unaccent($langs->transnoentities($line->journal_label)) . $separator; // FEC:EcritureNum print $line->piece_num . $separator; @@ -1634,81 +1640,85 @@ class AccountancyExport $invoices_infos = array(); $supplier_invoices_infos = array(); foreach ($objectLines as $line) { - $date = dol_print_date($line->doc_date, '%d/%m/%Y'); - - $invoice_ref = $line->doc_ref; - $company_name = ""; - - if (($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice') && $line->fk_doc > 0) { - if (($line->doc_type == 'customer_invoice' && !isset($invoices_infos[$line->fk_doc])) || - ($line->doc_type == 'supplier_invoice' && !isset($supplier_invoices_infos[$line->fk_doc]))) { - if ($line->doc_type == 'customer_invoice') { - // Get new customer invoice ref and company name - $sql = 'SELECT f.facnumber, s.nom FROM ' . MAIN_DB_PREFIX . 'facture as f'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe AS s ON f.fk_soc = s.rowid'; - $sql .= ' WHERE f.rowid = ' . $line->fk_doc; - $resql = $this->db->query($sql); - if ($resql) { - if ($obj = $this->db->fetch_object($resql)) { - // Save invoice infos - $invoices_infos[$line->fk_doc] = array('ref' => $obj->facnumber, 'company_name' => $obj->nom); - $invoice_ref = $obj->facnumber; - $company_name = $obj->nom; - } - } - } else { - // Get new supplier invoice ref and company name - $sql = 'SELECT ff.ref, s.nom FROM ' . MAIN_DB_PREFIX . 'facture_fourn as ff'; - $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe AS s ON ff.fk_soc = s.rowid'; - $sql .= ' WHERE ff.rowid = ' . $line->fk_doc; - $resql = $this->db->query($sql); - if ($resql) { - if ($obj = $this->db->fetch_object($resql)) { - // Save invoice infos - $supplier_invoices_infos[$line->fk_doc] = array('ref' => $obj->ref, 'company_name' => $obj->nom); - $invoice_ref = $obj->ref; - $company_name = $obj->nom; - } - } - } - } elseif ($line->doc_type == 'customer_invoice') { - // Retrieve invoice infos - $invoice_ref = $invoices_infos[$line->fk_doc]['ref']; - $company_name = $invoices_infos[$line->fk_doc]['company_name']; - } else { - // Retrieve invoice infos - $invoice_ref = $supplier_invoices_infos[$line->fk_doc]['ref']; - $company_name = $supplier_invoices_infos[$line->fk_doc]['company_name']; - } - } - - print $line->id . $this->separator; - print $date . $this->separator; - print substr($line->code_journal, 0, 4) . $this->separator; - - if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { - print length_accountg($line->subledger_account) . $this->separator; + if ($line->debit == 0 && $line->credit == 0) { + unset($array[$line]); } else { - print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator; + $date = dol_print_date($line->doc_date, '%d/%m/%Y'); + + $invoice_ref = $line->doc_ref; + $company_name = ""; + + if (($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice') && $line->fk_doc > 0) { + if (($line->doc_type == 'customer_invoice' && !isset($invoices_infos[$line->fk_doc])) || + ($line->doc_type == 'supplier_invoice' && !isset($supplier_invoices_infos[$line->fk_doc]))) { + if ($line->doc_type == 'customer_invoice') { + // Get new customer invoice ref and company name + $sql = 'SELECT f.ref, s.nom FROM ' . MAIN_DB_PREFIX . 'facture as f'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe AS s ON f.fk_soc = s.rowid'; + $sql .= ' WHERE f.rowid = ' . $line->fk_doc; + $resql = $this->db->query($sql); + if ($resql) { + if ($obj = $this->db->fetch_object($resql)) { + // Save invoice infos + $invoices_infos[$line->fk_doc] = array('ref' => $obj->ref, 'company_name' => $obj->nom); + $invoice_ref = $obj->ref; + $company_name = $obj->nom; + } + } + } else { + // Get new supplier invoice ref and company name + $sql = 'SELECT ff.ref, s.nom FROM ' . MAIN_DB_PREFIX . 'facture_fourn as ff'; + $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe AS s ON ff.fk_soc = s.rowid'; + $sql .= ' WHERE ff.rowid = ' . $line->fk_doc; + $resql = $this->db->query($sql); + if ($resql) { + if ($obj = $this->db->fetch_object($resql)) { + // Save invoice infos + $supplier_invoices_infos[$line->fk_doc] = array('ref' => $obj->ref, 'company_name' => $obj->nom); + $invoice_ref = $obj->ref; + $company_name = $obj->nom; + } + } + } + } elseif ($line->doc_type == 'customer_invoice') { + // Retrieve invoice infos + $invoice_ref = $invoices_infos[$line->fk_doc]['ref']; + $company_name = $invoices_infos[$line->fk_doc]['company_name']; + } else { + // Retrieve invoice infos + $invoice_ref = $supplier_invoices_infos[$line->fk_doc]['ref']; + $company_name = $supplier_invoices_infos[$line->fk_doc]['company_name']; + } + } + + print $line->id . $this->separator; + print $date . $this->separator; + print substr($line->code_journal, 0, 4) . $this->separator; + + if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { + print length_accountg($line->subledger_account) . $this->separator; + } else { + print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator; + } + //Libellé Auto + print $this->separator; + //print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator; + //Libellé manuel + print dol_trunc(str_replace('"', '', $invoice_ref . (!empty($company_name) ? ' - ' : '') . $company_name), 40, 'right', 'UTF-8', 1) . $this->separator; + //Numéro de pièce + print dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . $this->separator; + //Devise + print 'EUR' . $this->separator; + //Montant + print price2num(abs($line->montant)) . $this->separator; + //Sens + print $line->sens . $this->separator; + //Code lettrage + print $this->separator; + //Date Echéance + print $date; + print $this->end_line; } - //Libellé Auto - print $this->separator; - //print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator; - //Libellé manuel - print dol_trunc(str_replace('"', '', $invoice_ref . (!empty($company_name) ? ' - ' : '') . $company_name), 40, 'right', 'UTF-8', 1) . $this->separator; - //Numéro de pièce - print dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . $this->separator; - //Devise - print 'EUR' . $this->separator; - //Montant - print price2num(abs($line->montant)) . $this->separator; - //Sens - print $line->sens . $this->separator; - //Code lettrage - print $this->separator; - //Date Echéance - print $date; - print $this->end_line; } } @@ -1725,27 +1735,31 @@ class AccountancyExport $this->separator = ','; foreach ($objectLines as $line) { - $date = dol_print_date($line->doc_date, '%d%m%Y'); - - print $line->id . $this->separator; - print $date . $this->separator; - print substr($line->code_journal, 0, 4) . $this->separator; - if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { - print length_accountg($line->subledger_account) . $this->separator; + if ($line->debit == 0 && $line->credit == 0) { + unset($array[$line]); } else { - print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator; + $date = dol_print_date($line->doc_date, '%d%m%Y'); + + print $line->id . $this->separator; + print $date . $this->separator; + print substr($line->code_journal, 0, 4) . $this->separator; + if ((substr($line->numero_compte, 0, 3) == '411') || (substr($line->numero_compte, 0, 3) == '401')) { + print length_accountg($line->subledger_account) . $this->separator; + } else { + print substr(length_accountg($line->numero_compte), 0, 15) . $this->separator; + } + print $this->separator; + //print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator; + print '"' . dol_trunc(str_replace('"', '', $line->doc_ref), 40, 'right', 'UTF-8', 1) . '"' . $this->separator; + print '"' . dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1) . '"' . $this->separator; + print price2num($line->montant) . $this->separator; + print $line->sens . $this->separator; + print $date . $this->separator; + print $this->separator; + print $this->separator; + print 'EUR'; + print $this->end_line; } - print $this->separator; - //print '"'.dol_trunc(str_replace('"', '', $line->label_operation),40,'right','UTF-8',1).'"' . $this->separator; - print '"'.dol_trunc(str_replace('"', '', $line->doc_ref), 40, 'right', 'UTF-8', 1).'"' . $this->separator; - print '"'.dol_trunc(str_replace('"', '', $line->piece_num), 10, 'right', 'UTF-8', 1).'"'.$this->separator; - print price2num($line->montant).$this->separator; - print $line->sens.$this->separator; - print $date . $this->separator; - print $this->separator; - print $this->separator; - print 'EUR'; - print $this->end_line; } } diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index a76be081471..6ee8a03d8ff 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -126,7 +126,7 @@ class AccountingJournal extends CommonObject $this->rowid = $obj->rowid; $this->code = $obj->code; - $this->ref = $obj->code; + $this->ref = $obj->code; $this->label = $obj->label; $this->nature = $obj->nature; $this->active = $obj->active; diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 3b03e6ae8ca..c8a12cef083 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -315,6 +315,7 @@ class BookKeeping extends CommonObject $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"; @@ -327,8 +328,8 @@ class BookKeeping extends CommonObject $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); } - dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG); if (empty($this->piece_num)) { $this->piece_num = 1; } @@ -369,7 +370,7 @@ class BookKeeping extends CommonObject $sql .= ", ".(!empty($this->subledger_account) ? ("'".$this->db->escape($this->subledger_account)."'") : "NULL"); $sql .= ", ".(!empty($this->subledger_label) ? ("'".$this->db->escape($this->subledger_label)."'") : "NULL"); $sql .= ", '".$this->db->escape($this->numero_compte)."'"; - $sql .= ", ".(!empty($this->label_operation) ? ("'".$this->db->escape($this->label_operation)."'") : "NULL"); + $sql .= ", ".(!empty($this->label_compte) ? ("'".$this->db->escape($this->label_compte)."'") : "NULL"); $sql .= ", '".$this->db->escape($this->label_operation)."'"; $sql .= ", ".$this->debit; $sql .= ", ".$this->credit; @@ -383,7 +384,6 @@ class BookKeeping extends CommonObject $sql .= ", ".(!isset($this->entity) ? $conf->entity : $this->entity); $sql .= ")"; - 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.$this->table_element); @@ -795,7 +795,7 @@ class BookKeeping extends CommonObject $sql .= " t.label_operation,"; $sql .= " t.debit,"; $sql .= " t.credit,"; - $sql .= " t.montant,"; + $sql .= " t.montant as amount,"; $sql .= " t.sens,"; $sql .= " t.multicurrency_amount,"; $sql .= " t.multicurrency_code,"; @@ -806,7 +806,8 @@ class BookKeeping extends CommonObject $sql .= " t.code_journal,"; $sql .= " t.journal_label,"; $sql .= " t.piece_num,"; - $sql .= " t.date_creation"; + $sql .= " t.date_creation,"; + $sql .= " t.date_export"; // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -823,12 +824,18 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\''; } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') { $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; + } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } elseif ($key == 't.reconciled_option') { $sqlwhere[] = 't.lettering_code IS NULL'; } elseif ($key == 't.code_journal' && !empty($value)) { - $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1); + if (is_array($value)) { + $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1); + } else { + $sqlwhere[] = natural_search("t.code_journal", $value, 3, 1); + } } else { $sqlwhere[] = natural_search($key, $value, 0, 1); } @@ -878,7 +885,8 @@ class BookKeeping extends CommonObject $line->label_operation = $obj->label_operation; $line->debit = $obj->debit; $line->credit = $obj->credit; - $line->montant = $obj->montant; + $line->montant = $obj->amount; // deprecated + $line->amount = $obj->amount; $line->sens = $obj->sens; $line->multicurrency_amount = $obj->multicurrency_amount; $line->multicurrency_code = $obj->multicurrency_code; @@ -889,7 +897,8 @@ class BookKeeping extends CommonObject $line->code_journal = $obj->code_journal; $line->journal_label = $obj->journal_label; $line->piece_num = $obj->piece_num; - $line->date_creation = $obj->date_creation; + $line->date_creation = $this->db->jdate($obj->date_creation); + $line->date_export = $this->db->jdate($obj->date_export); $this->lines[] = $line; @@ -941,7 +950,7 @@ class BookKeeping extends CommonObject $sql .= " t.credit,"; $sql .= " t.lettering_code,"; $sql .= " t.date_lettering,"; - $sql .= " t.montant,"; + $sql .= " t.montant as amount,"; $sql .= " t.sens,"; $sql .= " t.fk_user_author,"; $sql .= " t.import_key,"; @@ -1019,7 +1028,8 @@ class BookKeeping extends CommonObject $line->label_operation = $obj->label_operation; $line->debit = $obj->debit; $line->credit = $obj->credit; - $line->montant = $obj->montant; + $line->montant = $obj->amount; // deprecated + $line->amount = $obj->amount; $line->sens = $obj->sens; $line->lettering_code = $obj->lettering_code; $line->date_lettering = $obj->date_lettering; @@ -1904,25 +1914,24 @@ class BookKeeping extends CommonObject /** * Return id and description of a root accounting account. - * This function takes the parent of parent to get the root account ! + * FIXME: This function takes the parent of parent to get the root account ! * * @param string $account Accounting account - * @return string Root account + * @return array Array with root account information (max 2 upper level) */ public function getRootAccount($account = null) { global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; - $sql = "SELECT root.rowid, root.account_number, root.label as label"; + $sql = "SELECT root.rowid, root.account_number, root.label as label,"; + $sql .= " parent.rowid as parent_rowid, parent.account_number as parent_account_number, parent.label as parent_label"; $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version"; $sql .= " AND asy.rowid = ".((int) $pcgver); - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid AND parent.active = 1"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid AND root.active = 1"; $sql .= " WHERE aa.account_number = '".$this->db->escape($account)."'"; - $sql .= " AND parent.active = 1"; - $sql .= " AND root.active = 1"; $sql .= " AND aa.entity IN (".getEntity('accountancy').")"; dol_syslog(get_class($this)."::select_account sql=".$sql, LOG_DEBUG); @@ -1933,7 +1942,8 @@ class BookKeeping extends CommonObject $obj = $this->db->fetch_object($resql); } - return array('id'=>$obj->rowid, 'account_number'=>$obj->account_number, 'label'=>$obj->label); + $result = array('id'=>$obj->rowid, 'account_number'=>$obj->account_number, 'label'=>$obj->label); + return $result; } else { $this->error = "Error ".$this->db->lasterror(); dol_syslog(__METHOD__." ".$this->error, LOG_ERR); diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 1a5098bda38..3634fba2e79 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2014 Florian Henry - * Copyright (C) 2013-2017 Alexandre Spangaro + * Copyright (C) 2013-2020 Alexandre Spangaro * Copyright (C) 2014 Juanjo Menent * Copyright (C) 2015 Jean-François Ferry * @@ -123,9 +123,9 @@ if ($action == 'validatehistory') { $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,"; $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,"; $sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,"; - $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export,"; + $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,"; $sql .= " co.code as country_code, co.label as country_label,"; - $sql .= " s.tva_intra"; + $sql .= " s.tva_intra, s.accountancy_code_sell as company_code_sell"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = s.fk_pays "; @@ -134,6 +134,7 @@ if ($action == 'validatehistory') { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON p.accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa.entity = ".$conf->entity; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa2 ON p.accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa2.entity = ".$conf->entity; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa3 ON p.accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa3.entity = ".$conf->entity; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa4 ON s.accountancy_code_sell = aa4.account_number AND aa4.active = 1 AND aa4.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa4.entity = ".$conf->entity; $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0"; $sql .= " AND l.product_type <= 2"; @@ -153,7 +154,7 @@ if ($action == 'validatehistory') { $isBuyerInEEC = isInEEC($objp); - // Search suggested account for product/service (similar code exists in page list.php to make manual binding) + // Level 2: Search suggested account for product/service (similar code exists in page list.php to make manual binding) $suggestedaccountingaccountfor = ''; if (($objp->country_code == $mysoc->country_code) || empty($objp->country_code)) { // If buyer in same country than seller (if not defined, we assume it is same country) $objp->code_sell_p = $objp->code_sell; @@ -179,6 +180,13 @@ if ($action == 'validatehistory') { } } + // Level 3: Search suggested account for this thirdparty (similar code exists in page index.php to make automatic binding) + if (!empty($objp->company_code_sell)) { + $objp->code_sell_t = $objp->company_code_sell; + $objp->aarowid_suggest = $objp->aarowid_thirdparty; + $suggestedaccountingaccountfor = ''; + } + if ($objp->aarowid_suggest > 0) { $sqlupdate = "UPDATE ".MAIN_DB_PREFIX."facturedet"; diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index 9a78ea3bfc9..a5c603c2504 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -37,7 +37,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; // Load translation files required by the page -$langs->loadLangs(array("bills", "compta", "accountancy", "productbatch")); +$langs->loadLangs(array("bills", "compta", "accountancy", "productbatch", "products")); $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') @@ -176,7 +176,8 @@ print ''."\n"; + } + + print load_fiche_titre($langs->trans("DoPayment")); + print "
\n"; + + print ''; + print ''; + print ''; + print ''; + print ''; + + print dol_get_fiche_head('', ''); + + print '
'; - print '
'; - print $langs->trans('From') . ' '; - print $form->selectDate($search_date_start, 'date_creation_start', 0, 0, 1); - print '
'; - print '
'; - print $langs->trans('to') . ' '; - print $form->selectDate($search_date_end, 'date_creation_end', 0, 0, 1); - print '
'; - print '
'; + print '
'; + print $langs->trans('From') . ' '; + print $form->selectDate($search_date_start, 'date_creation_start', 0, 0, 1); + print '
'; + print '
'; + print $langs->trans('to') . ' '; + print $form->selectDate($search_date_end, 'date_creation_end', 0, 0, 1); + print '
'; + print '
 '; - $searchpicto = $form->showFilterButtons(); - print $searchpicto; - print '
 '; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'; + + print ''; + //print '\n"; + print '\n"; + print '\n"; + /*print '\n"; + print '';*/ + + $sql = "SELECT sum(p.amount) as total"; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_vat as p"; + $sql .= " WHERE p.fk_tva = ".$chid; + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + $sumpaid = $obj->total; + $db->free(); + } + /*print ''; + print '';*/ + + print '"; + print ''; + + print '\n"; + print ''; + + print ''; + print ''; + print ''; + + // Number + print ''; + print ''."\n"; + + print ''; + print ''; + print ''; + print ''; + + print '
'.$langs->trans("Ref").''.$chid.'
'.$langs->trans("Type")."".$tva->type_label."
'.$langs->trans("Period")."".dol_print_date($tva->datev, 'day')."
'.$langs->trans("Label").''.$tva->label."
'.$langs->trans("DateDue")."".dol_print_date($tva->date_ech,'day')."
'.$langs->trans("Amount")."".price($tva->amount,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("AlreadyPaid").''.price($sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("RemainderToPay").''.price($total-$sumpaid,0,$outputlangs,1,-1,-1,$conf->currency).'
'.$langs->trans("Date").''; + $datepaye = dol_mktime(12, 0, 0, GETPOST("remonth", 'int'), GETPOST("reday", 'int'), GETPOST("reyear", 'int')); + $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ? (GETPOST("remonth", 'int') ? $datepaye : -1) : 0; + print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); + print "
'.$langs->trans("PaymentMode").''; + $form->select_types_paiements(GETPOSTISSET("paiementtype") ? GETPOST("paiementtype", "int") : $tva->paiementtype, "paiementtype"); + print "
'.$langs->trans('AccountToDebit').''; + $form->select_comptes(GETPOST("accountid") ? GETPOST("accountid", "int") : $tva->accountid, "accountid", 0, '', 1); // Show opend bank account list + print '
'.$langs->trans('Numero'); + print ' ('.$langs->trans("ChequeOrTransferNumber").')'; + print '
'.$langs->trans("Comments").'
'; + + print dol_get_fiche_end(); + + /* + * Autres charges impayees + */ + $num = 1; + $i = 0; + + print ''; + print ''; + //print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + $total = 0; + $totalrecu = 0; + + while ($i < $num) + { + $objp = $tva; + + print ''; + + if ($objp->datev > 0) + { + print ''."\n"; + } + else { + print "\n"; + } + + print '"; + + print '"; + + print '"; + + print '"; + + print "\n"; + $total += $objp->total; + $total_ttc += $objp->total_ttc; + $totalrecu += $objp->am; + $i++; + } + if ($i > 1) { + // Print total + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + + print "
'.$langs->trans("SocialContribution").''.$langs->trans("DateDue").''.$langs->trans("Amount").''.$langs->trans("AlreadyPaid").''.$langs->trans("RemainderToPay").''.$langs->trans("Amount").'
'.dol_print_date($objp->datev, 'day').'!!!'.price($objp->amount)."'.price($sumpaid)."'.price($objp->amount - $sumpaid)."'; + + if ($sumpaid <> $objp->amount) + { + $namef = "amount_".$objp->id; + $nameRemain = "remain_".$objp->id; + /* Disabled, we autofil the amount with remain to pay by default + if (!empty($conf->use_javascript_ajax)) { + print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->amount - $sumpaid)."'"); + } */ + $remaintopay = $objp->amount - $sumpaid; + print ''; + print ''; + } + else { + print '-'; + } + print "
'.$langs->trans("Total").':'.price($total_ttc).''.price($totalrecu).''.price($total_ttc - $totalrecu).' 
"; + + // Bouton Save payment + print '
'.$langs->trans("ClosePaidVATAutomatically"); + print '
'; + print '     '; + print ''; + print '
'; + + print "\n"; +} + +llxFooter(); +$db->close(); diff --git a/htdocs/compta/payment_sc/card.php b/htdocs/compta/payment_sc/card.php index 11c8512a265..78fa11fc70b 100644 --- a/htdocs/compta/payment_sc/card.php +++ b/htdocs/compta/payment_sc/card.php @@ -162,7 +162,7 @@ print dol_get_fiche_end(); /* - * List of social contributions payed + * List of social contributions paid */ $disable_delete = 0; @@ -213,7 +213,7 @@ if ($resql) print ''.price($objp->sc_amount).''; // Status print ''.$socialcontrib->getLibStatut(4, $objp->amount).''; - // Amount payed + // Amount paid print ''.price($objp->amount).''; print "\n"; if ($objp->paye == 1) // If at least one invoice is paid, disable delete diff --git a/htdocs/compta/payment_vat/card.php b/htdocs/compta/payment_vat/card.php new file mode 100644 index 00000000000..dee616eb2ef --- /dev/null +++ b/htdocs/compta/payment_vat/card.php @@ -0,0 +1,330 @@ + + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2021 Gauthier VERDOL + * + * This 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/payment_vat/card.php + * \ingroup facture + * \brief Onglet payment of a social contribution + * \remarks Fichier presque identique a fournisseur/paiement/card.php + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/paymentvat.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php'; +if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array('bills', 'banks', 'companies')); + +// Security check +$id = GETPOST("id", 'int'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm'); +if ($user->socid) $socid = $user->socid; +// TODO ajouter regle pour restreindre acces paiement +//$result = restrictedArea($user, 'facture', $id,''); + +$object = new PaymentVAT($db); +if ($id > 0) +{ + $result = $object->fetch($id); + if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); +} + + +/* + * Actions + */ + +// Delete payment +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->tax->charges->supprimer) +{ + $db->begin(); + + $result = $object->delete($user); + if ($result > 0) + { + $db->commit(); + header("Location: ".DOL_URL_ROOT."/compta/tva/payments.php?mode=tvaonly"); + exit; + } + else { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } +} + +// Validate social contribution +/* +if ($action == 'confirm_valide' && $confirm == 'yes' && $user->rights->tax->charges->creer) +{ + $db->begin(); + + $result=$object->valide(); + + if ($result > 0) + { + $db->commit(); + + $factures=array(); // TODO Get all id of invoices linked to this payment + foreach($factures as $id) + { + $fac = new Facture($db); + $fac->fetch($id); + + $outputlangs = $langs; + if (! empty($_REQUEST['lang_id'])) + { + $outputlangs = new Translate("",$conf); + $outputlangs->setDefaultLang($_REQUEST['lang_id']); + } + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + $fac->generateDocument($fac->modelpdf, $outputlangs); + } + } + + header('Location: card.php?id='.$object->id); + exit; + } + else + { + setEventMessages($object->error, $object->errors, 'errors'); + $db->rollback(); + } +} +*/ + + +/* + * View + */ + +llxHeader(); + +$tva = new TVA($db); + +$form = new Form($db); + +$h = 0; + +$head[$h][0] = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='.$id; +$head[$h][1] = $langs->trans("VATPayment"); +$hselected = $h; +$h++; + +/*$head[$h][0] = DOL_URL_ROOT.'/compta/payment_sc/info.php?id='.$id; +$head[$h][1] = $langs->trans("Info"); +$h++; +*/ + + +print dol_get_fiche_head($head, $hselected, $langs->trans("VATPayment"), -1, 'payment'); + +/* + * Deletion confirmation of payment + */ +if ($action == 'delete') { + print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); +} + +/* + * Validation confirmation of payment + */ +/* +if ($action == 'valide') +{ + $facid = $_GET['facid']; + print $form->formconfirm('card.php?id='.$object->id.'&facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide','',0,2); + +} +*/ + + +$linkback = ''.$langs->trans("BackToList").''; + +dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'id', ''); + + +print '
'; +print '
'; + +print ''; + +// Ref +/*print ''; +print '';*/ + +// Date +print ''; + +// Mode +print ''; + +// Numero +print ''; + +// Montant +print ''; + +// Note +print ''; + +// Bank account +if (!empty($conf->banque->enabled)) +{ + if ($object->bank_account) + { + $bankline = new AccountLine($db); + $bankline->fetch($object->bank_line); + + print ''; + print ''; + print ''; + print ''; + } +} + +print '
'.$langs->trans('Ref').''; +print $form->showrefnav($object,'id','',1,'rowid','id'); +print '
'.$langs->trans('Date').''.dol_print_date($object->datep, 'day').'
'.$langs->trans('Mode').''.$langs->trans("PaymentType".$object->type_code).'
'.$langs->trans('Numero').''.$object->num_paiement.'
'.$langs->trans('Amount').''.price($object->amount, 0, $outputlangs, 1, -1, -1, $conf->currency).'
'.$langs->trans('Note').''.nl2br($object->note).'
'.$langs->trans('BankTransactionLine').''; + print $bankline->getNomUrl(1, 0, 'showall'); + print '
'; + +print '
'; + +print dol_get_fiche_end(); + + +/* + * List of social contributions payed + */ + +$disable_delete = 0; +$sql = 'SELECT f.rowid as scid, f.label as label, f.paye, f.amount as tva_amount, pf.amount'; +//$sql .= ', pc.libelle as sc_type'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'payment_vat as pf,'.MAIN_DB_PREFIX.'tva as f'; +//$sql .= ', '.MAIN_DB_PREFIX.'c_chargesociales as pc'; +$sql .= ' WHERE pf.fk_tva = f.rowid'; +//$sql .= ' AND f.fk_type = pc.id'; +$sql .= ' AND f.entity = '.$conf->entity; +$sql .= ' AND pf.rowid = '.$object->id; + +dol_syslog("compta/payment_vat/card.php", LOG_DEBUG); +$resql = $db->query($sql); +if ($resql) +{ + $num = $db->num_rows($resql); + + $i = 0; + $total = 0; + print '
'; + print ''; + print ''; + //print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + + if ($num > 0) + { + while ($i < $num) + { + $objp = $db->fetch_object($resql); + + print ''; + // Ref + print '\n"; + // Type + /* print '\n";*/ + // Label + print ''; + // Expected to pay + print ''; + // Status + print ''; + // Amount payed + print ''; + print "\n"; + if ($objp->paye == 1) // If at least one invoice is paid, disable delete + { + $disable_delete = 1; + } + $total = $total + $objp->amount; + $i++; + } + } + + + print "
'.$langs->trans('VATDeclaration').''.$langs->trans('Type').''.$langs->trans('Label').''.$langs->trans('ExpectedToPay').''.$langs->trans('Status').''.$langs->trans('PayedByThisPayment').'
'; + $tva->fetch($objp->scid); + print $tva->getNomUrl(1); + print "'; + print $tva->type_label;4 + print "'.$objp->label.''.price($objp->tva_amount).''.$tva->getLibStatut(4, $objp->amount).''.price($objp->amount).'
\n"; + $db->free($resql); +} +else { + dol_print_error($db); +} + + + +/* + * Boutons Actions + */ +print '
'; + +/* +if (! empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) +{ + if ($user->socid == 0 && $object->statut == 0 && $_GET['action'] == '') + { + if ($user->rights->facture->paiement) + { + print ''.$langs->trans('Valid').''; + } + } +} +*/ + +if ($action == '') +{ + if ($user->rights->tax->charges->supprimer) + { + if (!$disable_delete) + { + print ''.$langs->trans('Delete').''; + } + else { + print ''.$langs->trans('Delete').''; + } + } +} + +print '
'; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php index 5d87303236a..73642df96bd 100644 --- a/htdocs/compta/prelevement/card.php +++ b/htdocs/compta/prelevement/card.php @@ -2,7 +2,7 @@ /* Copyright (C) 2005 Rodolphe Quiedeville * Copyright (C) 2005-2010 Laurent Destailleur * Copyright (C) 2010-2016 Juanjo Menent - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2021 Frédéric 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 @@ -98,7 +98,13 @@ if (empty($reshook)) // Seems to no be used and replaced with $action == 'infocredit' if ($action == 'confirm_credite' && GETPOST('confirm', 'alpha') == 'yes') { - $res = $object->set_credite(); + if ($object->statut == 2) { + $res = -1; + setEventMessages('WithdrawalCantBeCreditedTwice', array(), 'errors'); + } else { + $res = $object->set_credite(); + } + if ($res >= 0) { header("Location: card.php?id=".$id); @@ -145,10 +151,16 @@ if (empty($reshook)) { $dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $error = $object->set_infocredit($user, $dt); + if ($object->statut == 2) { + $error = 1; + setEventMessages('WithdrawalCantBeCreditedTwice', array(), 'errors'); + } else { + $error = $object->set_infocredit($user, $dt); + } + if ($error) { - setEventMessages($object->error, $object->errors, 'errors'); + setEventMessages($object->error, $object->errors, 'errors'); } } } @@ -354,8 +366,8 @@ if ($id > 0 || $ref) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { + // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -445,15 +457,14 @@ if ($id > 0 || $ref) $i++; } - if ($num > 0) - { + if ($num > 0) { print ''; print ''.$langs->trans("Total").''; print ' '; print ''; - if (empty($offset) && $num <= $limit) // If we have all record on same page, then the following test/warning can be done - { - if ($total != $object->amount) print img_warning("TotalAmountOfdirectDebitOrderDiffersFromSumOfLines"); + if (empty($offset) && $num <= $limit) { + // If we have all record on same page, then the following test/warning can be done + if ($total != $object->amount) print img_warning($langs->trans("TotalAmountOfdirectDebitOrderDiffersFromSumOfLines")); } print price($total); print "\n"; diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 89687997a59..22737fcfbfe 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -371,11 +371,11 @@ class BonPrelevement extends CommonObject $num = count($facs); for ($i = 0; $i < $num; $i++) { - /* Tag invoice as payed */ + /* Tag invoice as paid */ dol_syslog(get_class($this)."::set_credite set_paid fac ".$facs[$i]); $fac = new Facture($this->db); $fac->fetch($facs[$i]); - $result = $fac->set_paid($user); + $result = $fac->setPaid($user); } } @@ -482,7 +482,7 @@ class BonPrelevement extends CommonObject // @TODO Move this after creation of payment if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) { - $result = $fac->set_paid($user); + $result = $fac->setPaid($user); if ($result < 0) { $this->error = $fac->error; $this->errors = $fac->errors; @@ -1704,7 +1704,7 @@ class BonPrelevement extends CommonObject fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); - fputs($this->file, ' '.$conf->global->PAYMENTBYBANKTRANSFER_ICS.''.$CrLf); + fputs($this->file, ' '.$this->emetteur_ics.''.$CrLf); fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); fputs($this->file, ' '.$CrLf); diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 8b7d21d221f..28a3b1e4efa 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -184,7 +184,7 @@ class RejetPrelevement //Tag invoice as unpaid dol_syslog("RejetPrelevement::Create set_unpaid fac ".$fac->ref); - $fac->set_unpaid($user); + $fac->setUnpaid($user); //TODO: Must be managed by notifications module // Send email to sender of the standing order request diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 26b91a1e100..db751735bb0 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -66,18 +66,14 @@ $parameters = array('mode' => $mode, 'format' => $format, 'limit' => $limit, 'pa $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); -if (empty($reshook)) -{ +if (empty($reshook)) { // Change customer bank information to withdraw - if ($action == 'modify') - { - for ($i = 1; $i < 9; $i++) - { + if ($action == 'modify') { + for ($i = 1; $i < 9; $i++) { dolibarr_set_const($db, GETPOST("nom$i"), GETPOST("value$i"), 'chaine', 0, '', $conf->entity); } } - if ($action == 'create') - { + if ($action == 'create') { $default_account=($type == 'bank-transfer' ? 'PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT' : 'PRELEVEMENT_ID_BANKACCOUNT'); if ($id_bankaccount != $conf->global->{$default_account}){ @@ -88,7 +84,8 @@ if (empty($reshook)) $bank = new Account($db); $bank->fetch($conf->global->{$default_account}); if (empty($bank->ics) || empty($bank->ics_transfer)){ - setEventMessages($langs->trans("ErrorICSmissing", $bank->getNomUrl(1)), null, 'errors'); + $errormessage = str_replace('{url}', $bank->getNomUrl(1), $langs->trans("ErrorICSmissing", '{url}')); + setEventMessages($errormessage, null, 'errors'); header("Location: ".DOL_URL_ROOT.'/compta/prelevement/create.php'); exit; } @@ -111,8 +108,7 @@ if (empty($reshook)) $mesg = $langs->trans("NoInvoiceCouldBeWithdrawed", $format); setEventMessages($mesg, null, 'errors'); $mesg .= '
'."\n"; - foreach ($bprev->invoice_in_error as $key => $val) - { + foreach ($bprev->invoice_in_error as $key => $val) { $mesg .= ''.$val."
\n"; } } else { @@ -145,8 +141,7 @@ $bprev = new BonPrelevement($db); llxHeader('', $langs->trans("NewStandingOrder")); -if (prelevement_check_config($type) < 0) -{ +if (prelevement_check_config($type) < 0) { $langs->load("errors"); setEventMessages($langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Withdraw")), null, 'errors'); } @@ -237,8 +232,7 @@ if ($nb) { print ''.$title."\n"; } } else { - if ($mysoc->isInEEC()) - { + if ($mysoc->isInEEC()) { $title = $langs->trans("CreateForSepaFRST"); if ($type == 'bank-transfer') { $title = $langs->trans("CreateSepaFileForPaymentByBankTransfer"); @@ -289,8 +283,7 @@ $sql .= " ".MAIN_DB_PREFIX."societe as s,"; $sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; $sql .= " WHERE s.rowid = f.fk_soc"; $sql .= " AND f.entity IN (".getEntity('invoice').")"; -if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) -{ +if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) { $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED; } //$sql .= " AND pfd.amount > 0"; @@ -305,12 +298,11 @@ if ($type == 'bank-transfer') { if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { + // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -399,7 +391,7 @@ if ($resql) if ($format) print ' ('.$format.')'; } } else { - print img_warning($langs->trans("NoBankAccount")); + print img_warning($langs->trans("NoBankAccountDefined")); } print ''; // Amount diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index bf28ceb0996..07f3424ba60 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2013 Regis Houssin * Copyright (C) 2016-2018 Frédéric France * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2021 Gauthier VERDOL * * This 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,10 +29,13 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formsocialcontrib.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/tax.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->projet->enabled)) { +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +if (!empty($conf->projet->enabled)) +{ include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } @@ -40,7 +44,7 @@ if (!empty($conf->accounting->enabled)) { } // Load translation files required by the page -$langs->loadLangs(array('compta', 'bills', 'banks')); +$langs->loadLangs(array('compta', 'bills', 'banks', 'hrm')); $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); @@ -51,6 +55,7 @@ $dateech = dol_mktime(GETPOST('echhour'), GETPOST('echmin'), GETPOST('echsec'), $dateperiod = dol_mktime(GETPOST('periodhour'), GETPOST('periodmin'), GETPOST('periodsec'), GETPOST('periodmonth'), GETPOST('periodday'), GETPOST('periodyear')); $label = GETPOST('label', 'alpha'); $actioncode = GETPOST('actioncode'); +$fk_user = GETPOST('userid', 'int'); // Security check $socid = GETPOST('socid', 'int'); @@ -69,14 +74,14 @@ $object = new ChargeSociales($db); if ($action == 'confirm_paid' && $user->rights->tax->charges->creer && $confirm == 'yes') { $object->fetch($id); - $result = $object->set_paid($user); + $result = $object->setPaid($user); } if ($action == 'reopen' && $user->rights->tax->charges->creer) { $result = $object->fetch($id); if ($object->paye) { - $result = $object->set_unpaid($user); + $result = $object->setUnpaid($user); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); @@ -94,6 +99,12 @@ if ($action == 'classin' && $user->rights->tax->charges->creer) $object->setProject(GETPOST('projectid')); } +if ($action == 'setfk_user' && $user->rights->tax->charges->creer) { + $object->fetch($id); + $object->fk_user = $fk_user; + $object->update($user); +} + if ($action == 'setlib' && $user->rights->tax->charges->creer) { $object->fetch($id); @@ -163,6 +174,7 @@ if ($action == 'add' && $user->rights->tax->charges->creer) $object->date_ech = $dateech; $object->periode = $dateperiod; $object->amount = $amount; + $object->fk_user = $fk_user; $object->mode_reglement_id = (int) GETPOST('mode_reglement_id', 'int'); $object->fk_account = (int) GETPOST('fk_account', 'int'); $object->fk_project = (int) GETPOST('fk_project', 'int'); @@ -182,8 +194,7 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->tax->charges->cre if (!$dateech) { - setEventMessages($langs->trans("ErrorFieldReqrequire_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; -uired", $langs->transnoentities("Date")), null, 'errors'); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); $action = 'edit'; } elseif (!$dateperiod) { @@ -203,6 +214,7 @@ uired", $langs->transnoentities("Date")), null, 'errors'); $object->date_ech = $dateech; $object->periode = $dateperiod; $object->amount = $amount; + $object->fk_user = $fk_user; $result = $object->update($user); if ($result <= 0) { @@ -343,6 +355,12 @@ if ($action == 'create') print ''; print ''; + // Employee + print ''; + print $langs->trans('Employee'); + print ''; + print ''.$form->select_dolusers($fk_user, 'userid', 1).''; + // Project if (!empty($conf->projet->enabled)) { @@ -443,6 +461,26 @@ if ($id > 0) // Ref customer $morehtmlref .= $form->editfieldkey("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1); $morehtmlref .= $form->editfieldval("Label", 'lib', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', null, null, '', 1); + + // Employee + if ($action != 'editfk_user') { + $morehtmlref .= '
' . $form->editfieldkey("Employee", 'fk_user', $object->label, $object, $user->rights->tax->charges->creer, 'string', '', 0, 1); + + if (!empty($object->fk_user)) { + $userstatic = new User($db); + $userstatic->fetch($object->fk_user); + $morehtmlref .= $userstatic->getNomUrl(1); + } + } else { + $morehtmlref .= '
'.$langs->trans('Employee').' : '; + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $form->select_dolusers($object->fk_user, 'userid', 1); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } + // Project if (!empty($conf->projet->enabled)) { diff --git a/htdocs/compta/sociales/class/cchargesociales.class.php b/htdocs/compta/sociales/class/cchargesociales.class.php index ceace76bba9..c5ec3b24968 100644 --- a/htdocs/compta/sociales/class/cchargesociales.class.php +++ b/htdocs/compta/sociales/class/cchargesociales.class.php @@ -46,9 +46,15 @@ class Cchargesociales /** * @var string Label + * @deprecated */ public $libelle; + /** + * @var string Label + */ + public $label; + public $deductible; public $active; public $code; @@ -107,7 +113,6 @@ class Cchargesociales // Insert request $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'('; - $sql .= 'libelle,'; $sql .= 'deductible,'; $sql .= 'active,'; @@ -115,10 +120,7 @@ class Cchargesociales $sql .= 'fk_pays,'; $sql .= 'module'; $sql .= 'accountancy_code'; - - $sql .= ') VALUES ('; - $sql .= ' '.(!isset($this->libelle) ? 'NULL' : "'".$this->db->escape($this->libelle)."'").','; $sql .= ' '.(!isset($this->deductible) ? 'NULL' : $this->deductible).','; $sql .= ' '.(!isset($this->active) ? 'NULL' : $this->active).','; @@ -126,8 +128,6 @@ class Cchargesociales $sql .= ' '.(!isset($this->fk_pays) ? 'NULL' : $this->fk_pays).','; $sql .= ' '.(!isset($this->module) ? 'NULL' : "'".$this->db->escape($this->module)."'").','; $sql .= ' '.(!isset($this->accountancy_code) ? 'NULL' : "'".$this->db->escape($this->accountancy_code)."'"); - - $sql .= ')'; $this->db->begin(); @@ -179,7 +179,7 @@ class Cchargesociales $sql = 'SELECT'; $sql .= " t.id,"; - $sql .= " t.libelle,"; + $sql .= " t.libelle as label,"; $sql .= " t.deductible,"; $sql .= " t.active,"; $sql .= " t.code,"; @@ -201,7 +201,8 @@ class Cchargesociales $this->id = $obj->id; - $this->libelle = $obj->libelle; + $this->libelle = $obj->label; + $this->label = $obj->label; $this->deductible = $obj->deductible; $this->active = $obj->active; $this->code = $obj->code; @@ -501,6 +502,7 @@ class Cchargesociales $this->id = 0; $this->libelle = ''; + $this->label = ''; $this->deductible = ''; $this->active = ''; $this->code = ''; diff --git a/htdocs/compta/sociales/class/chargesociales.class.php b/htdocs/compta/sociales/class/chargesociales.class.php index ffb2d04e155..ec4e945f922 100644 --- a/htdocs/compta/sociales/class/chargesociales.class.php +++ b/htdocs/compta/sociales/class/chargesociales.class.php @@ -3,6 +3,7 @@ * Copyright (C) 2004-2007 Laurent Destailleur * Copyright (C) 2016-2020 Frédéric France * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -107,6 +108,11 @@ class ChargeSociales extends CommonObject */ public $fk_project; + /** + * @var int ID + */ + public $fk_user; + const STATUS_UNPAID = 0; const STATUS_PAID = 1; @@ -133,8 +139,8 @@ class ChargeSociales extends CommonObject { $sql = "SELECT cs.rowid, cs.date_ech"; $sql .= ", cs.libelle as label, cs.fk_type, cs.amount, cs.fk_projet as fk_project, cs.paye, cs.periode, cs.import_key"; - $sql .= ", cs.fk_account, cs.fk_mode_reglement"; - $sql .= ", c.libelle"; + $sql .= ", cs.fk_account, cs.fk_mode_reglement, cs.fk_user"; + $sql .= ", c.libelle as type_label"; $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle'; $sql .= " FROM ".MAIN_DB_PREFIX."chargesociales as cs"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_chargesociales as c ON cs.fk_type = c.id"; @@ -157,13 +163,14 @@ class ChargeSociales extends CommonObject $this->lib = $obj->label; $this->label = $obj->label; $this->type = $obj->fk_type; - $this->type_label = $obj->libelle; + $this->type_label = $obj->type_label; $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; $this->amount = $obj->amount; $this->fk_project = $obj->fk_project; + $this->fk_user = $obj->fk_user; $this->paye = $obj->paye; $this->periode = $this->db->jdate($obj->periode); $this->import_key = $this->import_key; @@ -222,7 +229,7 @@ class ChargeSociales extends CommonObject $this->db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."chargesociales (fk_type, fk_account, fk_mode_reglement, libelle, date_ech, periode, amount, fk_projet, entity, fk_user_author, date_creation)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."chargesociales (fk_type, fk_account, fk_mode_reglement, libelle, date_ech, periode, amount, fk_projet, entity, fk_user_author, fk_user, date_creation)"; $sql .= " VALUES (".$this->type; $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); $sql .= ", ".($this->mode_reglement_id > 0 ? $this->mode_reglement_id : "NULL"); @@ -233,6 +240,7 @@ class ChargeSociales extends CommonObject $sql .= ", ".($this->fk_project > 0 ? $this->fk_project : 'NULL'); $sql .= ", ".$conf->entity; $sql .= ", ".$user->id; + $sql .= ", ".($this->fk_user > 0 ? $this->db->escape($this->fk_user) : 'NULL'); $sql .= ", '".$this->db->idate($now)."'"; $sql .= ")"; @@ -346,6 +354,7 @@ class ChargeSociales extends CommonObject $sql .= ", periode='".$this->db->idate($this->periode)."'"; $sql .= ", amount='".price2num($this->amount, 'MT')."'"; $sql .= ", fk_projet=".($this->fk_project > 0 ? $this->db->escape($this->fk_project) : "NULL"); + $sql .= ", fk_user=".($this->fk_user > 0 ? $this->db->escape($this->fk_user) : "NULL"); $sql .= ", fk_user_modif=".$user->id; $sql .= " WHERE rowid=".$this->id; @@ -421,14 +430,28 @@ class ChargeSociales extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Tag social contribution as payed completely + * Tag social contribution as paid completely * - * @param User $user Object user making change - * @return int <0 if KO, >0 if OK + * @deprecated + * @see setPaid() + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK */ public function set_paid($user) { // phpcs:enable + dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE); + return $this->setPaid($user); + } + + /** + * Tag social contribution as paid completely + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function setPaid($user) + { $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; $sql .= " paye = 1"; $sql .= " WHERE rowid = ".$this->id; @@ -439,14 +462,28 @@ class ChargeSociales extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Remove tag payed on social contribution + * Remove tag paid on social contribution * - * @param User $user Object user making change - * @return int <0 if KO, >0 if OK + * @deprecated + * @see setUnpaid() + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK */ public function set_unpaid($user) { // phpcs:enable + dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE); + return $this->setUnpaid($user); + } + + /** + * Remove tag paid on social contribution + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function setUnpaid($user) + { $sql = "UPDATE ".MAIN_DB_PREFIX."chargesociales SET"; $sql .= " paye = 0"; $sql .= " WHERE rowid = ".$this->id; @@ -459,7 +496,7 @@ class ChargeSociales extends CommonObject * Retourne le libelle du statut d'une charge (impaye, payee) * * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @param 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) + * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount paid if you have it, 1 otherwise) * @return string Label */ public function getLibStatut($mode = 0, $alreadypaid = -1) @@ -473,7 +510,7 @@ class ChargeSociales extends CommonObject * * @param int $status Id status * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto - * @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) + * @param double $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount paid if you have it, 1 otherwise) * @return string Label */ public function LibStatut($status, $mode = 0, $alreadypaid = -1) diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 2f4f772fca0..9258ff63fc3 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -46,6 +46,11 @@ class PaymentSocialContribution extends CommonObject */ public $picto = 'payment'; + /** + * @var string Label + */ + public $label; + /** * @var int ID */ @@ -110,7 +115,7 @@ class PaymentSocialContribution extends CommonObject * Use this->amounts to have list of lines for the payment * * @param User $user User making payment - * @param int $closepaidcontrib 1=Also close payed contributions to paid, 0=Do nothing more + * @param int $closepaidcontrib 1=Also close paid contributions to paid, 0=Do nothing more * @return int <0 if KO, id of payment if OK */ public function create($user, $closepaidcontrib = 0) @@ -178,7 +183,7 @@ class PaymentSocialContribution extends CommonObject { $amount = price2num($amount); - // If we want to closed payed invoices + // If we want to closed paid invoices if ($closepaidcontrib) { $contrib = new ChargeSociales($this->db); @@ -192,7 +197,7 @@ class PaymentSocialContribution extends CommonObject $remaintopay = price2num($contrib->amount - $paiement - $creditnotes - $deposits, 'MT'); if ($remaintopay == 0) { - $result = $contrib->set_paid($user); + $result = $contrib->setPaid($user); } else dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); } } @@ -679,7 +684,7 @@ class PaymentSocialContribution extends CommonObject $result = ''; - if (empty($this->ref)) $this->ref = $this->lib; + if (empty($this->ref)) $this->ref = $this->label; $label = img_picto('', $this->picto).' '.$langs->trans("SocialContributionPayment").''; $label .= '
'.$langs->trans('Ref').': '.$this->ref; diff --git a/htdocs/compta/sociales/list.php b/htdocs/compta/sociales/list.php index 746a8480453..9a691a1785f 100644 --- a/htdocs/compta/sociales/list.php +++ b/htdocs/compta/sociales/list.php @@ -5,7 +5,8 @@ * Copyright (C) 2016 Frédéric France * Copyright (C) 2020 Pierre Ardoin * Copyright (C) 2020 Tobias Sekan - + * Copyright (C) 2021 Gauthier VERDOL + * * This 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 @@ -40,7 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; // Load translation files required by the page -$langs->loadLangs(array('compta', 'banks', 'bills')); +$langs->loadLangs(array('compta', 'banks', 'bills', 'hrm')); $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -56,7 +57,8 @@ $search_day_lim = GETPOST('search_day_lim', 'int'); $search_month_lim = GETPOST('search_month_lim', 'int'); $search_year_lim = GETPOST('search_year_lim', 'int'); $search_project_ref = GETPOST('search_project_ref', 'alpha'); -$search_project = GETPOST('search_project', 'alpha'); +$search_project = GETPOST('search_project', 'alpha'); +$search_users = GETPOST('search_users'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); @@ -91,6 +93,7 @@ $arrayfields = array( 'cs.rowid' =>array('label'=>"Ref", 'checked'=>1, 'position'=>10), 'cs.libelle' =>array('label'=>"Label", 'checked'=>1, 'position'=>20), 'cs.fk_type' =>array('label'=>"Type", 'checked'=>1, 'position'=>30), + 'cs.fk_user' =>array('label'=>"Employee", 'checked'=>1, 'position'=>30), 'p.ref' =>array('label'=>"ProjectRef", 'checked'=>1, 'position'=>40, 'enable'=>(!empty($conf->projet->enabled))), 'cs.date_ech' =>array('label'=>"Date", 'checked'=>1, 'position'=>50), 'cs.periode' =>array('label'=>"PeriodEndDate", 'checked'=>1, 'position'=>60), @@ -128,6 +131,7 @@ if (empty($reshook)) { $search_month_lim = ''; $search_project_ref = ''; $search_project = ''; + $search_users = ''; $search_array_options = array(); } } @@ -144,8 +148,8 @@ if (!empty($conf->projet->enabled)) $projectstatic = new Project($db); llxHeader('', $langs->trans("SocialContributions")); -$sql = "SELECT cs.rowid, cs.fk_type as type, "; -$sql .= " cs.amount, cs.date_ech, cs.libelle, cs.paye, cs.periode,"; +$sql = "SELECT cs.rowid, cs.fk_type as type, cs.fk_user,"; +$sql .= " cs.amount, cs.date_ech, cs.libelle as label, cs.paye, cs.periode,"; if (!empty($conf->projet->enabled)) $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label,"; $sql .= " c.libelle as type_label,"; $sql .= " SUM(pc.amount) as alreadypayed"; @@ -153,12 +157,14 @@ $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c,"; $sql .= " ".MAIN_DB_PREFIX."chargesociales as cs"; if (!empty($conf->projet->enabled)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = cs.fk_projet"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementcharge as pc ON pc.fk_charge = cs.rowid"; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON (cs.fk_user = u.rowid)"; $sql .= " WHERE cs.fk_type = c.id"; $sql .= " AND cs.entity = ".$conf->entity; // Search criteria if ($search_ref) $sql .= " AND cs.rowid=".$db->escape($search_ref); if ($search_label) $sql .= natural_search("cs.libelle", $search_label); if (!empty($conf->projet->enabled)) if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); +if (!empty($search_users)) $sql .= ' AND cs.fk_user IN('.implode(', ', $search_users).')'; if ($search_amount) $sql .= natural_search("cs.amount", $search_amount, 1); if ($search_status != '' && $search_status >= 0) $sql .= " AND cs.paye = ".$db->escape($search_status); $sql .= dolSqlDateFilter("cs.periode", $search_day_lim, $search_month_lim, $search_year_lim); @@ -179,7 +185,7 @@ if ($filtre) { if ($search_typeid) { $sql .= " AND cs.fk_type=".$db->escape($search_typeid); } -$sql .= " GROUP BY cs.rowid, cs.fk_type, cs.amount, cs.date_ech, cs.libelle, cs.paye, cs.periode, c.libelle"; +$sql .= " GROUP BY cs.rowid, cs.fk_type, cs.fk_user, cs.amount, cs.date_ech, cs.libelle, cs.paye, cs.periode, c.libelle"; if (!empty($conf->projet->enabled)) $sql .= ", p.rowid, p.ref, p.title"; $sql .= $db->order($sortfield, $sortorder); @@ -211,6 +217,9 @@ if ($search_label) $param .= '&search_label='.urlencode($search_label); if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); if ($search_typeid) $param .= '&search_typeid='.urlencode($search_typeid); +if ($search_users) { + foreach ($search_users as $id_user) $param .= '&search_users[]='.urlencode($id_user); +} if ($search_status != '' && $search_status != '-1') $param .= '&search_status='.urlencode($search_status); if ($year) $param .= '&year='.urlencode($year); @@ -289,6 +298,12 @@ if (!empty($arrayfields['cs.fk_type']['checked'])) { print ''; } +if (!empty($arrayfields['cs.fk_user']['checked'])) { + // Employee + print ''; + print $form->select_dolusers($search_users, 'search_users', 1, null, 0, '', '', '0', '0', 0, '', 0, '', '', 0, 0, true); +} + // Filter: Project ref if (!empty($arrayfields['p.ref']['checked'])) { print ''; @@ -343,6 +358,7 @@ if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titr if (!empty($arrayfields['cs.rowid']['checked'])) print_liste_field_titre($arrayfields['cs.rowid']['label'], $_SERVER["PHP_SELF"], "cs.rowid", '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['cs.libelle']['checked'])) print_liste_field_titre($arrayfields['cs.libelle']['label'], $_SERVER["PHP_SELF"], "cs.libelle", '', $param, 'class="left"', $sortfield, $sortorder); if (!empty($arrayfields['cs.fk_type']['checked'])) print_liste_field_titre($arrayfields['cs.fk_type']['label'], $_SERVER["PHP_SELF"], "cs.fk_type", '', $param, 'class="left"', $sortfield, $sortorder); +if (!empty($arrayfields['cs.fk_user']['checked'])) print_liste_field_titre("Employee", $_SERVER["PHP_SELF"], "u.lastname", "", $param, 'class="left"', $sortfield, $sortorder); if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], "p.ref", '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['cs.date_ech']['checked'])) print_liste_field_titre($arrayfields['cs.date_ech']['label'], $_SERVER["PHP_SELF"], "cs.date_ech", '', $param, 'align="center"', $sortfield, $sortorder); if (!empty($arrayfields['cs.periode']['checked'])) print_liste_field_titre($arrayfields['cs.periode']['label'], $_SERVER["PHP_SELF"], "cs.periode", '', $param, 'align="center"', $sortfield, $sortorder); @@ -358,14 +374,14 @@ print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], '', '', '', '', $ print ''; $i = 0; -$totalarray = array(); + $totalarray = $TLoadedUsers = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $chargesociale_static->id = $obj->rowid; $chargesociale_static->ref = $obj->rowid; - $chargesociale_static->label = $obj->libelle; + $chargesociale_static->label = $obj->label; $chargesociale_static->type_label = $obj->type_label; if (!empty($conf->projet->enabled)) { $projectstatic->id = $obj->project_id; @@ -389,7 +405,7 @@ while ($i < min($num, $limit)) // Label if (!empty($arrayfields['cs.libelle']['checked'])) { - print ''.dol_trunc($obj->libelle, 42).''; + print ''.dol_trunc($obj->label, 42).''; if (!$i) $totalarray['nbfield']++; } @@ -399,6 +415,22 @@ while ($i < min($num, $limit)) if (!$i) $totalarray['nbfield']++; } + if (!empty($arrayfields['cs.fk_user']['checked'])) { + // Employee + print ""; + if (!empty($obj->fk_user)) { + if (!empty($TLoadedUsers[$obj->fk_user])) $ustatic = $TLoadedUsers[$obj->fk_user]; + else { + $ustatic = new User($db); + $ustatic->fetch($obj->fk_user); + $TLoadedUsers[$obj->fk_user] = $ustatic; + } + print $ustatic->getNomUrl(-1); + } + print "\n"; + if (!$i) $totalarray['nbfield']++; + } + // Project ref if (!empty($arrayfields['p.ref']['checked'])) { print ''; diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 0be6659f7b4..03c128e841f 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -44,12 +44,12 @@ $nbofyear = 4; $year = GETPOST('year', 'int'); if (empty($year)) { - $year_current = strftime("%Y", dol_now()); - $month_current = strftime("%m", dol_now()); + $year_current = dol_print_date(dol_now(), "%Y"); + $month_current = dol_print_date(dol_now(), "%m"); $year_start = $year_current - ($nbofyear - 1); } else { $year_current = $year; - $month_current = strftime("%m", dol_now()); + $month_current = dol_print_date(dol_now(), "%m"); $year_start = $year - ($nbofyear - 1); } $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); @@ -58,12 +58,12 @@ $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); // We define date_start and date_end if (empty($date_start) || empty($date_end)) // We define date_start and date_end { - $q = GETPOST("q") ?GETPOST("q") : 0; + $q = GETPOST("q") ? GETPOST("q") : 0; if ($q == 0) { // We define date_start and date_end $year_end = $year_start + ($nbofyear - 1); - $month_start = GETPOST("month") ?GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOSTISSET("month") ? GETPOST("month", 'int') : ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1); if (!GETPOST('month')) { if (!GETPOST("year") && $month_start > $month_current) @@ -86,8 +86,10 @@ $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); $tmps = dol_getdate($date_start); +$mothn_start = $tmps['mon']; $year_start = $tmps['year']; $tmpe = dol_getdate($date_end); +$month_end = $tmpe['mon']; $year_end = $tmpe['year']; $nbofyear = ($year_end - $year_start) + 1; @@ -306,7 +308,7 @@ $now = dol_now(); $casenow = dol_print_date($now, "%Y-%m"); // Loop on each month -$nb_mois_decalage = $conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START - 1) : 0; +$nb_mois_decalage = GETPOSTISSET('date_startmonth') ? (GETPOST('date_startmonth', 'int') - 1) : (empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 0 : ($conf->global->SOCIETE_FISCAL_MONTH_START - 1)); for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { $mois_modulo = $mois; // ajout @@ -338,68 +340,75 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) if ($annee >= $year_start) // We ignore $annee < $year_start, we loop on it to be able to make delta, nothing is output. { if ($modecompta == 'CREANCES-DETTES') { - // Valeur CA du mois w/o VAT + // Value turnover of month w/o VAT print ''; - if ($cum_ht[$case]) - { - $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre. - print ''.price($cum_ht[$case], 1).''; - } else { - if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print ' '; } + if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) { + if ($cum_ht[$case]) { + $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre. + print ''.price($cum_ht[$case], 1).''; + } else { + if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print ' '; } + } } print ""; } - // Valeur CA du mois + // Value turnover of month print ''; - if ($cum[$case]) - { - $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre. - if ($modecompta != 'BOOKKEEPING') print ''; - print price($cum[$case], 1); - if ($modecompta != 'BOOKKEEPING') print ''; - } else { - if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print ' '; } + if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) { + if ($cum[$case]) { + $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre. + if ($modecompta != 'BOOKKEEPING') print ''; + print price($cum[$case], 1); + if ($modecompta != 'BOOKKEEPING') print ''; + } else { + if ($minyearmonth < $case && $case <= max($maxyearmonth, $nowyearmonth)) { print '0'; } else { print ' '; } + } } print ""; - // Pourcentage du mois - if ($annee_decalage > $minyear && $case <= $casenow) - { - if ($cum[$caseprev] && $cum[$case]) + // Percentage of month + print ''; + //var_dump($annee.' '.$year_end.' '.$mois.' '.$month_end); + if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) { + if ($annee_decalage > $minyear && $case <= $casenow) { - $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").'%'; + if ($cum[$caseprev] && $cum[$case]) + { + $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").'%'; + } + if ($cum[$caseprev] && !$cum[$case]) + { + print '-100%'; + } + if (!$cum[$caseprev] && $cum[$case]) + { + //print '+Inf%'; + print '-'; + } + if (isset($cum[$caseprev]) && !$cum[$caseprev] && !$cum[$case]) + { + print '+0%'; + } + if (!isset($cum[$caseprev]) && !$cum[$case]) + { + print '-'; + } + } else { + if ($minyearmonth <= $case && $case <= $maxyearmonth) { print '-'; } else { print ' '; } } - if ($cum[$caseprev] && !$cum[$case]) - { - print '-100%'; - } - if (!$cum[$caseprev] && $cum[$case]) - { - //print '+Inf%'; - print '-'; - } - if (isset($cum[$caseprev]) && !$cum[$caseprev] && !$cum[$case]) - { - print '+0%'; - } - if (!isset($cum[$caseprev]) && !$cum[$case]) - { - print '-'; - } - } else { - print ''; - if ($minyearmonth <= $case && $case <= $maxyearmonth) { print '-'; } else { print ' '; } - print ''; } + print ''; if ($annee_decalage < $year_end || ($annee_decalage == $year_end && $mois > 12 && $annee < $year_end)) print ' '; } - $total_ht[$annee] += ((!empty($cum_ht[$case])) ? $cum_ht[$case] : 0); - $total[$annee] += $cum[$case]; + if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) { + $total_ht[$annee] += ((!empty($cum_ht[$case])) ? $cum_ht[$case] : 0); + $total[$annee] += $cum[$case]; + } } print ''; @@ -470,34 +479,37 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) } */ -// Affiche total +// Show total print ''.$langs->trans("Total").''; for ($annee = $year_start; $annee <= $year_end; $annee++) { if ($modecompta == 'CREANCES-DETTES') { // Montant total HT - if ($total_ht[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) - { - print ''.($total_ht[$annee] ?price($total_ht[$annee]) : "0").""; + if ($total_ht[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) { + print ''; + print ($total_ht[$annee] ?price($total_ht[$annee]) : "0"); + print ""; } else { print ' '; } } - // Montant total - if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) - { - print ''.($total[$annee] ?price($total[$annee]) : "0").""; + // Total amount + if ($total[$annee] || ($annee >= $minyear && $annee <= max($nowyear, $maxyear))) { + print ''; + print ($total[$annee] ?price($total[$annee]) : "0"); + print ""; } else { print ' '; } // Pourcentage total - if ($annee > $minyear && $annee <= max($nowyear, $maxyear)) - { + if ($annee > $minyear && $annee <= max($nowyear, $maxyear)) { if ($total[$annee - 1] && $total[$annee]) { $percent = (round(($total[$annee] - $total[$annee - 1]) / $total[$annee - 1], 4) * 100); - print ''.($percent >= 0 ? "+$percent" : "$percent").'%'; + print ''; + print ($percent >= 0 ? "+$percent" : "$percent").'%'; + print ''; } if ($total[$annee - 1] && !$total[$annee]) { diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index 493f01ee53c..a961d4f1994 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2013 Regis Houssin * Copyright (C) 2015-2017 Alexandre Spangaro * Copyright (C) 2018 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL * * This 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,15 +28,23 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/paymentvat.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; +if (!empty($conf->accounting->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} + // Load translation files required by the page $langs->loadLangs(array('compta', 'banks', 'bills')); $id = GETPOST("id", 'int'); $action = GETPOST("action", "alpha"); +$confirm = GETPOST('confirm'); $refund = GETPOST("refund", "int"); +$auto_create_payment = GETPOST("auto_create_paiement", "int"); + if (empty($refund)) $refund = 0; $datev = dol_mktime(12, 0, 0, GETPOST("datevmonth", 'int'), GETPOST("datevday", 'int'), GETPOST("datevyear", 'int')); @@ -73,32 +82,71 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) if ($action == 'setdatev' && $user->rights->tax->charges->creer) { - $object->fetch($id); - $object->datev = $datev; - $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); + $object->fetch($id); + $object->datev = $datev; + $result = $object->update($user); + if ($result < 0) dol_print_error($db, $object->error); - $action = ''; + $action = ''; +} + +// payment mode +if ($action == 'setmode' && $user->rights->tax->charges->creer) { + $object->fetch($id); + $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); + if ($result < 0) + setEventMessages($object->error, $object->errors, 'errors'); +} + +// Bank account +if ($action == 'setbankaccount' && $user->rights->tax->charges->creer) { + $object->fetch($id); + $result = $object->setBankAccount(GETPOST('fk_account', 'int')); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } +} + +// Classify paid +if ($action == 'confirm_paid' && $user->rights->tax->charges->creer && $confirm == 'yes') +{ + $object->fetch($id); + $result = $object->setPaid($user); +} + +if ($action == 'reopen' && $user->rights->tax->charges->creer) { + $result = $object->fetch($id); + if ($object->paye) + { + $result = $object->setUnpaid($user); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); + exit(); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) { - $error = 0; + $error = 0; - $object->accountid = GETPOST("accountid", 'int'); - $object->type_payment = GETPOST("type_payment", 'alphanohtml'); + $object->fk_account = GETPOST("accountid", 'int'); + $object->type_payment = GETPOST("type_payment", 'alphanohtml'); $object->num_payment = GETPOST("num_payment", 'alphanohtml'); $object->datev = $datev; - $object->datep = $datep; + $object->datep = $datep; $amount = price2num(GETPOST("amount", 'alpha')); if ($refund == 1) { $amount = -$amount; } - $object->amount = $amount; + $object->amount = $amount; $object->label = GETPOST("label", 'alpha'); - $object->note_private = GETPOST("note", 'restricthtml'); + $object->note = GETPOST("note", 'none'); if (empty($object->datep)) { @@ -110,7 +158,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PeriodEndDate")), null, 'errors'); $error++; } - if (empty($object->type_payment) || $object->type_payment < 0) + if (!empty($auto_create_payment) && (empty($object->type_payment) || $object->type_payment < 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("PaymentMode")), null, 'errors'); $error++; @@ -120,38 +168,81 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); $error++; } + if (!empty($auto_create_payment) && ($object->fk_account <= 0)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountToCredit")), null, 'errors'); + $error++; + } if (!$error) { - $db->begin(); + $ret = $object->create($user); + if ($ret < 0) $error++; - $ret = $object->addPayment($user); - if ($ret > 0) + // Auto create payment + if (!empty($auto_create_payment) && !$error) { - $db->commit(); - header("Location: list.php"); + $db->begin(); + + // Create a line of payments + $paiement = new PaymentVAT($db); + $paiement->chid = $object->id; + $paiement->datepaye = $datep; + $paiement->amounts = array($object->id=>$amount); // Tableau de montant + $paiement->paiementtype = GETPOST("type_payment", 'alphanohtml'); + $paiement->num_payment = GETPOST("num_payment", 'alphanohtml'); + $paiement->note = GETPOST("note", 'none'); + + if (!$error) + { + $paymentid = $paiement->create($user, (int) GETPOST('closepaidtva')); + if ($paymentid < 0) + { + $error++; + setEventMessages($paiement->error, null, 'errors'); + $action = 'create'; + } + } + + if (!$error) + { + $result = $paiement->addPaymentToBank($user, 'payment_vat', '(VATPayment)', GETPOST('accountid', 'int'), '', ''); + if (!($result > 0)) + { + $error++; + setEventMessages($paiement->error, null, 'errors'); + } + } + + if (!$error) + { + $db->commit(); + } + else { + $db->rollback(); + } + } + if (empty($error)) { + header("Location: card.php?id=" . $object->id); exit; - } else { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - $action = "create"; } } $action = 'create'; } -if ($action == 'delete') +if ($action == 'confirm_delete' && $confirm == 'yes') { - $result = $object->fetch($id); + $result = $object->fetch($id); + $totalpaye = $object->getSommePaiement(); - if ($object->rappro == 0) + if (empty($totalpaye)) { - $db->begin(); + $db->begin(); - $ret = $object->delete($user); - if ($ret > 0) - { + $ret = $object->delete($user); + if ($ret > 0) + { if ($object->fk_bank) { $accountline = new AccountLine($db); @@ -164,21 +255,99 @@ if ($action == 'delete') $db->commit(); header("Location: ".DOL_URL_ROOT.'/compta/tva/list.php'); exit; - } else { + } + else { $object->error = $accountline->error; $db->rollback(); setEventMessages($object->error, $object->errors, 'errors'); } - } else { - $db->rollback(); - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - $mesg = 'Error try do delete a line linked to a conciliated bank transaction'; - setEventMessages($mesg, null, 'errors'); + } + else { + $db->rollback(); + setEventMessages($object->error, $object->errors, 'errors'); + } + } + else { + setEventMessages($langs->trans('DisabledBecausePayments'), null, 'errors'); } } +if ($action == 'update' && !$_POST["cancel"] && $user->rights->tax->charges->creer) +{ + $amount = price2num(GETPOST('amount')); + + if (empty($amount)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'edit'; + } + elseif (!is_numeric($amount)) + { + setEventMessages($langs->trans("ErrorFieldMustBeANumeric", $langs->transnoentities("Amount")), null, 'errors'); + $action = 'create'; + } + else { + $result = $object->fetch($id); + + $object->amount = price2num($amount); + + $result = $object->update($user); + if ($result <= 0) + { + setEventMessages($object->error, $object->errors, '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->fetch($id); + + if ($object->id > 0) + { + $object->paye = 0; + $object->id = $object->ref = null; + + if (GETPOST('clone_label', 'alphanohtml')) { + $object->label = GETPOST('clone_label', 'alphanohtml'); + } + else { + $object->label = $langs->trans("CopyOf").' '.$object->label; + } + + $newdateperiod = dol_mktime(0, 0, 0, GETPOST('clone_periodmonth', 'int'), GETPOST('clone_periodday', 'int'), GETPOST('clone_periodyear', 'int')); + if ($newdateperiod) $object->datev = $newdateperiod; + + //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); + } +} /* * View @@ -205,11 +374,10 @@ if ($id) if ($action == 'create') { print load_fiche_titre($langs->trans("VAT").' - '.$langs->trans("New")); - if (!empty($conf->use_javascript_ajax)) - { - print "\n".''."\n"; } - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - print '
'; - print '
'; - print $langs->trans("Type").':   '; - print '
'; - print ''; - print '   '; - print ''; - print '
'; - print "
\n"; + print '
'; + print '
'; + print $langs->trans("Type").':   '; + print '
'; + print ''; + print '   '; + print ''; + print '
'; + print "
\n"; - print dol_get_fiche_head(); + dol_fiche_head(); - print ''; + print '
'; - print ""; - print ''; + print ''; + print ''; - print ''; + print ''; // Label if ($refund == 1) { @@ -268,32 +460,47 @@ if ($action == 'create') // Amount print ''; - if (!empty($conf->banque->enabled)) - { - print ''; - } - - // Type payment - print '\n"; print ""; + if (!empty($conf->banque->enabled)) + { + print ''; + } + + // Auto create payment + print ''; + print ''."\n"; + // Number - print ''."\n"; - // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Comments + print ''; + print ''; + print ''; + print ''; - print '
'.$langs->trans("DatePayment").''; - print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); - print '
'.$langs->trans("DatePayment").''; + print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); + print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; - print $form->selectDate((GETPOST("datevmonth", 'int') ? $datev : -1), "datev", '', '', '', 'add', 1, 1); - print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; + print $form->selectDate((GETPOST("datevmonth", 'int') ? $datev : -1), "datev", '', '', '', 'add', 1, 1); + print '
'.$langs->trans("Amount").'
'.$langs->trans("BankAccount").''; - $form->select_comptes(GETPOST("accountid", 'int'), "accountid", 0, "courant=1", 2); // List of bank account available - print '
'.$langs->trans("PaymentMode").''; + // Type payment + print '
'.$langs->trans("PaymentMode").''; $form->select_types_paiements(GETPOST("type_payment"), "type_payment"); print "
'.$langs->trans("BankAccount").''; + $form->select_comptes(GETPOST("accountid", 'int'), "accountid", 0, "courant=1", 1); // List of bank account available + print '
'.$langs->trans('AutomaticCreationPayment').'
'.$langs->trans('Numero'); + print '
'.$langs->trans('Numero'); print ' ('.$langs->trans("ChequeOrTransferNumber").')'; print '
'.$langs->trans("Comments").'
'; + // Other attributes + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - print dol_get_fiche_end(); + // Bouton Save payment + print ''; + print $langs->trans("ClosePaidVATAutomatically"); + print ''; + + print ''; + + dol_fiche_end(); print '
'; print ''; @@ -301,7 +508,7 @@ if ($action == 'create') print ''; print '
'; - print '
'; + print ''; } // View mode @@ -309,7 +516,40 @@ if ($id) { $head = vat_prepare_head($object); - print dol_get_fiche_head($head, 'card', $langs->trans("VATPayment"), -1, 'payment'); + $totalpaye = $object->getSommePaiement(); + + // Clone confirmation + if ($action === 'clone') + { + $formquestion = array( + array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), + ); + + //$formquestion[] = array('type' => 'date', 'name' => 'clone_date_ech', 'label' => $langs->trans("Date"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'name' => 'clone_period', 'label' => $langs->trans("PeriodEndDate"), 'value' => -1); + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVAT', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 240); + } + + if ($action == 'paid') + { + $text = $langs->trans('ConfirmPayVAT'); + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PayVAT'), $text, "confirm_paid", '', '', 2); + } + + if ($action == 'delete') + { + $text = $langs->trans('ConfirmDeleteVAT'); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteVAT'), $text, 'confirm_delete', '', '', 2); + } + + if ($action == 'edit') + { + print "
id&action=update\" method=\"post\">"; + print ''; + } + + dol_fiche_head($head, 'card', $langs->trans("VATPayment"), -1, 'payment'); $morehtmlref = '
'; // Label of social contribution @@ -320,9 +560,12 @@ if ($id) $linkback = ''.$langs->trans("BackToList").''; + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', ''); print '
'; + print '
'; print '
'; print ''; @@ -330,10 +573,10 @@ if ($id) // Label //print ''; - print ""; + /*print ""; print ''; + print '';*/ print ''; - print ''; + if ($action == 'edit') { + print ''; + } else { + print ''; + } + // Mode of payment + print ''; + + // Bank account if (!empty($conf->banque->enabled)) { - if ($object->fk_account > 0) - { - $bankline = new AccountLine($db); - $bankline->fetch($object->fk_bank); - - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; } // Other attributes @@ -369,22 +636,180 @@ if ($id) print ''; - print dol_get_fiche_end(); + print '
'; + print '
'; + + $nbcols = 3; + if (!empty($conf->banque->enabled)) { + $nbcols++; + } + + /* + * Payments + */ + $sql = "SELECT p.rowid, p.num_paiement as num_payment, p.datep as dp, p.amount,"; + $sql .= " c.code as type_code,c.libelle as paiement_type,"; + $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.currency_code as bacurrency_code, ba.fk_accountancy_journal'; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_vat as p"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as c ON p.fk_typepaiement = c.id"; + $sql .= ", ".MAIN_DB_PREFIX."tva as tva"; + $sql .= " WHERE p.fk_tva = ".$id; + $sql .= " AND p.fk_tva = tva.rowid"; + $sql .= " AND tva.entity IN (".getEntity('tax').")"; + $sql .= " ORDER BY dp DESC"; + + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $totalpaye = 0; + + $num = $db->num_rows($resql); + $i = 0; $total = 0; + + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print '
'.$langs->trans("Label").''.$object->label.'
'.$langs->trans("DatePayment").''; print dol_print_date($object->datep, 'day'); - print '
'; print $form->editfieldkey($form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")), 'datev', $object->datev, $object, $user->rights->tax->charges->creer, 'day'); @@ -342,22 +585,46 @@ if ($id) //print dol_print_date($object->datev,'day'); print '
'.$langs->trans("Amount").''.price($object->amount).'
' . $langs->trans("Amount") . '
' . $langs->trans("Amount") . '' . price($object->amount) . '
'; + print ''; + if ($action != 'editmode') + print ''; + print '
'; + print $langs->trans('PaymentMode'); + print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; + print '
'; + if ($action == 'editmode') { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->type_payment, 'mode_reglement_id'); + } else { + $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->type_payment, 'none'); + } + print '
'.$langs->trans('BankTransactionLine').''; - print $bankline->getNomUrl(1, 0, 'showall'); - print '
'; + print ''; + print '
'; + print $langs->trans('BankAccount'); + print ''; + if ($action != 'editbankaccount' && $user->rights->tax->charges->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 ''; + print ''; + print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } + print ''; + print ''; + + if ($num > 0) + { + $bankaccountstatic = new Account($db); + while ($i < $num) + { + $objp = $db->fetch_object($resql); + + print ''; + print '\n"; + $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; + print "\n"; + if (!empty($conf->banque->enabled)) + { + $bankaccountstatic->id = $objp->baid; + $bankaccountstatic->ref = $objp->baref; + $bankaccountstatic->label = $objp->baref; + $bankaccountstatic->number = $objp->banumber; + $bankaccountstatic->currency_code = $objp->bacurrency_code; + + if (!empty($conf->accounting->enabled)) { + $bankaccountstatic->account_number = $objp->account_number; + + $accountingjournal = new AccountingJournal($db); + $accountingjournal->fetch($objp->fk_accountancy_journal); + $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1); + } + + print ''; + } + print '\n"; + print ""; + $totalpaye += $objp->amount; + $i++; + } + } + else { + print ''; + print ''; + print ''; + } + + print '\n"; + print '\n"; + + $resteapayer = $object->amount - $totalpaye; + $cssforamountpaymentcomplete = 'amountpaymentcomplete'; + + print '"; + print '\n"; + + print "
'.$langs->trans("RefPayment").''.$langs->trans("Date").''.$langs->trans("Type").''.$langs->trans('BankAccount').''.$langs->trans("Amount").'
'; + print ''.img_object($langs->trans("Payment"), "payment").' '.$objp->rowid.''.dol_print_date($db->jdate($objp->dp), 'day')."".$labeltype.' '.$objp->num_payment."'; + if ($bankaccountstatic->id) + print $bankaccountstatic->getNomUrl(1, 'transactions'); + print ''.price($objp->amount)."
'.$langs->trans("None").'
'.$langs->trans("AlreadyPaid")." :".price($totalpaye)."
'.$langs->trans("AmountExpected")." :".price($object->amount)."
'.$langs->trans("RemainderToPay")." :'.price($resteapayer)."
"; + print '
'; + + $db->free($resql); + } + else { + dol_print_error($db); + } + + print '
'; + print '
'; + print ''; + + print '
'; + + dol_fiche_end(); + + if ($action == 'edit') + { + print '
'; + print ''; + print '   '; + print ''; + print '
'; + print "
\n"; + } /* * Action buttons */ print "
\n"; - if ($object->rappro == 0) + if ($action != 'edit') { - if (!empty($user->rights->tax->charges->supprimer)) + // Reopen + if ($object->paye && $user->rights->tax->charges->creer) { - print ''; - } else { - print ''; + print ""; + } + + // Edit + if ($object->paye == 0 && $user->rights->tax->charges->creer) + { + print ""; + } + + // Emit payment + if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->tax->charges->creer) + { + print ""; + } + + // Classify 'paid' + if ($object->paye == 0 + && ( + (round($resteapayer) <= 0 && $object->amount > 0) + || (round($resteapayer) >= 0 && $object->amount < 0) + ) + && $user->rights->tax->charges->creer) + { + print ""; + } + + // Clone + if ($user->rights->tax->charges->creer) + { + print ""; + } + + if (!empty($user->rights->tax->charges->supprimer) && empty($totalpaye)) + { + print ''; + } + else { + print ''; } - } else { - print ''; } print "
"; } diff --git a/htdocs/compta/tva/class/paymentvat.class.php b/htdocs/compta/tva/class/paymentvat.class.php new file mode 100644 index 00000000000..13369e596bc --- /dev/null +++ b/htdocs/compta/tva/class/paymentvat.class.php @@ -0,0 +1,724 @@ + + * Copyright (C) 2004-2007 Laurent Destailleur + * Copyright (C) 2021 Gauthier VERDOL + * + * This 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/sociales/class/paymentsocialcontribution.class.php + * \ingroup facture + * \brief File of class to manage payment of social contributions + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; + + +/** + * Class to manage payments of social contributions + */ +class PaymentVAT extends CommonObject +{ + /** + * @var string ID to identify managed object + */ + public $element = 'payment_vat'; + + /** + * @var string Name of table without prefix where object is stored + */ + public $table_element = 'payment_vat'; + + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'payment'; + + /** + * @var int ID + */ + public $fk_tva; + + public $datec = ''; + public $tms = ''; + public $datep = ''; + + /** + * @deprecated + * @see $amount + */ + public $total; + + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts + + /** + * @var int ID + */ + public $fk_typepaiement; + + /** + * @var string + * @deprecated + */ + public $num_paiement; + + /** + * @var string + */ + public $num_payment; + + /** + * @var int ID + */ + public $fk_bank; + + /** + * @var int ID + */ + public $fk_user_creat; + + /** + * @var int ID + */ + public $fk_user_modif; + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } + + /** + * Create payment of social contribution into database. + * Use this->amounts to have list of lines for the payment + * + * @param User $user User making payment + * @param int $closepaidcontrib 1=Also close payed contributions to paid, 0=Do nothing more + * @return int <0 if KO, id of payment if OK + */ + public function create($user, $closepaidcontrib = 0) + { + global $conf, $langs; + + $error = 0; + + $now = dol_now(); + + dol_syslog(get_class($this)."::create", LOG_DEBUG); + + // Validate parametres + if (!$this->datepaye) + { + $this->error = 'ErrorBadValueForParameterCreatePaymentVAT'; + return -1; + } + + // Clean parameters + if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; + if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; + if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + + $totalamount = 0; + foreach ($this->amounts as $key => $value) // How payment is dispatch + { + $newvalue = price2num($value, 'MT'); + $this->amounts[$key] = $newvalue; + $totalamount += $newvalue; + } + $totalamount = price2num($totalamount); + + // Check parameters + if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + + + $this->db->begin(); + + if ($totalamount != 0) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_vat (fk_tva, datec, datep, amount,"; + $sql .= " fk_typepaiement, num_paiement, note, fk_user_creat, fk_bank)"; + $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; + $sql .= " '".$this->db->idate($this->datepaye)."',"; + $sql .= " ".$totalamount.","; + $sql .= " ".$this->paiementtype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note)."', ".$user->id.","; + $sql .= " 0)"; + + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_vat"); + + // Insere tableau des montants / factures + foreach ($this->amounts as $key => $amount) + { + $contribid = $key; + if (is_numeric($amount) && $amount <> 0) + { + $amount = price2num($amount); + + // If we want to closed payed invoices + if ($closepaidcontrib) + { + $contrib = new Tva($this->db); + $contrib->fetch($contribid); + $paiement = $contrib->getSommePaiement(); + //$creditnotes=$contrib->getSumCreditNotesUsed(); + $creditnotes = 0; + //$deposits=$contrib->getSumDepositsUsed(); + $deposits = 0; + $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); + $remaintopay = price2num($contrib->amount - $paiement - $creditnotes - $deposits, 'MT'); + if ($remaintopay == 0) + { + $result = $contrib->setPaid($user); + } + else dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); + } + } + } + } + else { + $error++; + } + } + + $result = $this->call_trigger('PAYMENTVAT_CREATE', $user); + if ($result < 0) $error++; + + if ($totalamount != 0 && !$error) + { + $this->amount = $totalamount; + $this->total = $totalamount; // deprecated + $this->db->commit(); + return $this->id; + } + else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from database + * + * @param int $id Id object + * @return int <0 if KO, >0 if OK + */ + public function fetch($id) + { + global $langs; + $sql = "SELECT"; + $sql .= " t.rowid,"; + $sql .= " t.fk_tva,"; + $sql .= " t.datec,"; + $sql .= " t.tms,"; + $sql .= " t.datep,"; + $sql .= " t.amount,"; + $sql .= " t.fk_typepaiement,"; + $sql .= " t.num_paiement as num_payment,"; + $sql .= " t.note,"; + $sql .= " t.fk_bank,"; + $sql .= " t.fk_user_creat,"; + $sql .= " t.fk_user_modif,"; + $sql .= " pt.code as type_code, pt.libelle as type_label,"; + $sql .= ' b.fk_account'; + $sql .= " FROM ".MAIN_DB_PREFIX."payment_vat as t LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepaiement = pt.id"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; + $sql .= " WHERE t.rowid = ".$id; + // TODO link on entity of tax; + + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); + + $this->id = $obj->rowid; + $this->ref = $obj->rowid; + + $this->fk_tva = $obj->fk_tva; + $this->datec = $this->db->jdate($obj->datec); + $this->tms = $this->db->jdate($obj->tms); + $this->datep = $this->db->jdate($obj->datep); + $this->amount = $obj->amount; + $this->fk_typepaiement = $obj->fk_typepaiement; + $this->num_paiement = $obj->num_payment; + $this->num_payment = $obj->num_payment; + $this->note = $obj->note; + $this->fk_bank = $obj->fk_bank; + $this->fk_user_creat = $obj->fk_user_creat; + $this->fk_user_modif = $obj->fk_user_modif; + + $this->type_code = $obj->type_code; + $this->type_label = $obj->type_label; + + $this->bank_account = $obj->fk_account; + $this->bank_line = $obj->fk_bank; + } + $this->db->free($resql); + + return 1; + } + else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } + + + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function update($user = null, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + // Clean parameters + + if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; + if (isset($this->amount)) $this->amount = trim($this->amount); + if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; + if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated + if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); + if (isset($this->note)) $this->note = trim($this->note); + if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; + if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; + if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + + + + // Check parameters + // Put here code to add control on parameters values + + // Update request + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_vat SET"; + + $sql .= " fk_tva=".(isset($this->fk_tva) ? $this->fk_tva : "null").","; + $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + $sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').","; + $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").","; + $sql .= " fk_typepaiement=".(isset($this->fk_typepaiement) ? $this->fk_typepaiement : "null").","; + $sql .= " num_paiement=".(isset($this->num_paiement) ? "'".$this->db->escape($this->num_paiement)."'" : "null").","; + $sql .= " note=".(isset($this->note) ? "'".$this->db->escape($this->note)."'" : "null").","; + $sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").","; + $sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").","; + $sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null").""; + + + $sql .= " WHERE rowid=".$this->id; + + $this->db->begin(); + + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + + // Commit or rollback + if ($error) + { + foreach ($this->errors as $errmsg) + { + dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); + $this->error .= ($this->error ? ', '.$errmsg : $errmsg); + } + $this->db->rollback(); + return -1 * $error; + } + else { + $this->db->commit(); + return 1; + } + } + + + /** + * Delete object in database + * + * @param User $user User that delete + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ + public function delete($user, $notrigger = 0) + { + global $conf, $langs; + $error = 0; + + dol_syslog(get_class($this)."::delete"); + + $this->db->begin(); + + if ($this->bank_line > 0) + { + $accline = new AccountLine($this->db); + $accline->fetch($this->bank_line); + $result = $accline->delete(); + if ($result < 0) { + $this->errors[] = $accline->error; + $error++; + } + } + + if (!$error) + { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_vat"; + $sql .= " WHERE rowid=".$this->id; + + dol_syslog(get_class($this)."::delete", LOG_DEBUG); + $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; + } + } + + + + /** + * Load an object from its id and create a new one in database + * + * @param User $user User making the clone + * @param int $fromid Id of object to clone + * @return int New id of clone + */ + public function createFromClone(User $user, $fromid) + { + $error = 0; + + $object = new PaymentSocialContribution($this->db); + + $this->db->begin(); + + // Load source object + $object->fetch($fromid); + $object->id = 0; + $object->statut = 0; + + // Clear fields + // ... + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->create($user); + + // Other options + if ($result < 0) + { + $this->error = $object->error; + $error++; + } + + unset($object->context['createfromclone']); + + // End + if (!$error) + { + $this->db->commit(); + return $object->id; + } + else { + $this->db->rollback(); + return -1; + } + } + + + /** + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void + */ + public function initAsSpecimen() + { + $this->id = 0; + + $this->fk_tva = 0; + $this->datec = ''; + $this->tms = ''; + $this->datep = ''; + $this->amount = ''; + $this->fk_typepaiement = ''; + $this->num_payment = ''; + $this->note_private = ''; + $this->note_public = ''; + $this->fk_bank = 0; + $this->fk_user_creat = 0; + $this->fk_user_modif = 0; + } + + + /** + * Add record into bank for payment with links between this bank record and invoices of payment. + * All payment properties must have been set first like after a call to create(). + * + * @param User $user Object of user making payment + * @param string $mode 'payment_sc' + * @param string $label Label to use in bank record + * @param int $accountid Id of bank account to do link with + * @param string $emetteur_nom Name of transmitter + * @param string $emetteur_banque Name of bank + * @return int <0 if KO, >0 if OK + */ + public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) + { + global $conf; + + // Clean data + $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); + + $error = 0; + + if (!empty($conf->banque->enabled)) + { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + + $acc = new Account($this->db); + $acc->fetch($accountid); + + $total = $this->total; + if ($mode == 'payment_vat') $total = -$total; + + // Insert payment into llx_bank + $bank_line_id = $acc->addline( + $this->datepaye, + $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") + $label, + $total, + $this->num_payment, + '', + $user, + $emetteur_nom, + $emetteur_banque + ); + + // Mise a jour fk_bank dans llx_paiement. + // On connait ainsi le paiement qui a genere l'ecriture bancaire + if ($bank_line_id > 0) + { + $result = $this->update_fk_bank($bank_line_id); + if ($result <= 0) + { + $error++; + dol_print_error($this->db); + } + + // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction + $url = ''; + if ($mode == 'payment_vat') $url = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='; + if ($url) + { + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); + if ($result <= 0) + { + $error++; + dol_print_error($this->db); + } + } + + // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) + $linkaddedforthirdparty = array(); + foreach ($this->amounts as $key => $value) + { + if ($mode == 'payment_vat') + { + $tva = new Tva($this->db); + $tva->fetch($key); + $result = $acc->add_url_line($bank_line_id, $tva->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', '('.$tva->label.')', 'vat'); + if ($result <= 0) dol_print_error($this->db); + } + } + } + else { + $this->error = $acc->error; + $error++; + } + } + + if (!$error) + { + return 1; + } + else { + return -1; + } + } + + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Mise a jour du lien entre le paiement de tva et la ligne dans llx_bank generee + * + * @param int $id_bank Id if bank + * @return int >0 if OK, <=0 if KO + */ + public function update_fk_bank($id_bank) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."payment_vat SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id; + + dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); + $result = $this->db->query($sql); + if ($result) + { + return 1; + } + else { + $this->error = $this->db->error(); + return 0; + } + } + + + /** + * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut($this->statut, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Renvoi le libelle d'un statut donne + * + * @param int $status Statut + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Libelle du statut + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + + $langs->load('compta'); + /*if ($mode == 0) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 1) + { + if ($status == 0) return $langs->trans('ToValidate'); + if ($status == 1) return $langs->trans('Validated'); + } + if ($mode == 2) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 3) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 4) + { + if ($status == 0) return img_picto($langs->trans('ToValidate'),'statut1').' '.$langs->trans('ToValidate'); + if ($status == 1) return img_picto($langs->trans('Validated'),'statut4').' '.$langs->trans('Validated'); + } + if ($mode == 5) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + } + if ($mode == 6) + { + if ($status == 0) return $langs->trans('ToValidate').' '.img_picto($langs->trans('ToValidate'),'statut1'); + if ($status == 1) return $langs->trans('Validated').' '.img_picto($langs->trans('Validated'),'statut4'); + }*/ + return ''; + } + + /** + * Return clicable name (with picto eventually) + * + * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto + * @param int $maxlen Longueur max libelle + * @return string Chaine avec URL + */ + public function getNomUrl($withpicto = 0, $maxlen = 0) + { + global $langs; + + $result = ''; + + if (empty($this->ref)) $this->ref = $this->lib; + + $label = img_picto('', $this->picto).' '.$langs->trans("VATPayment").''; + $label .= '
'.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->label)) { + $labeltoshow = $this->label; + $reg = array(); + if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) + { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + $labeltoshow = $langs->trans($reg[1]); + } + $label .= '
'.$langs->trans('Label').': '.$labeltoshow; + } + if ($this->datep) $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->datep, 'day'); + + if (!empty($this->id)) { + $link = ''; + $linkend = ''; + + if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + if ($withpicto && $withpicto != 2) $result .= ' '; + if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } + + return $result; + } +} diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index 51cac4c7394..a39a00d8b01 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -4,6 +4,7 @@ * Copyright (C) 2011-2017 Alexandre Spangaro * Copyright (C) 2018 Philippe Grand * Copyright (C) 2018 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -56,13 +57,13 @@ class Tva extends CommonObject public $num_payment; /** - * @var string label - */ - public $label; + * @var string label + */ + public $label; - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_bank; /** @@ -71,35 +72,39 @@ class Tva extends CommonObject public $accountid; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_creat; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; - /** + + const STATUS_UNPAID = 0; + const STATUS_PAID = 1; + + /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Create in database - * - * @param User $user User that create - * @return int <0 if KO, >0 if OK - */ - public function create($user) - { - global $conf, $langs; + /** + * Create in database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; $error = 0; $now = dol_now(); @@ -107,8 +112,9 @@ class Tva extends CommonObject // Clean parameters $this->amount = trim($this->amount); $this->label = trim($this->label); + $this->type_payment = (int) $this->type_payment; $this->note = trim($this->note); - $this->fk_bank = (int) $this->fk_bank; + $this->fk_account = (int) $this->fk_account; $this->fk_user_creat = (int) $this->fk_user_creat; $this->fk_user_modif = (int) $this->fk_user_modif; @@ -125,57 +131,61 @@ class Tva extends CommonObject $sql .= "amount,"; $sql .= "label,"; $sql .= "note,"; - $sql .= "fk_bank,"; + $sql .= "fk_account,"; + $sql .= "fk_typepayment,"; $sql .= "fk_user_creat,"; $sql .= "fk_user_modif"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " '".$this->db->idate($now)."',"; $sql .= " '".$this->db->idate($this->datep)."',"; $sql .= " '".$this->db->idate($this->datev)."',"; $sql .= " '".$this->db->escape($this->amount)."',"; $sql .= " '".$this->db->escape($this->label)."',"; $sql .= " '".$this->db->escape($this->note)."',"; - $sql .= " ".($this->fk_bank <= 0 ? "NULL" : "'".$this->db->escape($this->fk_bank)."'").","; + $sql .= " '".$this->db->escape($this->fk_account)."',"; + $sql .= " '".$this->db->escape($this->type_payment)."',"; $sql .= " '".$this->db->escape($this->fk_user_creat)."',"; $sql .= " '".$this->db->escape($this->fk_user_modif)."'"; $sql .= ")"; 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"); + $resql = $this->db->query($sql); + if ($resql) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); - // Call trigger - $result = $this->call_trigger('TVA_CREATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('TVA_CREATE', $user); + if ($result < 0) $error++; + // End call triggers - if (!$error) - { - $this->db->commit(); - return $this->id; - } else { + if (!$error) + { + $this->db->commit(); + return $this->id; + } + else { $this->db->rollback(); return -1; - } - } else { + } + } + else { $this->error = "Error ".$this->db->lasterror(); $this->db->rollback(); 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 - */ - public function update($user, $notrigger = 0) - { - global $conf, $langs; + /** + * 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 + */ + public function update($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; @@ -183,7 +193,6 @@ class Tva extends CommonObject $this->amount = trim($this->amount); $this->label = trim($this->label); $this->note = trim($this->note); - $this->fk_bank = (int) $this->fk_bank; $this->fk_user_creat = (int) $this->fk_user_creat; $this->fk_user_modif = (int) $this->fk_user_modif; @@ -193,56 +202,90 @@ class Tva extends CommonObject $this->db->begin(); // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; $sql .= " tms='".$this->db->idate($this->tms)."',"; $sql .= " datep='".$this->db->idate($this->datep)."',"; $sql .= " datev='".$this->db->idate($this->datev)."',"; $sql .= " amount=".price2num($this->amount).","; $sql .= " label='".$this->db->escape($this->label)."',"; $sql .= " note='".$this->db->escape($this->note)."',"; - $sql .= " fk_bank=".$this->fk_bank.","; $sql .= " fk_user_creat=".$this->fk_user_creat.","; $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? $this->fk_user_modif : $user->id).""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = "Error ".$this->db->lasterror(); - $error++; - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $this->error = "Error ".$this->db->lasterror(); + $error++; + } if (!$error && !$notrigger) { - // Call trigger - $result = $this->call_trigger('TVA_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } + // Call trigger + $result = $this->call_trigger('TVA_MODIFY', $user); + if ($result < 0) $error++; + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } else { - $this->db->rollback(); - return -1; - } + if (!$error) + { + $this->db->commit(); + return 1; + } + else { + $this->db->rollback(); + return -1; + } + } + + /** + * Tag TVA as payed completely + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function setPaid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; + $sql .= " paye = 1"; + $sql .= " WHERE rowid = ".$this->id; + $resql = $this->db->query($sql); + if ($resql) return 1; + else return -1; + } + + /** + * Remove tag payed on TVA + * + * @param User $user Object user making change + * @return int <0 if KO, >0 if OK + */ + public function setUnpaid($user) + { + // phpcs:enable + $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; + $sql .= " paye = 0"; + $sql .= " WHERE rowid = ".$this->id; + $resql = $this->db->query($sql); + if ($resql) return 1; + else return -1; } - /** - * 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 - */ - public function fetch($id, $user = null) - { - global $langs; - $sql = "SELECT"; + /** + * 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 + */ + public function fetch($id, $user = null) + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.tms,"; @@ -253,27 +296,25 @@ class Tva extends CommonObject $sql .= " t.num_payment,"; $sql .= " t.label,"; $sql .= " t.note,"; - $sql .= " t.fk_bank,"; + $sql .= " t.paye,"; $sql .= " t.fk_user_creat,"; $sql .= " t.fk_user_modif,"; - $sql .= " b.fk_account,"; - $sql .= " b.fk_type,"; - $sql .= " b.rappro"; + $sql .= " t.fk_account"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; + //$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", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); $this->datep = $this->db->jdate($obj->datep); $this->datev = $this->db->jdate($obj->datev); @@ -281,30 +322,31 @@ class Tva extends CommonObject $this->type_payment = $obj->fk_typepayment; $this->num_payment = $obj->num_payment; $this->label = $obj->label; + $this->paye = $obj->paye; $this->note = $obj->note; - $this->fk_bank = $obj->fk_bank; $this->fk_user_creat = $obj->fk_user_creat; $this->fk_user_modif = $obj->fk_user_modif; $this->fk_account = $obj->fk_account; $this->fk_type = $obj->fk_type; $this->rappro = $obj->rappro; - } - $this->db->free($resql); + } + $this->db->free($resql); - return 1; - } else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } + return 1; + } + else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } /** - * Delete object in database - * - * @param User $user User that delete - * @return int <0 if KO, >0 if OK - */ + * Delete object in database + * + * @param User $user User that delete + * @return int <0 if KO, >0 if OK + */ public function delete($user) { global $conf, $langs; @@ -333,11 +375,11 @@ class Tva extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { @@ -355,154 +397,160 @@ class Tva extends CommonObject } - /** - * Balance of VAT - * - * @param int $year Year - * @return double Amount - */ - public function solde($year = 0) - { + /** + * Balance of VAT + * + * @param int $year Year + * @return double Amount + */ + public function solde($year = 0) + { - $reglee = $this->tva_sum_reglee($year); + $reglee = $this->tva_sum_reglee($year); - $payee = $this->tva_sum_payee($year); - $collectee = $this->tva_sum_collectee($year); + $payee = $this->tva_sum_payee($year); + $collectee = $this->tva_sum_collectee($year); - $solde = $reglee - ($collectee - $payee); + $solde = $reglee - ($collectee - $payee); - return $solde; - } + return $solde; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT from invoices emitted by the thirdparty. - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_collectee($year = 0) - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Total of the VAT from invoices emitted by the thirdparty. + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_collectee($year = 0) + { + // phpcs:enable - $sql = "SELECT sum(f.tva) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) - { + $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 >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); $ret = $obj->amount; - $this->db->free($result); - return $ret; - } else { - $this->db->free($result); + $this->db->free($result); + return $ret; + } + else { + $this->db->free($result); return 0; - } - } else { - print $this->db->lasterror(); - return -1; - } - } + } + } + else { + print $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_payee($year = 0) - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_payee($year = 0) + { + // phpcs:enable - $sql = "SELECT sum(f.total_tva) as total_tva"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) - { - $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + $sql = "SELECT sum(f.total_tva) as total_tva"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + if ($year) + { + $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->total_tva; - $this->db->free($result); - return $ret; - } else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $ret = $obj->total_tva; + $this->db->free($result); + return $ret; + } + else { + $this->db->free($result); return 0; - } - } else { - print $this->db->lasterror(); - return -1; - } - } + } + } + else { + print $this->db->lasterror(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_reglee($year = 0) - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Total of the VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_reglee($year = 0) + { + // phpcs:enable - $sql = "SELECT sum(f.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; + $sql = "SELECT sum(f.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; - if ($year) - { + if ($year) + { $sql .= " WHERE f.datev >= '".$this->db->escape($year)."-01-01' AND f.datev <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->amount; - $this->db->free($result); - return $ret; - } else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) + { + if ($this->db->num_rows($result)) + { + $obj = $this->db->fetch_object($result); + $ret = $obj->amount; + $this->db->free($result); + return $ret; + } + else { + $this->db->free($result); return 0; - } - } else { - print $this->db->lasterror(); - return -1; - } - } + } + } + else { + print $this->db->lasterror(); + return -1; + } + } - /** - * Create in database - * + /** + * Create in database + * * @param User $user Object user that insert * @return int <0 if KO, rowid in tva table if OK - */ - public function addPayment($user) - { - global $conf, $langs; + */ + public function addPayment($user) + { + global $conf, $langs; - $this->db->begin(); + $this->db->begin(); - // Clean parameters - $this->amount = price2num(trim($this->amount)); - $this->label = trim($this->label); + // Clean parameters + $this->amount = price2num(trim($this->amount)); + $this->label = trim($this->label); $this->note = trim($this->note); $this->num_payment = trim($this->num_payment); $this->fk_bank = (int) $this->fk_bank; @@ -510,81 +558,81 @@ class Tva extends CommonObject $this->fk_user_modif = (int) $this->fk_user_modif; if (empty($this->datec)) $this->datec = dol_now(); - // Check parameters + // Check parameters if (!$this->label) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); return -3; } - if ($this->amount == '') - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); - return -4; - } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); - return -5; - } - if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); - return -5; - } + if ($this->amount == '') + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); + return -4; + } + if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + return -5; + } + if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) + { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); + return -5; + } - // Insert into llx_tva - $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; - $sql .= "datec"; - $sql .= ", datep"; - $sql .= ", datev"; + // Insert into llx_tva + $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; + $sql .= "datec"; + $sql .= ", datep"; + $sql .= ", datev"; $sql .= ", amount"; $sql .= ", fk_typepayment"; $sql .= ", num_payment"; if ($this->note) $sql .= ", note"; - if ($this->label) $sql .= ", label"; - $sql .= ", fk_user_creat"; + if ($this->label) $sql .= ", label"; + $sql .= ", fk_user_creat"; $sql .= ", fk_bank"; $sql .= ", entity"; $sql .= ") "; - $sql .= " VALUES ("; - $sql .= " '".$this->db->idate($this->datec)."'"; - $sql .= ", '".$this->db->idate($this->datep)."'"; - $sql .= ", '".$this->db->idate($this->datev)."'"; + $sql .= " VALUES ("; + $sql .= " '".$this->db->idate($this->datec)."'"; + $sql .= ", '".$this->db->idate($this->datep)."'"; + $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", ".$this->amount; - $sql .= ", '".$this->db->escape($this->type_payment)."'"; + $sql .= ", '".$this->db->escape($this->type_payment)."'"; $sql .= ", '".$this->db->escape($this->num_payment)."'"; if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; - if ($this->label) $sql .= ", '".$this->db->escape($this->label)."'"; - $sql .= ", '".$this->db->escape($user->id)."'"; + if ($this->label) $sql .= ", '".$this->db->escape($this->label)."'"; + $sql .= ", '".$this->db->escape($user->id)."'"; $sql .= ", NULL"; $sql .= ", ".$conf->entity; - $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 'payment_vat' + $result = $this->db->query($sql); + if ($result) + { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called 'payment_vat' - // 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 + // 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) - { - $ok = 1; + if ($this->id > 0) + { + $ok = 1; if (!empty($conf->banque->enabled) && !empty($this->amount)) - { - // Insert into llx_bank - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + { + // Insert into llx_bank + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acc = new Account($this->db); + $acc = new Account($this->db); $result = $acc->fetch($this->accountid); if ($result <= 0) dol_print_error($this->db); @@ -594,60 +642,65 @@ class Tva extends CommonObject $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, abs($this->amount), $this->num_payment, '', $user); } - // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction - if ($bank_line_id > 0) + // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction + if ($bank_line_id > 0) { - $this->update_fk_bank($bank_line_id); - } else { + $this->update_fk_bank($bank_line_id); + } + else { $this->error = $acc->error; $ok = 0; } - // Update links - $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; - $ok = 0; - } - } + // Update links + $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; + $ok = 0; + } + } if ($ok) { $this->db->commit(); return $this->id; - } else { + } + else { $this->db->rollback(); return -3; } - } else { - $this->db->rollback(); - return -2; - } - } else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + } + else { + $this->db->rollback(); + return -2; + } + } + else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** * Update link between payment tva and line generate into llx_bank - * - * @param int $id_bank Id bank account + * + * @param int $id_bank Id bank account * @return int <0 if KO, >0 if OK - */ + */ public function update_fk_bank($id_bank) { - // phpcs:enable + // phpcs:enable $sql = 'UPDATE '.MAIN_DB_PREFIX.'tva SET fk_bank = '.(int) $id_bank; $sql .= ' WHERE rowid = '.(int) $this->id; $result = $this->db->query($sql); if ($result) { return 1; - } else { + } + else { dol_print_error($this->db); return -1; } @@ -658,11 +711,12 @@ class Tva extends CommonObject * * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param string $option link option - * @param int $notooltip 1=Disable tooltip - * @param string $morecss More CSS + * @param int $notooltip 1=Disable tooltip + * @param string $morecss More CSS + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string Chaine with URL */ - public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '') + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) { global $langs, $conf; @@ -673,24 +727,35 @@ class Tva extends CommonObject $label = ''.$langs->trans("ShowVatPayment").''; $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; + if (!empty($this->label)) + $label .= '
'.$langs->trans('Label').': '.$this->label; - $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$this->id; - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + if ($option != 'nolink') + { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; + if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + } - $linkstart = ''; - $linkend = ''; + $linkclose = ''; + if (empty($notooltip)) + { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) + { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } + else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + + $linkstart = ''; + $linkend = ''; $picto = 'payment'; @@ -703,34 +768,35 @@ class Tva extends CommonObject } /** - * Return amount of payments already done - * - * @return int Amount of payment already done, <0 if KO - */ - public function getSommePaiement() - { - $table = 'paiementcharge'; - $field = 'fk_charge'; + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + public function getSommePaiement() + { + $table = 'payment_vat'; + $field = 'fk_tva'; - $sql = 'SELECT sum(amount) as amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$table; - $sql .= ' WHERE '.$field.' = '.$this->id; + $sql = 'SELECT sum(amount) as amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $amount = 0; + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $amount = 0; - $obj = $this->db->fetch_object($resql); - if ($obj) $amount = $obj->amount ? $obj->amount : 0; + $obj = $this->db->fetch_object($resql); + if ($obj) $amount = $obj->amount ? $obj->amount : 0; - $this->db->free($resql); - return $amount; - } else { - return -1; - } - } + $this->db->free($resql); + return $amount; + } + else { + return -1; + } + } /** * Informations of vat payment object @@ -772,35 +838,61 @@ class Tva extends CommonObject } $this->db->free($result); - } else { + } + else { dol_print_error($this->db); } } /** - * Retourne le libelle du statut d'une facture (brouillon, validee, abandonnee, payee) + * Retourne le libelle du statut d'une TVA (impaye, payee) * - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + * @param 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 */ - public function getLibStatut($mode = 0) + public function getLibStatut($mode = 0, $alreadypaid = -1) { - return $this->LibStatut($this->statut, $mode); + return $this->LibStatut($this->paye, $mode, $alreadypaid); } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Renvoi le libelle d'un statut donne + * Renvoi le libelle d'un statut donne * - * @param int $status Statut - * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto - * @return string Libelle du statut + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto + * @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 */ - public function LibStatut($status, $mode = 0) + public function LibStatut($status, $mode = 0, $alreadypaid = -1) { // phpcs:enable - global $langs; // TODO Renvoyer le libelle anglais et faire traduction a affichage + global $langs; - return ''; + // Load translation files required by the page + $langs->loadLangs(array("customers", "bills")); + + // We reinit status array to force to redefine them because label may change according to properties values. + $this->labelStatus = array(); + $this->labelStatusShort = array(); + + if (empty($this->labelStatus) || empty($this->labelStatusShort)) + { + global $langs; + //$langs->load("mymodule"); + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); + $this->labelStatus[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); + $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } + + $statusType = 'status1'; + if ($status == 0 && $alreadypaid <> 0) $statusType = 'status3'; + if ($status == 1) $statusType = 'status6'; + + return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } } diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index 4a16d996ab8..081023cd2e8 100644 --- a/htdocs/compta/tva/index.php +++ b/htdocs/compta/tva/index.php @@ -5,6 +5,7 @@ * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2014 Ferran Marcet * Copyright (C) 2018 Frédéric France + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,6 +36,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/localtax/class/localtax.class.php'; // Load translation files required by the page $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "product", "trips", "admin")); +$form = new Form($db); $now = dol_now(); $current_date = dol_getdate($now); if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1; @@ -57,11 +59,13 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end $q = GETPOST("q", "int"); if (empty($q)) { - if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { + if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } + else { if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat + } + elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat if ($current_date['mon'] < $conf->global->SOCIETE_FISCAL_MONTH_START) { if (($conf->global->SOCIETE_FISCAL_MONTH_START - $current_date['mon']) > 6) { // If period started from less than 6 years, we show past year $year_start--; @@ -73,12 +77,14 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month + } + elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -1, 'm'); $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; } } - } else { + } + else { if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } @@ -108,100 +114,102 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); */ function pt($db, $sql, $date) { - global $conf, $bc, $langs; + global $conf, $bc, $langs, $form; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - $total = 0; - print ''; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + $total = 0; + print '
'; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; - $totalclaimed = 0; - $totalpaid = 0; - $amountclaimed = 0; - $amountpaid = 0; - $previousmonth = ''; - $previousmode = ''; - $mode = ''; + $totalclaimed = 0; + $totalpaid = 0; + $amountclaimed = 0; + $amountpaid = 0; + $previousmonth = ''; + $previousmode = ''; + $mode = ''; - while ($i < $num) { - $obj = $db->fetch_object($result); - $mode = $obj->mode; + while ($i < $num) { + $obj = $db->fetch_object($result); + $mode = $obj->mode; - //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; - if ($obj->mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; + if ($obj->mode == 'claimed' && !empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - if ($obj->mode == 'claimed') - { - $amountclaimed = $obj->mm; - $totalclaimed = $totalclaimed + $amountclaimed; - } - if ($obj->mode == 'paid') - { - $amountpaid = $obj->mm; - $totalpaid = $totalpaid + $amountpaid; - } + if ($obj->mode == 'claimed') + { + $amountclaimed = $obj->mm; + $totalclaimed = $totalclaimed + $amountclaimed; + } + if ($obj->mode == 'paid') + { + $amountpaid = $obj->mm; + $totalpaid = $totalpaid + $amountpaid; + } - if ($obj->mode == 'paid') - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - $previousmode = ''; - $previousmonth = ''; - } else { - $previousmode = $obj->mode; - $previousmonth = $obj->dm; - } + if ($obj->mode == 'paid') + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + $previousmode = ''; + $previousmonth = ''; + } + else { + $previousmode = $obj->mode; + $previousmonth = $obj->dm; + } - $i++; - } + $i++; + } - if ($mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + if ($mode == 'claimed' && !empty($previousmode)) + { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - print ''; - print ''; - print ''; - print ''; - print ""; + print ''; + print ''; + print ''; + print ''; + print ""; - print "
'.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").'
'.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").$form->textwithpicto('', $langs->trans('PaidDuringThisPeriodDesc'), 1).'
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
"; + print ""; - $db->free($result); - } else { - dol_print_error($db); - } + $db->free($result); + } + else { + dol_print_error($db); + } } @@ -209,7 +217,6 @@ function pt($db, $sql, $date) * View */ -$form = new Form($db); $company_static = new Societe($db); $tva = new Tva($db); @@ -362,7 +369,8 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], //'link' =>$expensereport->getNomUrl(1) ); - } else { + } + else { //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; @@ -392,144 +400,144 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc } //now we have an array (x_both) indexed by rates for coll and paye - $action = "tva"; - $object = array(&$x_coll, &$x_paye, &$x_both); - $parameters["mode"] = $modetax; - $parameters["year"] = $y; - $parameters["month"] = $m; - $parameters["type"] = 'vat'; + $action = "tva"; + $object = array(&$x_coll, &$x_paye, &$x_both); + $parameters["mode"] = $modetax; + $parameters["year"] = $y; + $parameters["month"] = $m; + $parameters["type"] = 'vat'; - // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array - $hookmanager->initHooks(array('externalbalance')); - $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array + $hookmanager->initHooks(array('externalbalance')); + $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!is_array($x_coll) && $coll_listbuy == -1) - { - $langs->load("errors"); - print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; - break; - } - if (!is_array($x_paye) && $coll_listbuy == -2) - { - print ''.$langs->trans("FeatureNotYetAvailable").''; - break; - } + if (!is_array($x_coll) && $coll_listbuy == -1) + { + $langs->load("errors"); + print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; + break; + } + if (!is_array($x_paye) && $coll_listbuy == -2) + { + print ''.$langs->trans("FeatureNotYetAvailable").''; + break; + } - print ''; - print ''.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''; + print ''; + print ''.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''; - $x_coll_sum = 0; - foreach (array_keys($x_coll) as $rate) - { - $subtot_coll_total_ht = 0; - $subtot_coll_vat = 0; + $x_coll_sum = 0; + foreach (array_keys($x_coll) as $rate) + { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) - { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { - //print $langs->trans("NA"); - } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } - } - } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_coll_total_ht += $temp_ht; - $subtot_coll_vat += $temp_vat; - $x_coll_sum += $temp_vat; - } - } - print ''.price(price2num($x_coll_sum, 'MT')).''; + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; + } + } + print ''.price(price2num($x_coll_sum, 'MT')).''; - $x_paye_sum = 0; - foreach (array_keys($x_paye) as $rate) - { - $subtot_paye_total_ht = 0; - $subtot_paye_vat = 0; + $x_paye_sum = 0; + foreach (array_keys($x_paye) as $rate) + { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; - foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) - { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) + { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) + { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { - //print $langs->trans("NA"); - } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } - } - } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; - } - } - print ''.price(price2num($x_paye_sum, 'MT')).''; + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) + { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + print ''.price(price2num($x_paye_sum, 'MT')).''; - $subtotalcoll = $subtotalcoll + $x_coll_sum; - $subtotalpaye = $subtotalpaye + $x_paye_sum; + $subtotalcoll = $subtotalcoll + $x_coll_sum; + $subtotalpaye = $subtotalpaye + $x_paye_sum; - $diff = $x_coll_sum - $x_paye_sum; - $total = $total + $diff; - $subtotal = price2num($subtotal + $diff, 'MT'); + $diff = $x_coll_sum - $x_paye_sum; + $total = $total + $diff; + $subtotal = price2num($subtotal + $diff, 'MT'); - print ''.price(price2num($diff, 'MT')).''."\n"; - print " \n"; - print "\n"; + print ''.price(price2num($diff, 'MT')).''."\n"; + print " \n"; + print "\n"; - $i++; $m++; - if ($i > 2) - { - print ''; - print ''.$langs->trans("SubTotal").':'; - print ''.price(price2num($subtotalcoll, 'MT')).''; - print ''.price(price2num($subtotalpaye, 'MT')).''; - print ''.price(price2num($subtotal, 'MT')).''; - print ' '; - $i = 0; - $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; - } + $i++; $m++; + if ($i > 2) + { + print ''; + print ''.$langs->trans("SubTotal").':'; + print ''.price(price2num($subtotalcoll, 'MT')).''; + print ''.price(price2num($subtotalpaye, 'MT')).''; + print ''.price(price2num($subtotal, 'MT')).''; + print ' '; + $i = 0; + $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; + } } print ''.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).''; print " \n"; @@ -543,25 +551,26 @@ print '
'; /* - * Payed + * Paid */ print load_fiche_titre($langs->trans("VATPaid"), '', ''); $sql = ''; -$sql .= "SELECT SUM(amount) as mm, date_format(f.datev,'%Y-%m') as dm, 'claimed' as mode"; -$sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; -$sql .= " WHERE f.entity = ".$conf->entity; -$sql .= " AND (f.datev >= '".$db->idate($date_start)."' AND f.datev <= '".$db->idate($date_end)."')"; +$sql .= "SELECT SUM(amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'claimed' as mode"; +$sql .= " FROM ".MAIN_DB_PREFIX."tva as tva"; +$sql .= " WHERE tva.entity = ".$conf->entity; +$sql .= " AND (tva.datev >= '".$db->idate($date_start)."' AND tva.datev <= '".$db->idate($date_end)."')"; $sql .= " GROUP BY dm"; $sql .= " UNION "; -$sql .= "SELECT SUM(amount) as mm, date_format(f.datep,'%Y-%m') as dm, 'paid' as mode"; -$sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; -$sql .= " WHERE f.entity = ".$conf->entity; -$sql .= " AND (f.datep >= '".$db->idate($date_start)."' AND f.datep <= '".$db->idate($date_end)."')"; +$sql .= "SELECT SUM(ptva.amount) as mm, date_format(tva.datev,'%Y-%m') as dm, 'paid' as mode"; +$sql .= " FROM ".MAIN_DB_PREFIX."tva as tva"; +$sql .= " INNER JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON (tva.rowid = ptva.fk_tva)"; +$sql .= " WHERE tva.entity = ".$conf->entity; +$sql .= " AND (tva.datev >= '".$db->idate($date_start)."' AND tva.datev <= '".$db->idate($date_end)."')"; $sql .= " GROUP BY dm"; $sql .= " ORDER BY dm ASC, mode ASC"; @@ -578,37 +587,37 @@ if (!empty($conf->global->MAIN_FEATURES_LEVEL)) * Recap */ - print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation + print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation - $sql1 = "SELECT SUM(amount) as mm"; - $sql1 .= " FROM ".MAIN_DB_PREFIX."tva as f"; - $sql1 .= " WHERE f.entity = ".$conf->entity; - $sql1 .= " AND f.datev >= '".$db->idate($date_start)."'"; - $sql1 .= " AND f.datev <= '".$db->idate($date_end)."'"; + $sql1 = "SELECT SUM(amount) as mm"; + $sql1 .= " FROM ".MAIN_DB_PREFIX."tva as f"; + $sql1 .= " WHERE f.entity = ".$conf->entity; + $sql1 .= " AND f.datev >= '".$db->idate($date_start)."'"; + $sql1 .= " AND f.datev <= '".$db->idate($date_end)."'"; - $result = $db->query($sql1); - if ($result) { - $obj = $db->fetch_object($result); - print ''; + $result = $db->query($sql1); + if ($result) { + $obj = $db->fetch_object($result); + print '
'; - print ""; - print ''; - print ''; - print "\n"; + print ""; + print ''; + print ''; + print "\n"; - print ""; - print ''; - print '\n"; - print "\n"; + print ""; + print ''; + print '\n"; + print "\n"; - $restopay = $total - $obj->mm; - print ""; - print ''; - print ''; - print "\n"; + $restopay = $total - $obj->mm; + print ""; + print ''; + print ''; + print "\n"; - print '
'.$langs->trans("VATDue").''.price(price2num($total, 'MT')).'
'.$langs->trans("VATDue").''.price(price2num($total, 'MT')).'
'.$langs->trans("VATPaid").''.price(price2num($obj->mm, 'MT'))."
'.$langs->trans("VATPaid").''.price(price2num($obj->mm, 'MT'))."
'.$langs->trans("RemainToPay").''.price(price2num($restopay, 'MT')).'
'.$langs->trans("RemainToPay").''.price(price2num($restopay, 'MT')).'
'; - } + print ''; + } } print '
'; diff --git a/htdocs/compta/tva/info.php b/htdocs/compta/tva/info.php index ddabf6e2b49..45799c8e1f5 100644 --- a/htdocs/compta/tva/info.php +++ b/htdocs/compta/tva/info.php @@ -83,6 +83,8 @@ dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, print '
'; print '
'; +print '
'; + print '
'; dol_print_object_info($object); print '
'; diff --git a/htdocs/compta/tva/list.php b/htdocs/compta/tva/list.php index a142518279f..dd5118bc656 100644 --- a/htdocs/compta/tva/list.php +++ b/htdocs/compta/tva/list.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2009 Regis Houssin * Copyright (C) 2011-2019 Alexandre Spangaro * Copyright (C) 2020 Tobias Sekan + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -57,6 +58,7 @@ $search_type = GETPOST('search_type', 'int'); $search_cheque = GETPOST('search_cheque', 'alpha'); $search_account = GETPOST('search_account', 'int'); $search_amount = GETPOST('search_amount', 'alpha'); +$search_status = GETPOST('search_status', 'int'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'alpha'); @@ -75,12 +77,9 @@ $arrayfields = array( 't.rowid' =>array('checked'=>1, 'position'=>10, 'label'=>"Ref",), 't.label' =>array('checked'=>1, 'position'=>20, 'label'=>"Label"), 't.datev' =>array('checked'=>1, 'position'=>30, 'label'=>"PeriodEndDate"), - 't.datep' =>array('checked'=>1, 'position'=>40, 'label'=>"DatePayment"), 't.fk_typepayment' =>array('checked'=>1, 'position'=>50, 'label'=>"Type"), - 't.num_payment' =>array('checked'=>1, 'position'=>60, 'label'=>"Numero", 'tooltip'=>"ChequeOrTransferNumber"), - 'transaction' =>array('checked'=>1, 'position'=>70, 'label'=>"BankTransactionLine", 'enabled'=>(!empty($conf->banque->enabled))), - 'ba.label' =>array('checked'=>1, 'position'=>80, 'label'=>"Account", 'enable'=>(!empty($conf->banque->enabled))), - 't.amount' =>array('checked'=>1, 'position'=>90, 'label'=>"PayedByThisPayment"), + 't.amount' =>array('checked'=>1, 'position'=>90, 'label'=>"Amount"), + 't.status' =>array('checked'=>1, 'position'=>90, 'label'=>"Status"), ); $arrayfields = dol_sort_array($arrayfields, 'position'); @@ -113,6 +112,7 @@ if (empty($reshook)) { $search_cheque = ''; $search_account = ''; $search_amount = ''; + $search_status = ''; } } @@ -128,15 +128,13 @@ $bankstatic = new Account($db); $accountingjournal = new AccountingJournal($db); $bankline = new AccountLine($db); -llxHeader('', $langs->trans("VATPayments")); +llxHeader('', $langs->trans("VATDeclarations")); -$sql = 'SELECT t.rowid, t.amount, t.label, t.datev, t.datep, t.fk_typepayment as type, t.num_payment, t.fk_bank'; -$sql .= ', ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel'; -$sql .= ', pst.code as payment_code'; +$sql = 'SELECT t.rowid, t.amount, t.label, t.datev, t.datep, t.paye, t.fk_typepayment as type, t.num_payment, pst.code as payment_code,'; +$sql .= ' SUM(ptva.amount) as alreadypayed'; $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 .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; -$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; +$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON ptva.fk_tva = t.rowid"; $sql .= ' WHERE t.entity IN ('.getEntity($object->element).')'; if (!empty($search_ref)) $sql .= natural_search('t.rowid', $search_ref); @@ -146,10 +144,11 @@ if (!empty($search_dateend_end)) $sql .= ' AND t.datev <= "'.$db->idate($sea if (!empty($search_datepayment_start)) $sql .= ' AND t.datep >= "'.$db->idate($search_datepayment_start).'"'; if (!empty($search_datepayment_end)) $sql .= ' AND t.datep <= "'.$db->idate($search_datepayment_end).'"'; if (!empty($search_type) && $search_type > 0) $sql .= ' AND t.fk_typepayment='.$search_type; -if (!empty($search_cheque)) $sql .= natural_search('t.num_payment', $search_cheque); if (!empty($search_account) && $search_account > 0) $sql .= ' AND b.fk_account='.$search_account; if (!empty($search_amount)) $sql .= natural_search('t.amount', price2num(trim($search_amount)), 1); +if ($search_status != '' && $search_status >= 0) $sql .= " AND t.paye = ".$db->escape($search_status); +$sql .= " GROUP BY t.rowid, t.amount, t.label, t.datev, t.datep, t.paye, t.fk_typepayment, t.num_payment, pst.code"; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; @@ -200,6 +199,7 @@ if (!empty($search_type) && $search_type > 0) $param .= '&search_type='.$search if (!empty($search_cheque)) $param .= '&search_cheque="'.$search_cheque.'"'; if (!empty($search_account) && $search_account > 0) $param .= '&search_account='.$search_account; if (!empty($search_amount)) $param .= '&search_amount="'.$search_amount.'"'; +if ($search_status != '' && $search_status != '-1') $param .= '&search_status='.urlencode($search_status); print '
'; if ($optioncss != '') print ''; @@ -213,7 +213,7 @@ print ''; $url = DOL_URL_ROOT.'/compta/tva/card.php?action=create'; if (!empty($socid)) $url .= '&socid='.$socid; $newcardbutton = dolGetButtonTitle($langs->trans('NewVATPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); -print_barre_liste($langs->trans("VATPayments"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); +print_barre_liste($langs->trans("VATDeclarations"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); $varpage = empty($contextpage) ? $_SERVER['PHP_SELF'] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields @@ -257,7 +257,7 @@ if (!empty($arrayfields['t.datev']['checked'])) { } // Filter: Date payment -if (!empty($arrayfields['t.datep']['checked'])) { +/*if (!empty($arrayfields['t.datep']['checked'])) { print ''; print '
'; print $form->selectDate($search_datepayment_start ? $search_datepayment_start : -1, 'search_datepayment_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")); @@ -266,7 +266,7 @@ if (!empty($arrayfields['t.datep']['checked'])) { print $form->selectDate($search_datepayment_end ? $search_datepayment_end : -1, 'search_datepayment_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")); print '
'; print ''; -} +}*/ // Filter: Type if (!empty($arrayfields['t.fk_typepayment']['checked'])) { @@ -275,26 +275,6 @@ if (!empty($arrayfields['t.fk_typepayment']['checked'])) { print ''; } -// Filter: Cheque number -if (!empty($arrayfields['t.num_payment']['checked'])) { - print ''; - print ''; - print ''; -} - -// Filter: Bank transaction number (placeholder) -if (!empty($arrayfields['transaction']['checked'])) { - print ''; - print ''; -} - -// Filter: Bank account -if (!empty($arrayfields['ba.label']['checked'])) { - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); - print ''; -} - // Filter: Amount if (!empty($arrayfields['t.amount']['checked'])) { print ''; @@ -302,6 +282,14 @@ if (!empty($arrayfields['t.amount']['checked'])) { print ''; } +// Status +if (!empty($arrayfields['t.status']['checked'])) { + print ''; + $liststatus = array('0' => $langs->trans("Unpaid"), '1' => $langs->trans("Paid")); + print $form->selectarray('search_status', $liststatus, $search_status, 1); + print ''; +} + // Fields from hook $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook @@ -319,12 +307,9 @@ if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titr if (!empty($arrayfields['t.rowid']['checked'])) print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder); if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, 'align="left"', $sortfield, $sortorder); if (!empty($arrayfields['t.datev']['checked'])) print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['t.datep']['checked'])) print_liste_field_titre($arrayfields['t.datep']['label'], $_SERVER['PHP_SELF'], 't.datep', '', $param, 'align="center"', $sortfield, $sortorder); if (!empty($arrayfields['t.fk_typepayment']['checked'])) print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left '); -if (!empty($arrayfields['t.num_payment']['checked'])) print_liste_field_titre($arrayfields['t.num_payment']['label'], $_SERVER['PHP_SELF'], 't.num_payment', '', $param, '', $sortfield, $sortorder, '', $arrayfields['t.num_payment']['tooltip']); -if (!empty($arrayfields['transaction']['checked'])) print_liste_field_titre($arrayfields['transaction']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['ba.label']['checked'])) print_liste_field_titre($arrayfields['ba.label']['label'], $_SERVER['PHP_SELF'], 'ba.label', '', $param, '', $sortfield, $sortorder, 'left '); if (!empty($arrayfields['t.amount']['checked'])) print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['t.status']['checked'])) print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder); // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -341,6 +326,7 @@ while ($i < min($num, $limit)) { $tva_static->id = $obj->rowid; $tva_static->ref = $obj->rowid; + $tva_static->label = $obj->label; print ''; @@ -369,10 +355,10 @@ while ($i < min($num, $limit)) { } // Date payment - if (!empty($arrayfields['t.datep']['checked'])) { + /*if (!empty($arrayfields['t.datep']['checked'])) { print ''.dol_print_date($db->jdate($obj->datep), 'day').''; if (!$i) $totalarray['nbfield']++; - } + }*/ // Type if (!empty($arrayfields['t.fk_typepayment']['checked'])) @@ -381,21 +367,8 @@ while ($i < min($num, $limit)) { if (!$i) $totalarray['nbfield']++; } - // Cheque number - if (!empty($arrayfields['t.num_payment']['checked'])) { - print ''.$obj->num_payment.''; - if (!$i) $totalarray['nbfield']++; - } - - // Bank transaction - if (!empty($arrayfields['transaction']['checked'])) { - $bankline->fetch($obj->fk_bank); - print ''.$bankline->getNomUrl(1, 0).''; - if (!$i) $totalarray['nbfield']++; - } - // Account - if (!empty($arrayfields['ba.label']['checked'])) { + /*if (!empty($arrayfields['ba.label']['checked'])) { print ''; if ($obj->fk_bank > 0) { $bankstatic->id = $obj->bid; @@ -411,14 +384,22 @@ while ($i < min($num, $limit)) { } print ''; if (!$i) $totalarray['nbfield']++; - } + }*/ // Amount - $total = $total + $obj->amount; - print ''.price($obj->amount).''; - if (!$i) $totalarray['nbfield']++; - $totalarray['pos'][$totalarray['nbfield']] = 'amount'; - $totalarray['val']['amount'] += $objp->amount; + if (!empty($arrayfields['t.amount']['checked'])) { + $total = $total + $obj->amount; + print '' . price($obj->amount) . ''; + if (!$i) $totalarray['nbfield']++; + $totalarray['pos'][$totalarray['nbfield']] = 'amount'; + $totalarray['val']['amount'] += $obj->amount; + } + + if (!empty($arrayfields['t.status']['checked'])) { + print '' . $tva_static->LibStatut($obj->paye, 5, $obj->alreadypayed) . ''; + if (!$i) $totalarray['nbfield']++; + if (!empty($arrayfields['t.amount']['checked'])) $totalarray['pos'][$totalarray['nbfield']] = ''; + } // Buttons print ''; diff --git a/htdocs/compta/tva/payments.php b/htdocs/compta/tva/payments.php new file mode 100644 index 00000000000..0cdf7e7086b --- /dev/null +++ b/htdocs/compta/tva/payments.php @@ -0,0 +1,217 @@ + + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2005-2010 Regis Houssin + * Copyright (C) 2011-2016 Alexandre Spangaro + * Copyright (C) 2011-2014 Juanjo Menent + * Copyright (C) 2015 Jean-François Ferry + * Copyright (C) 2021 Gauthier VERDOL + * + * This 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/payments.php + * \ingroup compta + * \brief Page to list payments of special expenses + */ + +require '../../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/paymentvat.class.php'; +require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + +// Load translation files required by the page +$langs->loadLangs(array('compta', 'bills')); + +// Security check +if ($user->socid) $socid = $user->socid; +$result = restrictedArea($user, 'tax|salaries', '', '', 'charges|'); + +$mode = GETPOST("mode", 'alpha'); +$year = GETPOST("year", 'int'); +$filtre = GETPOST("filtre", 'alpha'); +if (!$year && $mode != 'tvaonly') { $year = date("Y", time()); } + +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST("sortfield", 'alpha'); +$sortorder = GETPOST("sortorder", 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); +if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; +if (!$sortfield) $sortfield = "ptva.datep"; +if (!$sortorder) $sortorder = "DESC"; + + +/* + * View + */ + +$tva_static = new Tva($db); +$tva = new Tva($db); +$payment_vat_static = new PaymentVAT($db); +$sal_static = new PaymentSalary($db); + +llxHeader('', $langs->trans("VATExpensesArea")); + +$title = $langs->trans("VATPayments"); + +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if ($sortfield) $param .= '&sortfield='.$sortfield; +if ($sortorder) $param .= '&sortorder='.$sortorder; + + +print ''; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy', 0, '', '', $limit); + +if ($year) $param .= '&year='.$year; + +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) +{ + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print ''; + print ''; + print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], "ptva.rowid", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "ptva.datep", "", $param, 'align="center"', $sortfield, $sortorder); + print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "pct.code", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre("BankAccount", $_SERVER["PHP_SELF"], "bank.ref", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre("LabelContrib", $_SERVER["PHP_SELF"], "tva.label", "", $param, '', $sortfield, $sortorder); + //print_liste_field_titre("TypeContrib", $_SERVER["PHP_SELF"], "tva.fk_type", "", $param, '', $sortfield, $sortorder); + print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "tva.datev", "", $param, 'width="140px"', $sortfield, $sortorder); + print_liste_field_titre("ExpectedToPay", $_SERVER["PHP_SELF"], "tva.amount", "", $param, 'class="right"', $sortfield, $sortorder); + print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "ptva.amount", "", $param, 'class="right"', $sortfield, $sortorder); + print "\n"; + + $sql = "SELECT tva.rowid, tva.label as label, b.fk_account"; + $sql .= ", tva.datev"; + $sql .= ", tva.amount as total,"; + $sql .= " ptva.rowid as pid, ptva.datep, ptva.amount as totalpaye, ptva.num_paiement as num_payment,"; + $sql .= " pct.code as payment_code"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as tva,"; + $sql .= " ".MAIN_DB_PREFIX."payment_vat as ptva"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bank as b ON (b.rowid = ptva.fk_bank)"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bank_account as bank ON (bank.rowid = b.fk_account)"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON ptva.fk_typepaiement = pct.id"; + $sql .= " WHERE ptva.fk_tva = tva.rowid"; + $sql .= " AND tva.entity = ".$conf->entity; + if ($year > 0) + { + $sql .= " AND ("; + // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, + // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire + $sql .= " (tva.datev IS NOT NULL AND tva.datev between '".$db->idate(dol_get_first_day($year))."' AND '".$db->idate(dol_get_last_day($year))."')"; + $sql .= " OR (tva.datev IS NULL AND tva.datev between '".$db->idate(dol_get_first_day($year))."' AND '".$db->idate(dol_get_last_day($year))."')"; + $sql .= ")"; + } + if (preg_match('/^cs\./', $sortfield) + || preg_match('/^tva\./', $sortfield) + || preg_match('/^ptva\./', $sortfield) + || preg_match('/^pct\./', $sortfield) + || preg_match('/^bank\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + //$sql.= $db->plimit($limit+1,$offset); + //print $sql; + + dol_syslog("compta/tva/payments.php: select payment", LOG_DEBUG); + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + $total = 0; + $totalnb = 0; + $totalpaye = 0; + + while ($i < min($num, $limit)) + { + $obj = $db->fetch_object($resql); + + $payment_vat_static->id = $obj->pid; + $payment_vat_static->ref = $obj->pid; + + print ''; + // Ref payment + print '\n"; + // Date payment + print ''; + // Type payment + print ''; + // Account + print ''; + // Label + print ''; + // Type + //print ''; + // Date + $date = $obj->datev; + print ''; + // Expected to pay + print ''; + // Paid + print ''; + print ''; + + $total = $total + $obj->total; + $totalnb = $totalnb + $obj->nb; + $totalpaye = $totalpaye + $obj->totalpaye; + $i++; + } + print ''; + print ''; // A total here has no sense + //print ''; + print ''; + print ''; + print ''; + print '"; + print ""; + } + else { + dol_print_error($db); + } + print '
'.$payment_vat_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->datep), 'day').''; + if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + print $obj->num_payment.''; + $account = new Account($db); + $account->fetch($obj->fk_account); + print $account->getNomUrl(1); + print ''; + $tva->id = $obj->rowid; + $tva->ref = $obj->rowid; + $tva->label = $obj->label; + print $tva->getNomUrl(1, '20'); + print ''.$obj->type_label.''.dol_print_date($date, 'day').''.price($obj->total).''; + if ($obj->totalpaye) print price($obj->totalpaye); + print '
'.$langs->trans("Total").'    '.price($totalpaye)."
'; + print '
'; +} + +print ''; + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 1156e254e52..943c704b17f 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -54,6 +54,8 @@ $mesg = ''; $error = 0; $errors = array(); $action = (GETPOST('action', 'alpha') ? GETPOST('action', 'alpha') : 'view'); $confirm = GETPOST('confirm', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); + $id = GETPOST('id', 'int'); $socid = GETPOST('socid', 'int'); @@ -200,7 +202,7 @@ if (empty($reshook)) } } } - $object->email = (string) GETPOST("email", 'alpha'); + $object->email = (string) GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL); $object->no_email = GETPOST("no_email", "int"); $object->phone_pro = (string) GETPOST("phone_pro", 'alpha'); $object->phone_perso = (string) GETPOST("phone_perso", 'alpha'); @@ -225,44 +227,59 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST("lastname")) { + if (!empty($conf->mailing->enabled) && $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1 && $object->no_email==-1 && !empty($object->email)) { + $error++; + $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("No_Email")); + $action = 'create'; + } + + if (!empty($object->email) && !isValidEMail($object->email)) + { + $langs->load("errors"); + $error++; + $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); + $action = 'create'; + } + + if (empty($object->lastname)) { $error++; $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Lastname").' / '.$langs->transnoentities("Label")); $action = 'create'; } - if (!$error) - { + if (empty($error)) { $id = $object->create($user); - if ($id <= 0) - { + if ($id <= 0) { $error++; $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); $action = 'create'; - } else { - // Categories association - $contcats = GETPOST('contcats', 'array'); - $object->setCategories($contcats); + } + } - // Add mass emailing flag into table mailing_unsubscribe - if (GETPOST('no_email', 'int') && $object->email) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$db->escape($object->email)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - if (empty($obj->nb)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$db->escape($object->email)."', ".$db->escape(getEntity('mailing', 0)).", '".$db->idate(dol_now())."')"; - $resql = $db->query($sql); - } - } + if (empty($error)) { + // Categories association + $contcats = GETPOST('contcats', 'array'); + if (count($contcats)>0) { + $result = $object->setCategories($contcats); + if ($result <= 0) { + $error++; + $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); + $action = 'create'; } } } - if (!$error && $id > 0) + if (empty($error) && !empty($conf->mailing->enabled) && !empty($object->email)) { + // Add mass emailing flag into table mailing_unsubscribe + $result=$object->setNoEmail($object->no_email); + if ($result<0) { + $error++; + $errors = array_merge($errors, ($object->error ? array($object->error) : $object->errors)); + $action = 'create'; + } + } + + if (empty($error) && $id > 0) { $db->commit(); if (!empty($backtopage)) $url = $backtopage; @@ -296,18 +313,33 @@ if (empty($reshook)) } } - if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) + if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) { - if (empty($_POST["lastname"])) + if (!GETPOST("lastname", 'alpha')) { $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); $action = 'edit'; } + if (!empty($conf->mailing->enabled) && $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1 && GETPOST("no_email", "int")==-1 && !empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) { + $error++; + $errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("No_Email")); + $action = 'edit'; + } + + if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) + { + $langs->load("errors"); + $error++; + $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); + $action = 'edit'; + } + if (!$error) { $contactid = GETPOST("contactid", 'int'); $object->fetch($contactid); + $object->fetchRoles($contactid); // Photo save $dir = $conf->societe->multidir_output[$object->entity]."/contact/".$object->id."/photos"; @@ -374,7 +406,7 @@ if (empty($reshook)) $object->state_id = GETPOST("state_id", 'int'); $object->country_id = GETPOST("country_id", 'int'); - $object->email = (string) GETPOST("email", 'alpha'); + $object->email = (string) GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL); $object->no_email = GETPOST("no_email", "int"); //$object->jabberid = GETPOST("jabberid", 'alpha'); //$object->skype = GETPOST("skype", 'alpha'); @@ -396,7 +428,8 @@ if (empty($reshook)) $object->priv = (string) GETPOST("priv", 'int'); $object->note_public = (string) GETPOST("note_public", 'restricthtml'); $object->note_private = (string) GETPOST("note_private", 'restricthtml'); - $object->roles = GETPOST("roles", 'array'); + + $object->roles = GETPOST("roles", 'array'); // Note GETPOSTISSET("role") is null when combo is empty // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); @@ -411,31 +444,15 @@ if (empty($reshook)) $categories = GETPOST('contcats', 'array'); $object->setCategories($categories); - $no_email = GETPOST('no_email', 'int'); - // Update mass emailing flag into table mailing_unsubscribe if (GETPOSTISSET('no_email') && $object->email) { - if ($no_email) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$db->escape($object->email)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - if (empty($noemail)) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$db->escape($object->email)."', ".$db->escape(getEntity('mailing', 0)).", '".$db->idate(dol_now())."')"; - $resql = $db->query($sql); - } - } - } else { - $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$db->escape($object->email)."' AND entity = ".$db->escape(getEntity('mailing', 0)); - $resql = $db->query($sql); + $no_email = GETPOST('no_email', 'int'); + $result=$object->setNoEmail($no_email); + if ($result<0) { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'edit'; } - - $object->no_email = $no_email; } $object->old_lastname = ''; @@ -648,8 +665,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", 'alpha') : $object->civility_code, 'civility_code'); print ''; + // Job position print ''; - print 'poste).'">'; + print 'poste).'">'; $colspan = 3; if ($conf->use_javascript_ajax && $socid > 0) $colspan = 2; @@ -738,27 +756,36 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; print ''; + //Unsubscribe if (!empty($conf->mailing->enabled)) { - $noemail = ''; - if (empty($noemail) && !empty($object->email)) + if ($conf->use_javascript_ajax && $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1) { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; + print "\n".''."\n"; + } + if (!GETPOSTISSET("no_email") && !empty($object->email)) + { + $result=$object->getNoEmail(); + if ($result<0) { + setEventMessages($object->error, $object->errors, 'errors'); } } - print ''; - print ''; - print ''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'alpha') : $noemail), 1).''; + print ''; + print ''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'int') : $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS), 1, false, ($conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1)).''; print ''; } - print ''; + if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { @@ -774,39 +801,6 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } } - // if (! empty($conf->socialnetworks->enabled)) - // { - // // Jabber - // if (! empty($conf->global->SOCIALNETWORKS_JABBER)) - // { - // print ''; - // print 'jabberid).'">'; - // } - // // Skype - // if (! empty($conf->global->SOCIALNETWORKS_SKYPE)) - // { - // print ''; - // print 'skype).'">'; - // } - // // Twitter - // if (! empty($conf->global->SOCIALNETWORKS_TWITTER)) - // { - // print ''; - // print 'twitter).'">'; - // } - // // Facebook - // if (! empty($conf->global->SOCIALNETWORKS_FACEBOOK)) - // { - // print ''; - // print 'facebook).'">'; - // } - // // LinkedIn - // if (! empty($conf->global->SOCIALNETWORKS_LINKEDIN)) - // { - // print ''; - // print 'linkedin).'">'; - // } - // } // Visibility print ''; @@ -975,8 +969,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print $formcompany->select_civility(GETPOSTISSET("civility_code") ? GETPOST("civility_code", "aZ09") : $object->civility_code, 'civility_code'); print ''; + // Job position print ''; - print 'poste).'">'; + print 'poste).'">'; // Address print ''; @@ -1050,28 +1045,40 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; // Unsubscribe - print ''; if (!empty($conf->mailing->enabled)) { - $noemail = ''; - if (empty($noemail) && !empty($object->email)) + if ($conf->use_javascript_ajax && $conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1) { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; + print "\n".''."\n"; + } + if (!GETPOSTISSET("no_email") && !empty($object->email)) + { + $result=$object->getNoEmail(); + if ($result<0) { + setEventMessages($object->error, $object->errors, 'errors'); } } - - print ''; - print ''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ?GETPOST("no_email", 'alpha') : $noemail), 1).''; - } else { - print ''; + print ''; + print ''; + print ''.$form->selectyesno('no_email', (GETPOSTISSET("no_email") ? GETPOST("no_email", 'int') : $object->no_email), 1, false, ($conf->global->MAILING_CONTACT_DEFAULT_BULK_STATUS==-1)).''; + print ''; } - print ''; if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { @@ -1300,20 +1307,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Unsubscribe opt-out if (!empty($conf->mailing->enabled)) { - //print 'eee'.$object->email; - $noemail = $object->no_email; - if (empty($noemail) && !empty($object->email)) - { - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$db->escape($object->email)."'"; - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $noemail = $obj->nb; - } + $result=$object->getNoEmail(); + if ($result<0) { + setEventMessages($object->error, $object->errors, 'errors'); } - print ''.$langs->trans("No_Email").''.yn($noemail).''; + print ''.$langs->trans("No_Email").''.yn($object->no_email).''; } print ''.$langs->trans("ContactVisibility").''; @@ -1382,7 +1380,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) if (!empty($object->socid)) { print ''.$langs->trans("ContactByDefaultFor").''; print ''; - print $formcompany->showRoles("roles", $object, 'view'); + print $formcompany->showRoles("roles", $object, 'view', $object->roles); print ''; } diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 8fe4943d267..94eb700ab92 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -145,14 +145,32 @@ class Contact extends CommonObject */ public $town; - public $state_id; // Id of department - public $state_code; // Code of department - public $state; // Label of department + /** + * @var int // Id of department + */ + public $state_id; + + /** + * @var string // Code of department + */ + public $state_code; + + /** + * @var string // Label of department + */ + public $state; public $poste; // Position - public $socid; // fk_soc - public $statut; // 0=inactif, 1=actif + /** + * @var int Thirdparty ID + */ + public $socid; + + /** + * @var int 0=inactive, 1=active + */ + public $statut; public $code; @@ -247,7 +265,14 @@ class Contact extends CommonObject public $ref_commande; // Nb de reference commande pour lequel il est contact public $ref_propal; // Nb de reference propal pour lequel il est contact + /** + * @var int user ID + */ public $user_id; + + /** + * @var string user login + */ public $user_login; // END MODULEBUILDER PROPERTIES @@ -259,12 +284,19 @@ class Contact extends CommonObject */ public $oldcopy; // To contains a clone of this when we need to save old properties of object - public $roles = array(); + /** + * @var array roles + */ + public $roles; public $cacheprospectstatus = array(); public $fk_prospectlevel; public $stcomm_id; public $statut_commercial; + + /** + * @var string picto + */ public $stcomm_picto; /** @@ -335,8 +367,7 @@ class Contact extends CommonObject $sql = "SELECT count(sp.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " WHERE sp.fk_soc = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; @@ -344,13 +375,13 @@ class Contact extends CommonObject } $sql .= ' '.$clause.' sp.entity IN ('.getEntity($this->element).')'; $sql .= " AND (sp.priv='0' OR (sp.priv='1' AND sp.fk_user_creat=".$user->id."))"; - if ($user->socid > 0) $sql .= " AND sp.fk_soc = ".$user->socid; + if ($user->socid > 0) { + $sql .= " AND sp.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["contacts"] = $obj->nb; } $this->db->free($resql); @@ -402,8 +433,11 @@ class Contact extends CommonObject $sql .= ", import_key"; $sql .= ") VALUES ("; $sql .= "'".$this->db->idate($now)."',"; - if ($this->socid > 0) $sql .= " ".$this->db->escape($this->socid).","; - else $sql .= "null,"; + if ($this->socid > 0) { + $sql .= " ".$this->db->escape($this->socid).","; + } else { + $sql .= "null,"; + } $sql .= "'".$this->db->escape($this->lastname)."',"; $sql .= "'".$this->db->escape($this->firstname)."',"; $sql .= " ".($user->id > 0 ? "'".$this->db->escape($user->id)."'" : "null").","; @@ -721,8 +755,7 @@ class Contact extends CommonObject if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname; if ($this->poste) $info["title"] = $this->poste; - if ($this->socid > 0) - { + if ($this->socid > 0) { $soc = new Societe($this->db); $soc->fetch($this->socid); @@ -757,8 +790,7 @@ class Contact extends CommonObject $info["phpgwContactCatId"] = 0; $info["phpgwContactAccess"] = "public"; - if (dol_strlen($this->egroupware_id) == 0) - { + if (dol_strlen($this->egroupware_id) == 0) { $this->egroupware_id = 1; } @@ -856,7 +888,7 @@ class Contact extends CommonObject * @param User $user Load also alerts of this user (subscribing to alerts) that want alerts about this contact * @param string $ref_ext External reference, not given by Dolibarr * @param string $email Email - * @param int $loadalsoroles Load also roles + * @param int $loadalsoroles Load also roles. Try to always 0 here and load roles with a separate call of fetchRoles(). * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found. */ public function fetch($id, $user = null, $ref_ext = '', $email = '', $loadalsoroles = 0) @@ -1180,6 +1212,20 @@ class Contact extends CommonObject } } + if (!$error) + { + // Remove Roles + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id; + dol_syslog(__METHOD__, LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error .= $this->db->lasterror(); + $errorflag = -1; + } + } + if (!$error) { // Remove category @@ -1601,10 +1647,11 @@ class Contact extends CommonObject } /** - * Fetch Roles for a contact + * Fetch roles (default contact of some companies) for the current contact. + * This load the array ->roles. * - * @return float|int - * @throws Exception + * @return int <0 if KO, Nb of roles found if OK + * @see updateRoles() */ public function fetchRoles() { @@ -1612,25 +1659,23 @@ class Contact extends CommonObject $error = 0; $num = 0; - $sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle, sc.rowid as contactroleid"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."c_type_contact as tc"; - $sql .= " ON tc.rowid = sc.fk_c_type_contact"; - $sql .= " AND sc.fk_socpeople = ".$this->id; + $sql = "SELECT tc.rowid, tc.element, tc.source, tc.code, tc.libelle as label, sc.rowid as contactroleid, sc.fk_soc as socid"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe_contacts as sc, ".MAIN_DB_PREFIX."c_type_contact as tc"; + $sql .= " WHERE tc.rowid = sc.fk_c_type_contact"; $sql .= " AND tc.source = 'external' AND tc.active=1"; + $sql .= " AND sc.fk_socpeople = ".$this->id; $sql .= " AND sc.entity IN (".getEntity('societe').')'; - dol_syslog(__METHOD__, LOG_DEBUG); - - $this->roles = array(); $resql = $this->db->query($sql); if ($resql) { + $this->roles = array(); + $num = $this->db->num_rows($resql); if ($num > 0) { while ($obj = $this->db->fetch_object($resql)) { $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code; $libelle_element = $langs->trans('ContactDefault_'.$obj->element); - $this->roles[$obj->contactroleid] = array('id'=>$obj->rowid, 'element'=>$obj->element, 'source'=>$obj->source, 'code'=>$obj->code, 'label'=>$libelle_element.' - '.($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle)); + $this->roles[$obj->contactroleid] = array('id'=>$obj->rowid, 'socid'=>$obj->socid, 'element'=>$obj->element, 'source'=>$obj->source, 'code'=>$obj->code, 'label'=>$libelle_element.' - '.($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->label)); } } } else { @@ -1692,10 +1737,11 @@ class Contact extends CommonObject } /** - * Updates Roles + * Updates all roles (default contact for companies) according to values inside the ->roles array. + * This is called by update of contact. * * @return float|int - * @throws Exception + * @see fetchRoles() */ public function updateRoles() { @@ -1703,11 +1749,12 @@ class Contact extends CommonObject $error = 0; + if (!isset($this->roles)) return; // Avoid to loose roles when property not set + $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".$this->socid." AND fk_socpeople=".$this->id; ; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople=".$this->id." AND entity IN (".getEntity("societe_contact").")"; - dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if (!$result) { $this->errors[] = $this->db->lasterror().' sql='.$sql; @@ -1715,25 +1762,40 @@ class Contact extends CommonObject } else { if (count($this->roles) > 0) { foreach ($this->roles as $keyRoles => $valRoles) { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_contacts"; - $sql .= " (entity,"; - $sql .= "date_creation,"; - $sql .= "fk_soc,"; - $sql .= "fk_c_type_contact,"; - $sql .= "fk_socpeople) "; - $sql .= " VALUES (".$conf->entity.","; - $sql .= "'".$this->db->idate(dol_now())."',"; - $sql .= $this->socid.", "; - $sql .= $valRoles." , "; - $sql .= $this->id; - $sql .= ")"; - dol_syslog(__METHOD__, LOG_DEBUG); + $idrole = 0; + if (is_array($valRoles)) { + $idrole = $valRoles['id']; + } else { + $idrole = $valRoles; + } - $result = $this->db->query($sql); - if (!$result) - { - $this->errors[] = $this->db->lasterror().' sql='.$sql; - $error++; + $socid = 0; + if (is_array($valRoles)) { + $socid = $valRoles['socid']; + } else { + $socid = $this->socid; + } + + if ($socid > 0) { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_contacts"; + $sql .= " (entity,"; + $sql .= "date_creation,"; + $sql .= "fk_soc,"; + $sql .= "fk_c_type_contact,"; + $sql .= "fk_socpeople) "; + $sql .= " VALUES (".$conf->entity.","; + $sql .= "'".$this->db->idate(dol_now())."',"; + $sql .= $socid.", "; + $sql .= $idrole." , "; + $sql .= $this->id; + $sql .= ")"; + + $result = $this->db->query($sql); + if (!$result) + { + $this->errors[] = $this->db->lasterror().' sql='.$sql; + $error++; + } } } } @@ -1880,4 +1942,93 @@ class Contact extends CommonObject return "Error, mode/status not found"; } + + + /** + * Set "blacklist" mailing status + * + * @param int $no_email 1=Do not send mailing, 0=Ok to recieve mailling + * @return int <0 if KO, >0 if OK + */ + public function setNoEmail($no_email) + { + $error = 0; + + // Update mass emailing flag into table mailing_unsubscribe + if ($this->email) + { + $this->db->begin(); + + if ($no_email) + { + $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'"; + $resql = $this->db->query($sql); + if ($resql) + { + $obj = $this->db->fetch_object($resql); + $noemail = $obj->nb; + if (empty($noemail)) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".$this->db->escape(getEntity('mailing', 0)).", '".$this->db->idate(dol_now())."')"; + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + } + } else { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + } else { + $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity = ".$this->db->escape(getEntity('mailing', 0)); + $resql = $this->db->query($sql); + if (!$resql) + { + $error++; + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + } + } + + if (empty($error)) { + $this->no_email = $no_email; + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return $error * -1; + } + } + + return 0; + } + + /** + * get "blacklist" mailing status + * set no_email attribut to 1 or 0 + * + * @return int <0 if KO, >0 if OK + */ + public function getNoEmail() + { + if ($this->email) + { + $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'"; + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + $this->no_email = $obj->nb; + return 1; + } else { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + return -1; + } + } + return 0; + } } diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 8d6b11e19f0..c33867fed7f 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -933,31 +933,31 @@ while ($i < min($num, $limit)) // Phone if (!empty($arrayfields['p.phone']['checked'])) { - print ''.dol_print_phone($obj->phone_pro, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL').''; + print ''.dol_print_phone($obj->phone_pro, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''; if (!$i) $totalarray['nbfield']++; } // Phone perso if (!empty($arrayfields['p.phone_perso']['checked'])) { - print ''.dol_print_phone($obj->phone_perso, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL').''; + print ''.dol_print_phone($obj->phone_perso, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''; if (!$i) $totalarray['nbfield']++; } // Phone mobile if (!empty($arrayfields['p.phone_mobile']['checked'])) { - print ''.dol_print_phone($obj->phone_mobile, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL').''; + print ''.dol_print_phone($obj->phone_mobile, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'mobile').''; if (!$i) $totalarray['nbfield']++; } // Fax if (!empty($arrayfields['p.fax']['checked'])) { - print ''.dol_print_phone($obj->fax, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL').''; + print ''.dol_print_phone($obj->fax, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'fax').''; if (!$i) $totalarray['nbfield']++; } // EMail if (!empty($arrayfields['p.email']['checked'])) { - print ''.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 18).''; + print ''.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 18, 0, 1).''; if (!$i) $totalarray['nbfield']++; } // No EMail diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 678ed9bbbd6..8d78b410329 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -213,7 +213,7 @@ if (empty($reshook)) $object->note_private = GETPOST('note_private', 'alpha'); $object->note_public = GETPOST('note_public', 'alpha'); $object->fk_project = GETPOST('projectid', 'int'); - $object->remise_percent = GETPOST('remise_percent', 'alpha'); + $object->remise_percent = price2num(GETPOST('remise_percent'), 2); $object->ref = GETPOST('ref', 'alpha'); $object->ref_customer = GETPOST('ref_customer', 'alpha'); $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); @@ -385,7 +385,7 @@ if (empty($reshook)) $predef = ''; $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); $price_ht = price2num(GETPOST('price_ht'), 'MU'); - $price_ht_devise = price2num(GETPOST('multicurrency_price_ht', 'CR')); + $price_ht_devise = price2num(GETPOST('multicurrency_price_ht', 'CU')); if (GETPOST('prod_entry_mode', 'alpha') == 'free') { $idprod = 0; @@ -395,8 +395,8 @@ if (empty($reshook)) $tva_tx = ''; } - $qty = price2num(GETPOST('qty'.$predef), 'alpha'); - $remise_percent = ((GETPOST('remise_percent'.$predef) != '') ? GETPOST('remise_percent'.$predef) : 0); + $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); + $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), 2) : 0); if ($qty == '') { @@ -499,6 +499,12 @@ if (empty($reshook)) } $desc = $prod->description; + + //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time + if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) { + $product_desc=''; + } + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); @@ -667,10 +673,10 @@ if (empty($reshook)) $objectline->fk_product = GETPOST('idprod', 'int'); $objectline->description = GETPOST('product_desc', 'restricthtml'); - $objectline->price_ht = GETPOST('elprice'); - $objectline->subprice = GETPOST('elprice'); - $objectline->qty = GETPOST('elqty'); - $objectline->remise_percent = GETPOST('elremise_percent'); + $objectline->price_ht = price2num(GETPOST('elprice'), 'MU'); + $objectline->subprice = price2num(GETPOST('elprice'), 'MU'); + $objectline->qty = price2num(GETPOST('elqty'), 'MS'); + $objectline->remise_percent = price2num(GETPOST('elremise_percent'), 2); $objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0 $objectline->vat_src_code = $vat_src_code; $objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index 72a8ec2974d..1226d578f2f 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -33,6 +33,7 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; @@ -175,6 +176,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $sall = ""; $search_status = ""; $toselect = ''; + $search_type_thirdparty = ''; $search_array_options = array(); } @@ -198,6 +200,7 @@ $form = new Form($db); $formfile = new FormFile($db); $formother = new FormOther($db); $socstatic = new Societe($db); +$formcompany = new FormCompany($db); $contracttmp = new Contrat($db); $sql = 'SELECT'; @@ -235,6 +238,7 @@ if ($search_user > 0) } $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= ' AND c.entity IN ('.getEntity('contract').')'; +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; if ($socid) $sql .= " AND s.rowid = ".$db->escape($socid); if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; @@ -275,7 +279,6 @@ if ($search_dfyear > 0 && $search_op2df) else $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; } $sql .= $db->order($sortfield, $sortorder); -//print $sql; $totalnboflines = 0; $result = $db->query($sql); @@ -347,6 +350,7 @@ if ($search_dfyear != '') $param .= '&search_dfyear='.urlencode($search_df if ($search_dfmonth != '') $param .= '&search_dfmonth='.urlencode($search_dfmonth); if ($search_sale != '') $param .= '&search_sale='.urlencode($search_sale); if ($search_user != '') $param .= '&search_user='.urlencode($search_user); +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); if ($show_files) $param .= '&show_files='.urlencode($show_files); if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); @@ -492,7 +496,7 @@ if (!empty($arrayfields['country.code_iso']['checked'])) if (!empty($arrayfields['typent.code']['checked'])) { print ''; - print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 0, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT)); + print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print ''; } if (!empty($arrayfields['sale_representative']['checked'])) @@ -658,7 +662,7 @@ while ($i < min($num, $limit)) } if (!empty($arrayfields['s.nom']['checked'])) { - print ''; + print ''; if ($obj->socid > 0) { // TODO Use a cache for this string print $socstatic->getNomUrl(1, ''); @@ -717,15 +721,13 @@ while ($i < min($num, $limit)) $listsalesrepresentatives = $socstatic->getSalesRepresentatives($user); if ($listsalesrepresentatives < 0) dol_print_error($db); $nbofsalesrepresentative = count($listsalesrepresentatives); - if ($nbofsalesrepresentative > 3) { + if ($nbofsalesrepresentative > 6) { // We print only number print $nbofsalesrepresentative; - } elseif ($nbofsalesrepresentative > 0) - { + } elseif ($nbofsalesrepresentative > 0) { $userstatic = new User($db); $j = 0; - foreach ($listsalesrepresentatives as $val) - { + foreach ($listsalesrepresentatives as $val) { $userstatic->id = $val['id']; $userstatic->lastname = $val['lastname']; $userstatic->firstname = $val['firstname']; @@ -733,17 +735,23 @@ while ($i < min($num, $limit)) $userstatic->statut = $val['statut']; $userstatic->entity = $val['entity']; $userstatic->photo = $val['photo']; + $userstatic->login = $val['login']; + $userstatic->phone = $val['phone']; + $userstatic->job = $val['job']; + $userstatic->gender = $val['gender']; //print '
': - print $userstatic->getNomUrl(-2); + print ($nbofsalesrepresentative < 2) ? $userstatic->getNomUrl(-1, '', 0, 0, 12) : $userstatic->getNomUrl(-2); $j++; - if ($j < $nbofsalesrepresentative) print ' '; + if ($j < $nbofsalesrepresentative) { + print ' '; + } //print '
'; } } //else print $langs->trans("NoSalesRepresentativeAffected"); } else { - print ' '; + print ' '; } print ''; } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 81cc4d81bd4..95c5037c5fb 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -304,7 +304,7 @@ if (!$error && $massaction == 'confirm_presend') if ($_POST['addmaindocfile']) { // TODO Use future field $objectobj->fullpathdoc to know where is stored default file - // TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc. + // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf'; $subdir = ''; // TODO Set subdir to be compatible with multi levels dir trees @@ -590,7 +590,8 @@ if (!$error && $massaction == 'confirm_presend') } } -if ($massaction == 'confirm_createbills') // Create bills from orders +// TODO Move this action into commande/list.php if called only by this page. +if ($massaction == 'confirm_createbills') // Create bills from orders. { $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); @@ -600,6 +601,8 @@ if ($massaction == 'confirm_createbills') // Create bills from orders $TFactThird = array(); $nb_bills_created = 0; + $lastid= 0; + $lastref = ''; $db->begin(); @@ -609,8 +612,9 @@ if ($massaction == 'confirm_createbills') // Create bills from orders if ($cmd->fetch($id_order) <= 0) continue; $objecttmp = new Facture($db); - if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. - else { + if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) { + $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order. + } else { // Load extrafields of order $cmd->fetch_optionals(); @@ -636,7 +640,11 @@ if ($massaction == 'confirm_createbills') // Create bills from orders $res = $objecttmp->create($user); - if ($res > 0) $nb_bills_created++; + if ($res > 0) { + $nb_bills_created++; + $lastref = $objecttmp->ref; + $lastid = $objecttmp->id; + } } if ($objecttmp->id > 0) @@ -818,7 +826,14 @@ if ($massaction == 'confirm_createbills') // Create bills from orders if (!$error) { $db->commit(); - setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs'); + + if ($nb_bills_created == 1) { + $texttoshow = $langs->trans('BillXCreated', '{s1}'); + $texttoshow = str_replace('{s1}', ''.$lastref.'', $texttoshow); + setEventMessages($texttoshow, null, 'mesgs'); + } else { + setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs'); + } // Make a redirect to avoid to bill twice if we make a refresh or back $param = ''; @@ -1266,7 +1281,7 @@ if (!$error && $massaction == 'generate_doc' && $permissiontoread) if (empty($hideref)) $hideref = 0; if (empty($moreparams)) $moreparams = null; - $result = $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); + $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); if ($result <= 0) { diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 929d35d9730..1bea255bda2 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -227,7 +227,7 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST } if (count($receivercc) > 0) { foreach ($receivercc as $key => $val) { - if ($val == 'thirdparty') { // Key selected means currentthird party (may be usd for current member or current user too) + if ($val == 'thirdparty') { // Key selected means current thirdparty (may be usd for current member or current user too) // Recipient was provided from combo list $tmparray[] = dol_string_nospecial($thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>'; } elseif ($val == 'contact') { // Key selected means current contact @@ -399,7 +399,6 @@ if (($action == 'send' || $action == 'relance') && !$_POST['addfile'] && !$_POST $error++; } // End call triggers - if ($error) { setEventMessages($object->error, $object->errors, 'errors'); } diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index 24220f79f8c..d662d3c85c9 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -21,7 +21,7 @@ * \brief Code for actions on setting notes of object page */ - +// $error must have been initialized to 0 // $action must be defined // $arrayofparameters must be set for action 'update' // $nomessageinupdate can be set to 1 @@ -31,7 +31,6 @@ if ($action == 'update' && is_array($arrayofparameters)) { $db->begin(); - $ok = true; foreach ($arrayofparameters as $key => $val) { // Modify constant only if key was posted (avoid resetting key to the null value) @@ -40,7 +39,7 @@ if ($action == 'update' && is_array($arrayofparameters)) $result = dolibarr_set_const($db, $key, GETPOST($key, 'alpha'), 'chaine', 0, '', $conf->entity); if ($result < 0) { - $ok = false; + $error++; break; } } @@ -74,7 +73,7 @@ if ($action == 'setModuleOptions') if ($param) { $res = dolibarr_set_const($db, $param, $value, 'chaine', 0, '', $conf->entity); - if (!$res > 0) $error++; + if (!($res > 0)) $error++; } } } @@ -93,7 +92,11 @@ if ($action == 'setModuleOptions') if (!$tmpdir) { unset($listofdir[$key]); continue; } - if (!is_dir($tmpdir)) $texttitle .= img_warning($langs->trans("ErrorDirNotFound", $tmpdir), 0); + if (!is_dir($tmpdir)) { + if (empty($nomessageinsetmoduleoptions)) { + setEventMessages($langs->trans("ErrorDirNotFound", $tmpdir), null, 'warnings'); + } + } else { $upload_dir = $tmpdir; } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 41e23819266..9575208f485 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -201,6 +201,13 @@ if ($type == 'directory') 'mrp-mo' ); + $parameters = array('modulepart'=>$module); + $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); + if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray)>0) + { + $automodules[]=$hookmanager->resArray['module']; + } + // TODO change for multicompany sharing if ($module == 'company') $upload_dir = $conf->societe->dir_output; elseif ($module == 'invoice') $upload_dir = $conf->facture->dir_output; @@ -220,6 +227,13 @@ if ($type == 'directory') elseif ($module == 'recruitment-recruitmentcandidature') $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature'; elseif ($module == 'banque') $upload_dir = $conf->bank->dir_output; elseif ($module == 'mrp-mo') $upload_dir = $conf->mrp->dir_output.'/mo'; + else { + $parameters = array('modulepart'=>$module); + $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); + if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) { + $upload_dir = $hookmanager->resArray['directory']; + } + } // Automatic list if (in_array($module, $automodules)) diff --git a/htdocs/core/boxes/box_birthdays.php b/htdocs/core/boxes/box_birthdays.php index 9a2ccd33cf7..ea83e022079 100644 --- a/htdocs/core/boxes/box_birthdays.php +++ b/htdocs/core/boxes/box_birthdays.php @@ -91,7 +91,7 @@ class box_birthdays extends ModeleBoxes $sql .= " WHERE u.entity IN (".getEntity('user').")"; $sql .= " AND u.statut = 1"; $sql .= dolSqlDateFilter('u.birth', 0, $tmparray['mon'], 0); - $sql .= " ORDER BY u.birth ASC"; + $sql .= " ORDER BY DAY(u.birth) ASC"; $sql .= $this->db->plimit($max, 0); dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); diff --git a/htdocs/core/boxes/box_birthdays_members.php b/htdocs/core/boxes/box_birthdays_members.php index 02a315ea836..56619fac581 100644 --- a/htdocs/core/boxes/box_birthdays_members.php +++ b/htdocs/core/boxes/box_birthdays_members.php @@ -91,7 +91,7 @@ class box_birthdays_members extends ModeleBoxes $sql .= " WHERE u.entity IN (".getEntity('adherent').")"; $sql .= " AND u.statut = 1"; $sql .= dolSqlDateFilter('u.birth', 0, $tmparray['mon'], 0); - $sql .= " ORDER BY u.birth ASC"; + $sql .= " ORDER BY DAY(u.birth) ASC"; $sql .= $this->db->plimit($max, 0); dol_syslog(get_class($this)."::loadBox", LOG_DEBUG); diff --git a/htdocs/core/boxes/box_clients.php b/htdocs/core/boxes/box_clients.php index 11e8b6a8f29..adcff0d158c 100644 --- a/htdocs/core/boxes/box_clients.php +++ b/htdocs/core/boxes/box_clients.php @@ -2,7 +2,7 @@ /* Copyright (C) 2003-2007 Rodolphe Quiedeville * Copyright (C) 2004-2010 Laurent Destailleur * Copyright (C) 2005-2009 Regis Houssin - * Copyright (C) 2015 Frederic France + * Copyright (C) 2015-2021 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 @@ -79,7 +79,7 @@ class box_clients extends ModeleBoxes $this->max = $max; - include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; + include_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; $thirdpartystatic = new Client($this->db); $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedCustomers", $max)); diff --git a/htdocs/core/boxes/box_commandes.php b/htdocs/core/boxes/box_commandes.php index 3f7875ce7d4..9b020a05711 100644 --- a/htdocs/core/boxes/box_commandes.php +++ b/htdocs/core/boxes/box_commandes.php @@ -83,7 +83,7 @@ class box_commandes extends ModeleBoxes $societestatic = new Societe($this->db); $userstatic = new User($this->db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."CustomerOrders", $max)); + $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".(!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) ? "" : "Modified")."CustomerOrders", $max)); if ($user->rights->commande->lire) { @@ -108,7 +108,7 @@ class box_commandes extends ModeleBoxes if (!empty($conf->global->ORDER_BOX_LAST_ORDERS_VALIDATED_ONLY)) $sql .= " AND c.fk_statut = 1"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY c.date_commande DESC, c.ref DESC "; + if (!empty($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 .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_contracts.php b/htdocs/core/boxes/box_contracts.php index 9350bae2da9..0fa10b43fd8 100644 --- a/htdocs/core/boxes/box_contracts.php +++ b/htdocs/core/boxes/box_contracts.php @@ -92,7 +92,7 @@ class box_contracts extends ModeleBoxes $sql .= " AND c.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY c.date_contrat DESC, c.ref DESC "; + if (! empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE)) $sql .= " ORDER BY c.date_contrat DESC, c.ref DESC "; else $sql .= " ORDER BY c.tms DESC, c.ref DESC "; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_dolibarr_state_board.php b/htdocs/core/boxes/box_dolibarr_state_board.php new file mode 100644 index 00000000000..c1a81bafbed --- /dev/null +++ b/htdocs/core/boxes/box_dolibarr_state_board.php @@ -0,0 +1,321 @@ + + * Copyright (C) 2004-2010 Laurent Destailleur + * Copyright (C) 2005-2009 Regis Houssin + * Copyright (C) 2015-2021 Frederic France + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/core/boxes/box_dolibarr_state_board.php + * \ingroup + * \brief Module Dolibarr state base + */ + +include_once DOL_DOCUMENT_ROOT . '/core/boxes/modules_boxes.php'; +include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php'; + + +/** + * Class to manage the box to show last thirdparties + */ +class box_dolibarr_state_board extends ModeleBoxes +{ + public $boxcode = "dolibarrstatebox"; + public $boximg = "generic"; + public $boxlabel = "BoxDolibarrStateBoard"; + public $depends = array("user"); + + /** + * @var DoliDB Database handler. + */ + public $db; + + public $enabled = 1; + + public $info_box_head = array(); + public $info_box_contents = array(); + + + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param = '') + { + global $conf, $user; + + $this->db = $db; + + // disable box for such cases + if (!empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) { + $this->enabled = 0; // disabled by this option + } + + $this->hidden = !($user->rights->societe->lire && empty($user->socid)); + } + + /** + * Load data for box to show them later + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $user, $langs, $conf; + $langs->load("boxes"); + + $this->max = $max; + $this->info_box_head = array('text' => $langs->trans("DolibarrStateBoard")); + + if (empty($user->socid) && empty($conf->global->MAIN_DISABLE_GLOBAL_BOXSTATS)) { + $hookmanager = new HookManager($this->db); + $hookmanager->initHooks(array('index')); + $boxstatItems = array(); + $boxstatFromHook = ''; + $boxstatFromHook = $hookmanager->resPrint; + $boxstat = ''; + + $keys = array( + 'users', + 'members', + 'expensereports', + 'holidays', + 'customers', + 'prospects', + 'suppliers', + 'contacts', + 'products', + 'services', + 'projects', + 'proposals', + 'orders', + 'invoices', + 'donations', + 'supplier_proposals', + 'supplier_orders', + 'supplier_invoices', + 'contracts', + 'interventions', + 'ticket' + ); + $conditions = array( + 'users' => $user->rights->user->user->lire, + 'members' => !empty($conf->adherent->enabled) && $user->rights->adherent->lire, + 'customers' => !empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS_STATS), + 'prospects' => !empty($conf->societe->enabled) && $user->rights->societe->lire && empty($conf->global->SOCIETE_DISABLE_PROSPECTS) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS_STATS), + 'suppliers' => !empty($conf->fournisseur->enabled) && $user->rights->fournisseur->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_STATS), + 'contacts' => !empty($conf->societe->enabled) && $user->rights->societe->contact->lire, + 'products' => !empty($conf->product->enabled) && $user->rights->produit->lire, + 'services' => !empty($conf->service->enabled) && $user->rights->service->lire, + 'proposals' => !empty($conf->propal->enabled) && $user->rights->propale->lire, + 'orders' => !empty($conf->commande->enabled) && $user->rights->commande->lire, + 'invoices' => !empty($conf->facture->enabled) && $user->rights->facture->lire, + 'donations' => !empty($conf->don->enabled) && $user->rights->don->lire, + 'contracts' => !empty($conf->contrat->enabled) && $user->rights->contrat->lire, + 'interventions' => !empty($conf->ficheinter->enabled) && $user->rights->ficheinter->lire, + 'supplier_orders' => !empty($conf->supplier_order->enabled) && $user->rights->fournisseur->commande->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_ORDERS_STATS), + 'supplier_invoices' => !empty($conf->supplier_invoice->enabled) && $user->rights->fournisseur->facture->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_INVOICES_STATS), + 'supplier_proposals' => !empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire && empty($conf->global->SOCIETE_DISABLE_SUPPLIERS_PROPOSAL_STATS), + 'projects' => !empty($conf->projet->enabled) && $user->rights->projet->lire, + 'expensereports' => !empty($conf->expensereport->enabled) && $user->rights->expensereport->lire, + 'holidays' => !empty($conf->holiday->enabled) && $user->rights->holiday->read, + 'ticket' => !empty($conf->ticket->enabled) && $user->rights->ticket->read + ); + $classes = array( + 'users' => 'User', + 'members' => 'Adherent', + 'customers' => 'Client', + 'prospects' => 'Client', + 'suppliers' => 'Fournisseur', + 'contacts' => 'Contact', + 'products' => 'Product', + 'services' => 'ProductService', + 'proposals' => 'Propal', + 'orders' => 'Commande', + 'invoices' => 'Facture', + 'donations' => 'Don', + 'contracts' => 'Contrat', + 'interventions' => 'Fichinter', + 'supplier_orders' => 'CommandeFournisseur', + 'supplier_invoices' => 'FactureFournisseur', + 'supplier_proposals' => 'SupplierProposal', + 'projects' => 'Project', + 'expensereports' => 'ExpenseReport', + 'holidays' => 'Holiday', + 'ticket' => 'Ticket', + ); + $includes = array( + 'users' => DOL_DOCUMENT_ROOT . "/user/class/user.class.php", + 'members' => DOL_DOCUMENT_ROOT . "/adherents/class/adherent.class.php", + 'customers' => DOL_DOCUMENT_ROOT . "/societe/class/client.class.php", + 'prospects' => DOL_DOCUMENT_ROOT . "/societe/class/client.class.php", + 'suppliers' => DOL_DOCUMENT_ROOT . "/fourn/class/fournisseur.class.php", + 'contacts' => DOL_DOCUMENT_ROOT . "/contact/class/contact.class.php", + 'products' => DOL_DOCUMENT_ROOT . "/product/class/product.class.php", + 'services' => DOL_DOCUMENT_ROOT . "/product/class/product.class.php", + 'proposals' => DOL_DOCUMENT_ROOT . "/comm/propal/class/propal.class.php", + 'orders' => DOL_DOCUMENT_ROOT . "/commande/class/commande.class.php", + 'invoices' => DOL_DOCUMENT_ROOT . "/compta/facture/class/facture.class.php", + 'donations' => DOL_DOCUMENT_ROOT . "/don/class/don.class.php", + 'contracts' => DOL_DOCUMENT_ROOT . "/contrat/class/contrat.class.php", + 'interventions' => DOL_DOCUMENT_ROOT . "/fichinter/class/fichinter.class.php", + 'supplier_orders' => DOL_DOCUMENT_ROOT . "/fourn/class/fournisseur.commande.class.php", + 'supplier_invoices' => DOL_DOCUMENT_ROOT . "/fourn/class/fournisseur.facture.class.php", + 'supplier_proposals' => DOL_DOCUMENT_ROOT . "/supplier_proposal/class/supplier_proposal.class.php", + 'projects' => DOL_DOCUMENT_ROOT . "/projet/class/project.class.php", + 'expensereports' => DOL_DOCUMENT_ROOT . "/expensereport/class/expensereport.class.php", + 'holidays' => DOL_DOCUMENT_ROOT . "/holiday/class/holiday.class.php", + 'ticket' => DOL_DOCUMENT_ROOT . "/ticket/class/ticket.class.php" + ); + $links = array( + 'users' => DOL_URL_ROOT . '/user/list.php', + 'members' => DOL_URL_ROOT . '/adherents/list.php?statut=1&mainmenu=members', + 'customers' => DOL_URL_ROOT . '/societe/list.php?type=c&mainmenu=companies', + 'prospects' => DOL_URL_ROOT . '/societe/list.php?type=p&mainmenu=companies', + 'suppliers' => DOL_URL_ROOT . '/societe/list.php?type=f&mainmenu=companies', + 'contacts' => DOL_URL_ROOT . '/contact/list.php?mainmenu=companies', + 'products' => DOL_URL_ROOT . '/product/list.php?type=0&mainmenu=products', + 'services' => DOL_URL_ROOT . '/product/list.php?type=1&mainmenu=products', + 'proposals' => DOL_URL_ROOT . '/comm/propal/list.php?mainmenu=commercial&leftmenu=propals', + 'orders' => DOL_URL_ROOT . '/commande/list.php?mainmenu=commercial&leftmenu=orders', + 'invoices' => DOL_URL_ROOT . '/compta/facture/list.php?mainmenu=billing&leftmenu=customers_bills', + 'donations' => DOL_URL_ROOT . '/don/list.php?leftmenu=donations', + 'contracts' => DOL_URL_ROOT . '/contrat/list.php?mainmenu=commercial&leftmenu=contracts', + 'interventions' => DOL_URL_ROOT . '/fichinter/list.php?mainmenu=commercial&leftmenu=ficheinter', + 'supplier_orders' => DOL_URL_ROOT . '/fourn/commande/list.php?mainmenu=commercial&leftmenu=orders_suppliers', + 'supplier_invoices' => DOL_URL_ROOT . '/fourn/facture/list.php?mainmenu=billing&leftmenu=suppliers_bills', + 'supplier_proposals' => DOL_URL_ROOT . '/supplier_proposal/list.php?mainmenu=commercial&leftmenu=', + 'projects' => DOL_URL_ROOT . '/projet/list.php?mainmenu=project', + 'expensereports' => DOL_URL_ROOT . '/expensereport/list.php?mainmenu=hrm&leftmenu=expensereport', + 'holidays' => DOL_URL_ROOT . '/holiday/list.php?mainmenu=hrm&leftmenu=holiday', + 'ticket' => DOL_URL_ROOT . '/ticket/list.php?leftmenu=ticket' + ); + $titres = array( + 'users' => "Users", + 'members' => "Members", + 'customers' => "ThirdPartyCustomersStats", + 'prospects' => "ThirdPartyProspectsStats", + 'suppliers' => "Suppliers", + 'contacts' => "Contacts", + 'products' => "Products", + 'services' => "Services", + 'proposals' => "CommercialProposalsShort", + 'orders' => "CustomersOrders", + 'invoices' => "BillsCustomers", + 'donations' => "Donations", + 'contracts' => "Contracts", + 'interventions' => "Interventions", + 'supplier_orders' => "SuppliersOrders", + 'supplier_invoices' => "SuppliersInvoices", + 'supplier_proposals' => "SupplierProposalShort", + 'projects' => "Projects", + 'expensereports' => "ExpenseReports", + 'holidays' => "Holidays", + 'ticket' => "Ticket", + ); + $langfile = array( + 'customers' => "companies", + 'contacts' => "companies", + 'services' => "products", + 'proposals' => "propal", + 'invoices' => "bills", + 'supplier_orders' => "orders", + 'supplier_invoices' => "bills", + 'supplier_proposals' => 'supplier_proposal', + 'expensereports' => "trips", + 'holidays' => "holiday", + ); + $boardloaded = array(); + + foreach ($keys as $val) { + if ($conditions[$val]) { + $boxstatItem = ''; + $class = $classes[$val]; + // Search in cache if load_state_board is already realized + $classkeyforcache = $class; + if ($classkeyforcache == 'ProductService') $classkeyforcache = 'Product'; // ProductService use same load_state_board than Product + + if (!isset($boardloaded[$classkeyforcache]) || !is_object($boardloaded[$classkeyforcache])) { + include_once $includes[$val]; // Loading a class cost around 1Mb + + $board = new $class($this->db); + $board->load_state_board(); + $boardloaded[$class] = $board; + } else { + $board = $boardloaded[$classkeyforcache]; + } + + $langs->load(empty($langfile[$val]) ? $val : $langfile[$val]); + + $text = $langs->trans($titres[$val]); + $boxstatItem .= ''; + $boxstatItem .= '
'; + $boxstatItem .= '' . $text . '
'; + $boxstatItem .= '' . img_object("", $board->picto, 'class="inline-block"') . ' ' . ($board->nb[$val] ? $board->nb[$val] : 0) . ''; + $boxstatItem .= '
'; + $boxstatItem .= '
'; + + $boxstatItems[$val] = $boxstatItem; + } + } + + if (!empty($boxstatFromHook) || !empty($boxstatItems)) { + $boxstat .= $boxstatFromHook; + + if (is_array($boxstatItems) && count($boxstatItems) > 0) { + $boxstat .= implode('', $boxstatItems); + } + + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + $boxstat .= '
'; + + $this->info_box_contents[0][0] = array( + 'tr' => 'class="nohover"', + 'td' => '', + 'textnoformat' => $boxstat + ); + } + } else { + $this->info_box_contents[0][0] = array( + 'td' => '', + 'text' => $langs->trans("ReadPermissionNotAllowed") + ); + } + } + + + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } +} diff --git a/htdocs/core/boxes/box_factures.php b/htdocs/core/boxes/box_factures.php index 011342d8a30..20e83fb442c 100644 --- a/htdocs/core/boxes/box_factures.php +++ b/htdocs/core/boxes/box_factures.php @@ -81,7 +81,7 @@ class box_factures extends ModeleBoxes $langs->load("bills"); - $text = $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."CustomerBills", $max); + $text = $langs->trans("BoxTitleLast".(!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) ? "" : "Modified")."CustomerBills", $max); $this->info_box_head = array( 'text' => $text, 'limit'=> dol_strlen($text) @@ -106,7 +106,7 @@ class box_factures extends ModeleBoxes $sql .= " AND f.entity IN (".getEntity('invoice').")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY f.datef DESC, f.ref DESC "; + if (!empty($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 .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_factures_fourn.php b/htdocs/core/boxes/box_factures_fourn.php index d3c1ccd9017..1858a308756 100644 --- a/htdocs/core/boxes/box_factures_fourn.php +++ b/htdocs/core/boxes/box_factures_fourn.php @@ -81,7 +81,7 @@ class box_factures_fourn extends ModeleBoxes $thirdpartystatic = new Fournisseur($this->db); $this->info_box_head = array( - 'text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."SupplierBills", $max) + 'text' => $langs->trans("BoxTitleLast".(!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) ? "" : "Modified")."SupplierBills", $max) ); if ($user->rights->fournisseur->facture->lire) @@ -104,7 +104,7 @@ class box_factures_fourn extends ModeleBoxes $sql .= " AND f.entity = ".$conf->entity; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY f.datef DESC, f.ref DESC "; + if (!empty($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 .= $this->db->plimit($max, 0); @@ -133,7 +133,7 @@ class box_factures_fourn extends ModeleBoxes $thirdpartystatic->id = $objp->socid; $thirdpartystatic->name = $objp->name; - //$thirdpartystatic->name_alias = $objp->name_alias; + $thirdpartystatic->name_alias = $objp->name_alias; $thirdpartystatic->code_fournisseur = $objp->code_fournisseur; $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur; $thirdpartystatic->fournisseur = $objp->fournisseur; diff --git a/htdocs/core/boxes/box_factures_fourn_imp.php b/htdocs/core/boxes/box_factures_fourn_imp.php index b957e5bf0c1..99848d916f4 100644 --- a/htdocs/core/boxes/box_factures_fourn_imp.php +++ b/htdocs/core/boxes/box_factures_fourn_imp.php @@ -26,7 +26,7 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; /** - * Class to manage the box to show not payed suppliers invoices + * Class to manage the box to show not paid suppliers invoices */ class box_factures_fourn_imp extends ModeleBoxes { @@ -130,7 +130,7 @@ class box_factures_fourn_imp extends ModeleBoxes $thirdpartystatic->id = $objp->socid; $thirdpartystatic->name = $objp->name; - //$thirdpartystatic->name_alias = $objp->name_alias; + $thirdpartystatic->name_alias = $objp->name_alias; $thirdpartystatic->code_fournisseur = $objp->code_fournisseur; $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur; $thirdpartystatic->fournisseur = $objp->fournisseur; diff --git a/htdocs/core/boxes/box_factures_imp.php b/htdocs/core/boxes/box_factures_imp.php index 08233ff754c..b47f948f4ca 100644 --- a/htdocs/core/boxes/box_factures_imp.php +++ b/htdocs/core/boxes/box_factures_imp.php @@ -110,7 +110,8 @@ class box_factures_imp extends ModeleBoxes $sql .= " AND fk_statut = 1"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " GROUP BY s.nom, s.rowid, s.email, s.code_client, s.logo, f.ref, f.date_lim_reglement,"; + $sql .= " GROUP BY s.rowid, s.nom, s.name_alias, s.code_client, s.code_compta, s.client, s.logo, s.email, s.entity, s.tva_intra, s.siren, s.siret, s.ape, s.idprof4, s.idprof5, s.idprof6,"; + $sql .= " f.ref, f.date_lim_reglement,"; $sql .= " f.type, f.datef, f.total, f.tva, f.total_ttc, f.paye, f.fk_statut, f.rowid"; //$sql.= " ORDER BY f.datef DESC, f.ref DESC "; $sql .= " ORDER BY datelimite ASC, f.ref ASC "; diff --git a/htdocs/core/boxes/box_funnel_of_prospection.php b/htdocs/core/boxes/box_funnel_of_prospection.php index 5b6130d8eb2..519cb2cd306 100644 --- a/htdocs/core/boxes/box_funnel_of_prospection.php +++ b/htdocs/core/boxes/box_funnel_of_prospection.php @@ -96,6 +96,7 @@ class box_funnel_of_prospection extends ModeleBoxes $listofopplabel = array(); $listofoppcode = array(); $colorseriesstat = array(); + $bordercolorseries = array(); $sql = "SELECT cls.rowid, cls.code, cls.percent, cls.label"; $sql .= " FROM " . MAIN_DB_PREFIX . "c_lead_status as cls"; $sql .= " WHERE active=1"; @@ -113,19 +114,24 @@ class box_funnel_of_prospection extends ModeleBoxes $listofoppcode[$objp->rowid] = $objp->code; switch ($objp->code) { case 'PROSP': - $colorseriesstat[$objp->rowid] = "-" . $badgeStatus0; + $colorseriesstat[$objp->rowid] = '#FFFFFF'; + $bordercolorseries[$objp->rowid] = $badgeStatus0; break; case 'QUAL': - $colorseriesstat[$objp->rowid] = "-" . $badgeStatus1; + $colorseriesstat[$objp->rowid] = '#FFFFFF'; + $bordercolorseries[$objp->rowid] = $badgeStatus1; break; case 'PROPO': $colorseriesstat[$objp->rowid] = $badgeStatus1; + $bordercolorseries[$objp->rowid] = $badgeStatus1; break; case 'NEGO': $colorseriesstat[$objp->rowid] = $badgeStatus4; + $bordercolorseries[$objp->rowid] = $badgeStatus4; break; case 'WON': $colorseriesstat[$objp->rowid] = $badgeStatus6; + $bordercolorseries[$objp->rowid] = $badgeStatus6; break; default: break; @@ -191,7 +197,10 @@ class box_funnel_of_prospection extends ModeleBoxes $listofstatus = array_keys($listofoppstatus); $liststatus = array(); $data = array(''); + $customlabels = array(); + $total=0; foreach ($listofstatus as $status) { + $customlabel = ''; $labelStatus = ''; if ($status != 7) { $code = dol_getIdFromCode($this->db, $status, 'c_lead_status', 'rowid', 'code'); @@ -201,8 +210,9 @@ class box_funnel_of_prospection extends ModeleBoxes if (empty($labelStatus)) { $labelStatus = $listofopplabel[$status]; } - - $data[] = (isset($valsamount[$status]) ? (float) $valsamount[$status] : 0); + $amount = (isset($valsamount[$status]) ? (float) $valsamount[$status] : 0); + $data[] = $amount; + $customlabel = $amount; $liststatus[] = $labelStatus; if (!$conf->use_javascript_ajax) { $stringtoprint .= ''; @@ -211,6 +221,7 @@ class box_funnel_of_prospection extends ModeleBoxes $stringtoprint .= "\n"; } } + $customlabels[]=$customlabel; } $dataseries[] = $data; if ($conf->use_javascript_ajax) { @@ -219,13 +230,18 @@ class box_funnel_of_prospection extends ModeleBoxes $dolgraph->SetMinValue(0); $dolgraph->SetData($dataseries); $dolgraph->SetLegend($liststatus); + $dolgraph->setHideXValues(true); $dolgraph->SetDataColor(array_values($colorseriesstat)); + $dolgraph->setBorderColor(array_values($bordercolorseries)); $dolgraph->setShowLegend(2); $dolgraph->setShowPercent(1); - $dolgraph->setTitle(''); + $dolgraph->setMirrorGraphValues(true); + $dolgraph->setBorderWidth(2); $dolgraph->SetType(array('horizontalbars')); $dolgraph->SetHeight('200'); $dolgraph->SetWidth('600'); + $dolgraph->setTooltipsTitles($liststatus); + $dolgraph->setTooltipsLabels($customlabels); $dolgraph->mode = 'depth'; $dolgraph->draw('idgraphleadfunnel'); $stringtoprint .= $dolgraph->show($totaloppnb ? 0 : 1); diff --git a/htdocs/core/boxes/box_graph_invoices_permonth.php b/htdocs/core/boxes/box_graph_invoices_permonth.php index 983bb75cbc3..97ebbee1d85 100644 --- a/htdocs/core/boxes/box_graph_invoices_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_permonth.php @@ -112,15 +112,16 @@ class box_graph_invoices_permonth extends ModeleBoxes $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $endyear = $tmparray['year']; - $shownb = $tmparray['shownb']; - $showtot = $tmparray['showtot']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - 1; + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + $mode = 'customer'; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; $HEIGHT = '192'; diff --git a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php index 1490f5ea6e9..d044c65b9f0 100644 --- a/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_invoices_supplier_permonth.php @@ -109,15 +109,17 @@ class box_graph_invoices_supplier_permonth extends ModeleBoxes $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $endyear = $tmparray['year']; - $shownb = $tmparray['shownb']; - $showtot = $tmparray['showtot']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); + if (empty($year)) $year = $nowarray['year']; if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - 1; + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + $mode = 'supplier'; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; $HEIGHT = '192'; diff --git a/htdocs/core/boxes/box_graph_orders_permonth.php b/htdocs/core/boxes/box_graph_orders_permonth.php index d9c26620553..9f0f5ece978 100644 --- a/htdocs/core/boxes/box_graph_orders_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_permonth.php @@ -112,15 +112,16 @@ class box_graph_orders_permonth extends ModeleBoxes $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $endyear = $tmparray['year']; - $shownb = $tmparray['shownb']; - $showtot = $tmparray['showtot']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - 1; + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + $mode = 'customer'; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; $HEIGHT = '192'; diff --git a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php index 765c6324516..c16c0616fbc 100644 --- a/htdocs/core/boxes/box_graph_orders_supplier_permonth.php +++ b/htdocs/core/boxes/box_graph_orders_supplier_permonth.php @@ -111,15 +111,16 @@ class box_graph_orders_supplier_permonth extends ModeleBoxes $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $endyear = $tmparray['year']; - $shownb = $tmparray['shownb']; - $showtot = $tmparray['showtot']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - 1; + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + $mode = 'supplier'; $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; $HEIGHT = '192'; diff --git a/htdocs/core/boxes/box_graph_product_distribution.php b/htdocs/core/boxes/box_graph_product_distribution.php index 407c66177b5..8c6049c720b 100644 --- a/htdocs/core/boxes/box_graph_product_distribution.php +++ b/htdocs/core/boxes/box_graph_product_distribution.php @@ -95,11 +95,11 @@ class box_graph_product_distribution extends ModeleBoxes $showpropalnb = GETPOST($param_showpropalnb, 'alpha'); $showordernb = GETPOST($param_showordernb, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $year = $tmparray['year']; - $showinvoicenb = $tmparray['showinvoicenb']; - $showpropalnb = $tmparray['showpropalnb']; - $showordernb = $tmparray['showordernb']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $year = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $showinvoicenb = (!empty($tmparray['showinvoicenb']) ? $tmparray['showinvoicenb'] : ''); + $showpropalnb = (!empty($tmparray['showpropalnb']) ? $tmparray['showpropalnb'] : ''); + $showordernb = (!empty($tmparray['showordernb']) ? $tmparray['showordernb'] : ''); } if (empty($showinvoicenb) && empty($showpropalnb) && empty($showordernb)) { $showpropalnb = 1; $showinvoicenb = 1; $showordernb = 1; } if (empty($conf->facture->enabled) || empty($user->rights->facture->lire)) $showinvoicenb = 0; diff --git a/htdocs/core/boxes/box_graph_propales_permonth.php b/htdocs/core/boxes/box_graph_propales_permonth.php index de1a1f8de83..29b7cab5a78 100644 --- a/htdocs/core/boxes/box_graph_propales_permonth.php +++ b/htdocs/core/boxes/box_graph_propales_permonth.php @@ -112,15 +112,16 @@ class box_graph_propales_permonth extends ModeleBoxes $shownb = GETPOST($param_shownb, 'alpha'); $showtot = GETPOST($param_showtot, 'alpha'); } else { - $tmparray = json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true); - $endyear = $tmparray['year']; - $shownb = $tmparray['shownb']; - $showtot = $tmparray['showtot']; + $tmparray = (!empty($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode]) ? json_decode($_COOKIE['DOLUSERCOOKIE_box_'.$this->boxcode], true) : array()); + $endyear = (!empty($tmparray['year']) ? $tmparray['year'] : ''); + $shownb = (!empty($tmparray['shownb']) ? $tmparray['shownb'] : ''); + $showtot = (!empty($tmparray['showtot']) ? $tmparray['showtot'] : ''); } if (empty($shownb) && empty($showtot)) { $shownb = 1; $showtot = 1; } $nowarray = dol_getdate(dol_now(), true); if (empty($endyear)) $endyear = $nowarray['year']; - $startyear = $endyear - 1; + $startyear = $endyear - (empty($conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH) ? 1 : $conf->global->MAIN_NB_OF_YEAR_IN_WIDGET_GRAPH); + $WIDTH = (($shownb && $showtot) || !empty($conf->dol_optimize_smallscreen)) ? '256' : '320'; $HEIGHT = '192'; @@ -176,8 +177,10 @@ class box_graph_propales_permonth extends ModeleBoxes //$datatype2 = array('lines','bars'); $filenamenb = $dir."/".$prefix."propalsamountinyear-".$endyear.".png"; - if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=propalsamountinyear-'.$endyear.'.png'; - if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstatssupplier&file=propalsamountinyear-'.$endyear.'.png'; + if (!empty($mode)) { + if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstats&file=propalsamountinyear-'.$endyear.'.png'; + if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=propalstatssupplier&file=propalsamountinyear-'.$endyear.'.png'; + } $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); diff --git a/htdocs/core/boxes/box_last_ticket.php b/htdocs/core/boxes/box_last_ticket.php index 268a6861524..dbc453eced6 100644 --- a/htdocs/core/boxes/box_last_ticket.php +++ b/htdocs/core/boxes/box_last_ticket.php @@ -134,7 +134,7 @@ class box_last_ticket extends ModeleBoxes $thirdparty->name = $objp->company_name; $link = $thirdparty->getNomUrl(1); } else { - $link = dol_print_email($objp->origin_email); + $link = ''.dol_print_email($objp->origin_email).''; } $r = 0; @@ -149,15 +149,15 @@ class box_last_ticket extends ModeleBoxes // Subject $this->info_box_contents[$i][$r] = array( - 'td' => '', - 'text' => $objp->subject, // Some event have no ref + 'td' => 'class="tdoverflowmax200"', + 'text' => ''.$objp->subject.'', // Some event have no ref 'url' => DOL_URL_ROOT."/ticket/card.php?track_id=".$objp->track_id, ); $r++; // Customer $this->info_box_contents[$i][$r] = array( - 'td' => '', + 'td' => 'class="tdoverflowmax100"', 'text' => $link, 'asis' => 1, ); diff --git a/htdocs/core/boxes/box_members.php b/htdocs/core/boxes/box_members.php index 2d0ad45a266..2a69c7b3a21 100644 --- a/htdocs/core/boxes/box_members.php +++ b/htdocs/core/boxes/box_members.php @@ -63,7 +63,9 @@ class box_members extends ModeleBoxes // disable module for such cases $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); - if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) $this->enabled = 0; // disabled for external users + if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { + $this->enabled = 0; // disabled for external users + } $this->hidden = !($user->rights->adherent->lire); } @@ -87,7 +89,7 @@ class box_members extends ModeleBoxes $this->info_box_head = array('text' => $langs->trans("BoxTitleLastModifiedMembers", $max)); if ($user->rights->adherent->lire) { - $sql = "SELECT a.rowid, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; + $sql = "SELECT a.rowid, a.ref, a.lastname, a.firstname, a.societe as company, a.fk_soc,"; $sql .= " a.datec, a.tms, a.statut as status, a.datefin as date_end_subscription,"; $sql .= ' a.photo, a.email, a.gender, a.morphy,'; $sql .= " t.subscription"; @@ -110,14 +112,15 @@ class box_members extends ModeleBoxes $memberstatic->lastname = $objp->lastname; $memberstatic->firstname = $objp->firstname; $memberstatic->id = $objp->rowid; - $memberstatic->ref = $objp->rowid; + $memberstatic->ref = $objp->ref; $memberstatic->photo = $objp->photo; $memberstatic->gender = $objp->gender; $memberstatic->email = $objp->email; $memberstatic->morphy = $objp->morphy; $memberstatic->company = $objp->company; $memberstatic->statut = $objp->status; - + $memberstatic->need_subscription = $objp->subscription; + $memberstatic->datefin = $this->db->jdate($objp->date_end_subscription); if (!empty($objp->fk_soc)) { $memberstatic->socid = $objp->fk_soc; $memberstatic->fetch_thirdparty(); @@ -151,11 +154,12 @@ class box_members extends ModeleBoxes $line++; } - if ($num == 0) + if ($num == 0) { $this->info_box_contents[$line][0] = array( 'td' => 'class="center"', 'text'=>$langs->trans("NoRecordedCustomers"), ); + } $this->db->free($result); } else { diff --git a/htdocs/core/boxes/box_produits.php b/htdocs/core/boxes/box_produits.php index f36b0500655..44333683000 100644 --- a/htdocs/core/boxes/box_produits.php +++ b/htdocs/core/boxes/box_produits.php @@ -2,7 +2,7 @@ /* Copyright (C) 2003 Rodolphe Quiedeville * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2015 Frederic France + * Copyright (C) 2015-2021 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 @@ -196,7 +196,7 @@ class box_produits extends ModeleBoxes $this->info_box_contents[$line][] = array( 'td' => 'class="right" width="18"', - 'text' => ''.$productstatic->LibStatut($objp->tosell, 3, 0).'', + 'text' => ''.$productstatic->LibStatut($objp->tosell, 3, 0).'', 'asis' => 1 ); diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php index 893bb2273ab..0c6752ec764 100644 --- a/htdocs/core/boxes/box_produits_alerte_stock.php +++ b/htdocs/core/boxes/box_produits_alerte_stock.php @@ -3,7 +3,7 @@ * Copyright (C) 2004-2011 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2005-2012 Maxime Kohlhaas - * Copyright (C) 2015-2019 Frédéric France + * Copyright (C) 2015-2021 Frédéric France * Copyright (C) 2015 Juanjo Menent * * This program is free software; you can redistribute it and/or modify @@ -64,7 +64,7 @@ class box_produits_alerte_stock extends ModeleBoxes $this->db = $db; $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); - $tmpentry = array('enabled'=>((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && !empty($conf->stock->enabled)), 'perms'=>($user->rights->stock->lire), 'module'=>'product|service|stock'); + $tmpentry = array('enabled'=>((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && !empty($conf->stock->enabled)), 'perms'=>!empty($user->rights->stock->lire), 'module'=>'product|service|stock'); $showmode = isVisibleToUserType(($user->socid > 0 ? 1 : 0), $tmpentry, $listofmodulesforexternal); $this->hidden = ($showmode != 1); } @@ -206,23 +206,24 @@ class box_produits_alerte_stock extends ModeleBoxes $this->info_box_contents[$line][] = array( 'td' => 'class="right" width="18"', - 'text' => ''.$productstatic->LibStatut($objp->tosell, 3, 0).'', + 'text' => ''.$productstatic->LibStatut($objp->tosell, 3, 0).'', 'asis' => 1 ); $this->info_box_contents[$line][] = array( 'td' => 'class="right" width="18"', - 'text' => ''.$productstatic->LibStatut($objp->tobuy, 3, 0).'', + 'text' => ''.$productstatic->LibStatut($objp->tobuy, 3, 0).'', 'asis' => 1 ); $line++; } - if ($num == 0) + if ($num == 0) { $this->info_box_contents[$line][0] = array( 'td' => 'class="center"', 'text'=>$langs->trans("NoTooLowStockProducts"), ); + } $this->db->free($result); } else { diff --git a/htdocs/core/boxes/box_propales.php b/htdocs/core/boxes/box_propales.php index f98e0f1e347..6efd56c01db 100644 --- a/htdocs/core/boxes/box_propales.php +++ b/htdocs/core/boxes/box_propales.php @@ -81,7 +81,7 @@ class box_propales extends ModeleBoxes $propalstatic = new Propal($this->db); $societestatic = new Societe($this->db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."Propals", $max)); + $this->info_box_head = array('text' => $langs->trans("BoxTitleLast".(!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) ? "" : "Modified")."Propals", $max)); if ($user->rights->propale->lire) { @@ -96,7 +96,7 @@ class box_propales extends ModeleBoxes $sql .= " AND p.entity IN (".getEntity('propal').")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY p.datep DESC, p.ref DESC "; + if (!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE)) $sql .= " ORDER BY p.datep DESC, p.ref DESC "; else $sql .= " ORDER BY p.tms DESC, p.ref DESC "; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_shipments.php b/htdocs/core/boxes/box_shipments.php index 5a1f093ce87..22b28d42761 100644 --- a/htdocs/core/boxes/box_shipments.php +++ b/htdocs/core/boxes/box_shipments.php @@ -105,6 +105,7 @@ class box_shipments extends ModeleBoxes if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON e.fk_soc = sc.fk_soc"; $sql .= " WHERE e.entity IN (".getEntity('expedition').")"; if (!empty($conf->global->ORDER_BOX_LAST_SHIPMENTS_VALIDATED_ONLY)) $sql .= " AND e.fk_statut = 1"; + if ($user->socid > 0) $sql.= " AND s.rowid = ".$user->socid; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND sc.fk_user = ".$user->id; else $sql .= " ORDER BY e.date_delivery, e.ref DESC "; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_supplier_orders.php b/htdocs/core/boxes/box_supplier_orders.php index 151c1df6bcb..5074d403231 100644 --- a/htdocs/core/boxes/box_supplier_orders.php +++ b/htdocs/core/boxes/box_supplier_orders.php @@ -79,7 +79,7 @@ class box_supplier_orders extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; $thirdpartystatic = new Fournisseur($this->db); - $this->info_box_head = array('text' => $langs->trans("BoxTitleLatest".($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE ? "" : "Modified")."SupplierOrders", $max)); + $this->info_box_head = array('text' => $langs->trans("BoxTitleLatest".(!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) ? "" : "Modified")."SupplierOrders", $max)); if ($user->rights->fournisseur->commande->lire) { @@ -98,7 +98,7 @@ class box_supplier_orders extends ModeleBoxes $sql .= " AND c.entity IN (".getEntity('supplier_order').")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY c.date_commande DESC, c.ref DESC "; + if (!empty($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 .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php b/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php index 80fdbc2f4a2..22f669966f3 100644 --- a/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php +++ b/htdocs/core/boxes/box_supplier_orders_awaiting_reception.php @@ -99,7 +99,7 @@ class box_supplier_orders_awaiting_reception extends ModeleBoxes $sql .= " AND c.fk_statut IN (".CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.")"; if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - if ($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE) $sql .= " ORDER BY c.date_commande DESC, c.ref DESC"; + if (!empty($conf->global->MAIN_LASTBOX_ON_OBJECT_DATE)) $sql .= " ORDER BY c.date_commande DESC, c.ref DESC"; else $sql .= " ORDER BY c.date_livraison ASC, c.fk_statut ASC"; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index e96adea7531..0d235a21798 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -41,7 +41,10 @@ class CMailFile public $sendmode; public $sendsetup; - public $subject; // Topic: Subject of email + /** + * @var string Subject of email + */ + public $subject; public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '' or 'John Doe ' or ''). Note that with gmail smtps, value here is forced by google to account (but not the reply-to). // Sender: Who send the email ("Sender" has sent emails on behalf of "From"). // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain. @@ -148,7 +151,7 @@ class CMailFile // Add autocopy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO) && !preg_match('/'.preg_quote($conf->global->MAIN_MAIL_AUTOCOPY_TO, '/').'/i', $to)) { - $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; } $this->subject = $subject; @@ -161,7 +164,9 @@ class CMailFile $this->addr_cc = $addr_cc; $this->addr_bcc = $addr_bcc; $this->deliveryreceipt = $deliveryreceipt; - if (empty($replyto)) $replyto = $from; + if (empty($replyto)) { + $replyto = $from; + } $this->reply_to = $replyto; $this->errors_to = $errors_to; $this->trackid = $trackid; @@ -180,15 +185,18 @@ class CMailFile $this->sendmode = $smtpContextSendMode; } } - if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE; - if (empty($this->sendmode)) $this->sendmode = 'mail'; + if (empty($this->sendmode)) { + $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE; + } + if (empty($this->sendmode)) { + $this->sendmode = 'mail'; + } // We define end of line (RFC 821). $this->eol = "\r\n"; // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n). $this->eol2 = "\r\n"; - if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) - { + if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) { $this->eol = "\n"; $this->eol2 = "\n"; $moreinheader = str_replace("\r\n", "\n", $moreinheader); @@ -206,23 +214,22 @@ class CMailFile dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG); dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG); - if (empty($subject)) - { + if (empty($subject)) { dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject"); $this->error = 'ErrorSubjectIsRequired'; return; } - if (empty($msg)) - { + if (empty($msg)) { dol_syslog("CMailFile::CMailfile: Try to send an email with empty body"); $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure) } // Detect if message is HTML (use fast method) - if ($msgishtml == -1) - { + if ($msgishtml == -1) { $this->msgishtml = 0; - if (dol_textishtml($msg)) $this->msgishtml = 1; + if (dol_textishtml($msg)) { + $this->msgishtml = 1; + } } else { $this->msgishtml = $msgishtml; } @@ -237,26 +244,23 @@ class CMailFile // Replace relative /viewimage to absolute path $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1); - if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml = 1; // To force to send everything with content type html. + if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) { + $this->msgishtml = 1; // To force to send everything with content type html. + } // Detect images - if ($this->msgishtml) - { + if ($this->msgishtml) { $this->html = $msg; $findimg = 0; - if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) - { + if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) { $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias'); } // Define if there is at least one file - if ($findimg) - { - foreach ($this->html_images as $i => $val) - { - if ($this->html_images[$i]) - { + if ($findimg) { + foreach ($this->html_images as $i => $val) { + if ($this->html_images[$i]) { $this->atleastoneimage = 1; dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG); } @@ -265,12 +269,9 @@ class CMailFile } // Define if there is at least one file - if (is_array($filename_list)) - { - foreach ($filename_list as $i => $val) - { - if ($filename_list[$i]) - { + if (is_array($filename_list)) { + foreach ($filename_list as $i => $val) { + if ($filename_list[$i]) { $this->atleastonefile = 1; dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG); } @@ -279,7 +280,7 @@ class CMailFile // Add autocopy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO) && !preg_match('/'.preg_quote($conf->global->MAIN_MAIL_AUTOCOPY_TO, '/').'/i', $to)) { - $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; + $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO; } $this->addr_to = $to; @@ -292,8 +293,7 @@ class CMailFile $this->deliveryreceipt = $deliveryreceipt; $this->trackid = $trackid; - if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) - { + if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) { $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO; $this->addr_cc = ''; $this->addr_bcc = ''; @@ -311,8 +311,7 @@ class CMailFile // We set all data according to choosed sending method. // We also set a value for ->msgid - if ($this->sendmode == 'mail') - { + if ($this->sendmode == 'mail') { // Use mail php function (default PHP method) // ------------------------------------------ @@ -323,15 +322,15 @@ class CMailFile // Define smtp_headers (this also set ->msgid) $smtp_headers = $this->write_smtpheaders(); - if (!empty($moreinheader)) $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n + if (!empty($moreinheader)) { + $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n + } // Define mime_headers $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list); - if (!empty($this->html)) - { - if (!empty($css)) - { + if (!empty($this->html)) { + if (!empty($css)) { $this->css = $css; $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS } @@ -357,8 +356,7 @@ class CMailFile $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol; $this->message .= $text_body.$files_encoded; $this->message .= "--".$this->mixed_boundary."--".$this->eol; - } elseif ($this->sendmode == 'smtps') - { + } elseif ($this->sendmode == 'smtps') { // Use SMTPS library // ------------------------------------------ @@ -378,12 +376,12 @@ class CMailFile $smtps->setTrackId($this->trackid); $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1)); - if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader); + if (!empty($moreinheader)) { + $smtps->setMoreInHeader($moreinheader); + } - if (!empty($this->html)) - { - if (!empty($css)) - { + if (!empty($this->html)) { + if (!empty($css)) { $this->css = $css; $this->buildCSS(); } @@ -394,21 +392,20 @@ class CMailFile // Replace . alone on a new line with .. to avoid to have SMTP interpret this as end of message $msg = preg_replace('/(\r|\n)\.(\r|\n)/ims', '\1..\2', $msg); - if ($this->msgishtml) $smtps->setBodyContent($msg, 'html'); - else $smtps->setBodyContent($msg, 'plain'); + if ($this->msgishtml) { + $smtps->setBodyContent($msg, 'html'); + } else { + $smtps->setBodyContent($msg, 'plain'); + } - if ($this->atleastoneimage) - { - foreach ($this->images_encoded as $img) - { + if ($this->atleastoneimage) { + foreach ($this->images_encoded as $img) { $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']); } } - if (!empty($this->atleastonefile)) - { - foreach ($filename_list as $i => $val) - { + if (!empty($this->atleastonefile)) { + foreach ($filename_list as $i => $val) { $content = file_get_contents($filename_list[$i]); $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i]); } @@ -418,7 +415,9 @@ class CMailFile $smtps->setBCC($this->addr_bcc); $smtps->setErrorsTo($this->errors_to); $smtps->setDeliveryReceipt($this->deliveryreceipt); - if (!empty($conf->global->$keyforsslseflsigned)) $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true))); + if (!empty($conf->global->$keyforsslseflsigned)) { + $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true))); + } $host = dol_getprefix('email'); $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host; @@ -465,8 +464,7 @@ class CMailFile $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom); $adressEmailFrom = reset($adressEmailFrom); - if ($emailMatchs !== false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) - { + if ($emailMatchs !== false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) { $result = $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID); } else { $result = $this->message->setFrom($this->getArrayAddress($this->addr_from)); @@ -511,10 +509,8 @@ class CMailFile $msg = $this->checkIfHTML($msg); } - if ($this->atleastoneimage) - { - foreach ($this->images_encoded as $img) - { + if ($this->atleastoneimage) { + foreach ($this->images_encoded as $img) { //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid'] $attachment = Swift_Image::fromPath($img['fullpath']); // embed image @@ -534,10 +530,8 @@ class CMailFile $this->message->addPart(dol_nl2br($msg), 'text/html'); } - if (!empty($this->atleastonefile)) - { - foreach ($filename_list as $i => $val) - { + if (!empty($this->atleastonefile)) { + foreach ($filename_list as $i => $val) { //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i])); $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]); if (!empty($mimefilename_list[$i])) { @@ -547,10 +541,16 @@ class CMailFile } } - if (!empty($this->addr_cc)) $this->message->setCc($this->getArrayAddress($this->addr_cc)); - if (!empty($this->addr_bcc)) $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); + if (!empty($this->addr_cc)) { + $this->message->setCc($this->getArrayAddress($this->addr_cc)); + } + if (!empty($this->addr_bcc)) { + $this->message->setBcc($this->getArrayAddress($this->addr_bcc)); + } //if (! empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to)); - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); + if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) { + $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from)); + } } else { // Send mail method not correctly defined // -------------------------------------- @@ -573,29 +573,25 @@ class CMailFile $res = false; - if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) - { + if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) { require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; $hookmanager = new HookManager($db); $hookmanager->initHooks(array('mail')); $parameters = array(); $action = ''; $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { + if ($reshook < 0) { $this->error = "Error in hook maildao sendMail ".$reshook; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); return $reshook; } - if ($reshook == 1) // Hook replace standard code - { + if ($reshook == 1) { // Hook replace standard code return true; } $sendingmode = $this->sendmode; - if ($this->context == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') - { + if ($this->context == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') { // List of sending methods $listofmethods = array(); $listofmethods['mail'] = 'PHP mail function'; @@ -610,8 +606,7 @@ class CMailFile $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]); $this->error .= '
'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']); - if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) - { + if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) { $this->error .= '
'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS); } @@ -619,33 +614,37 @@ class CMailFile } // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) { + $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10; + } $tmparray1 = explode(',', $this->addr_to); - if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) - { + if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) { $this->error = 'Too much recipients in to:'; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) { + $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10; + } $tmparray2 = explode(',', $this->addr_cc); - if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) - { + if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) { $this->error = 'Too much recipients in cc:'; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10; + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) { + $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10; + } $tmparray3 = explode(',', $this->addr_bcc); - if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) - { + if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) { $this->error = 'Too much recipients in bcc:'; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; } - if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10; - if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) - { + if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) { + $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10; + } + if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) { $this->error = 'Too much recipients in to:, cc:, bcc:'; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING); return false; @@ -674,8 +673,7 @@ class CMailFile } // Action according to choosed sending method - if ($this->sendmode == 'mail') - { + if ($this->sendmode == 'mail') { // Use mail php function (default PHP method) // ------------------------------------------ dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG); @@ -683,59 +681,67 @@ class CMailFile //dol_syslog("CMailFile::sendfile message=\n".$message); // If Windows, sendmail_from must be defined - if (isset($_SERVER["WINDIR"])) - { - if (empty($this->addr_from)) $this->addr_from = 'robot@example.com'; + if (isset($_SERVER["WINDIR"])) { + if (empty($this->addr_from)) { + $this->addr_from = 'robot@example.com'; + } @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2)); } // Force parameters //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".$conf->global->$keyforsmtpserver." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG); - if (!empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver); - if (!empty($conf->global->$keyforsmtpport)) ini_set('smtp_port', $conf->global->$keyforsmtpport); + if (!empty($conf->global->$keyforsmtpserver)) { + ini_set('SMTP', $conf->global->$keyforsmtpserver); + } + if (!empty($conf->global->$keyforsmtpport)) { + ini_set('smtp_port', $conf->global->$keyforsmtpport); + } $res = true; - if ($res && !$this->subject) - { + if ($res && !$this->subject) { $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
Subject is empty"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } $dest = $this->getValidAddress($this->addr_to, 2); - if ($res && !$dest) - { + if ($res && !$dest) { $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."
Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } - if ($res) - { + if ($res) { $additionnalparam = ''; // By default - if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) - { + if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) { // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie. // Having this variable defined may create problems with some sendmail (option -f refused) // Having this variable not defined may create problems with some other sendmail (option -f required) $additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : '')); } - if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender - { + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) { // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba'; } - if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) { + $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params + } $linuxlike = 1; - if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0; - if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0; + if (preg_match('/^win/i', PHP_OS)) { + $linuxlike = 0; + } + if (preg_match('/^mac/i', PHP_OS)) { + $linuxlike = 0; + } dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG); $this->message = stripslashes($this->message); - if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + $this->dump_mail(); + } // Encode subject if required. $subjecttouse = $this->subject; @@ -743,11 +749,13 @@ class CMailFile $subjecttouse = $this->encodetorfc2822($subjecttouse); } - if (!empty($additionnalparam)) $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam); - else $res = mail($dest, $subjecttouse, $this->message, $this->headers); + if (!empty($additionnalparam)) { + $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam); + } else { + $res = mail($dest, $subjecttouse, $this->message, $this->headers); + } - if (!$res) - { + if (!$res) { $langs->load("errors"); $this->error = "Failed to send mail with php mail"; if (!$linuxlike) { @@ -761,18 +769,19 @@ class CMailFile } } - if (isset($_SERVER["WINDIR"])) - { + if (isset($_SERVER["WINDIR"])) { @ini_restore('sendmail_from'); } // Restore parameters - if (!empty($conf->global->$keyforsmtpserver)) ini_restore('SMTP'); - if (!empty($conf->global->$keyforsmtpport)) ini_restore('smtp_port'); - } elseif ($this->sendmode == 'smtps') - { - if (!is_object($this->smtps)) - { + if (!empty($conf->global->$keyforsmtpserver)) { + ini_restore('SMTP'); + } + if (!empty($conf->global->$keyforsmtpport)) { + ini_restore('smtp_port'); + } + } elseif ($this->sendmode == 'smtps') { + if (!is_object($this->smtps)) { $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."
Constructor of object CMailFile was not initialized without errors."; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); return false; @@ -783,14 +792,22 @@ class CMailFile $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library // Clean parameters - if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); - if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); + if (empty($conf->global->$keyforsmtpserver)) { + $conf->global->$keyforsmtpserver = ini_get('SMTP'); + } + if (empty($conf->global->$keyforsmtpport)) { + $conf->global->$keyforsmtpport = ini_get('smtp_port'); + } // If we use SSL/TLS $server = $conf->global->$keyforsmtpserver; $secure = ''; - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; - if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { + $secure = 'ssl'; + } + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) { + $secure = 'tls'; + } $server = ($secure ? $secure.'://' : '').$server; $port = $conf->global->$keyforsmtpport; @@ -799,74 +816,87 @@ class CMailFile $this->smtps->setPort($port); // 25, 465...; $loginid = ''; $loginpass = ''; - if (!empty($conf->global->$keyforsmtpid)) - { + if (!empty($conf->global->$keyforsmtpid)) { $loginid = $conf->global->$keyforsmtpid; $this->smtps->setID($loginid); } - if (!empty($conf->global->$keyforsmtppw)) - { + if (!empty($conf->global->$keyforsmtppw)) { $loginpass = $conf->global->$keyforsmtppw; $this->smtps->setPW($loginpass); } $res = true; $from = $this->smtps->getFrom('org'); - if ($res && !$from) - { + if ($res && !$from) { $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Sender address '$from' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } $dest = $this->smtps->getTo(); - if ($res && !$dest) - { + if ($res && !$dest) { $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Recipient address '$dest' invalid"; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); $res = false; } - if ($res) - { - if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true); + if ($res) { + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + $this->smtps->setDebug(true); + } $result = $this->smtps->sendMsg(); //print $result; - if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + $this->dump_mail(); + } $result = $this->smtps->getErrors(); - if (empty($this->error) && empty($result)) - { + if (empty($this->error) && empty($result)) { dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG); $res = true; } else { - if (empty($this->error)) $this->error = $result; + if (empty($this->error)) { + $this->error = $result; + } dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - ".$this->error, LOG_ERR); $res = false; } } - } elseif ($this->sendmode == 'swiftmailer') - { + } elseif ($this->sendmode == 'swiftmailer') { // Use Swift Mailer library // ------------------------------------------ require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php'; // Clean parameters - if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP'); - if (empty($conf->global->$keyforsmtpport)) $conf->global->$keyforsmtpport = ini_get('smtp_port'); + if (empty($conf->global->$keyforsmtpserver)) { + $conf->global->$keyforsmtpserver = ini_get('SMTP'); + } + if (empty($conf->global->$keyforsmtpport)) { + $conf->global->$keyforsmtpport = ini_get('smtp_port'); + } // If we use SSL/TLS $server = $conf->global->$keyforsmtpserver; $secure = ''; - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl'; - if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls'; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { + $secure = 'ssl'; + } + if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) { + $secure = 'tls'; + } $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); - if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid); - if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw); - if (!empty($conf->global->$keyforsslseflsigned)) $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false))); + if (!empty($conf->global->$keyforsmtpid)) { + $this->transport->setUsername($conf->global->$keyforsmtpid); + } + if (!empty($conf->global->$keyforsmtppw)) { + $this->transport->setPassword($conf->global->$keyforsmtppw); + } + if (!empty($conf->global->$keyforsslseflsigned)) { + $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false))); + } //$smtps->_msgReplyTo = 'reply@web.com'; // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable @@ -898,7 +928,9 @@ class CMailFile } catch (Exception $e) { $this->error = $e->getMessage(); } - if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail(); + if (!empty($conf->global->MAIN_MAIL_DEBUG)) { + $this->dump_mail(); + } $res = true; if (!empty($this->error) || !$result) { @@ -916,8 +948,7 @@ class CMailFile $parameters = array(); $action = ''; $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { + if ($reshook < 0) { $this->error = "Error in hook maildao sendMailAfter ".$reshook; dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR); @@ -1014,9 +1045,13 @@ class CMailFile { if (!preg_match('/^[\s\t]*styleCSS)) $out .= $this->styleCSS; + if (!empty($this->styleCSS)) { + $out .= $this->styleCSS; + } $out .= "bodyCSS)) $out .= $this->bodyCSS; + if (!empty($this->bodyCSS)) { + $out .= $this->bodyCSS; + } $out .= ">"; $out .= $msg; $out .= ""; @@ -1070,29 +1105,37 @@ class CMailFile // Sender //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2; $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2; - if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) - { + if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) { $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; + 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; + } // Receiver - if (isset($this->addr_cc) && $this->addr_cc) $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; - if (isset($this->addr_bcc) && $this->addr_bcc) $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? + if (isset($this->addr_cc) && $this->addr_cc) { + $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2; + } + if (isset($this->addr_bcc) && $this->addr_bcc) { + $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ? + } // Delivery receipt - if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; + if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) { + $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2; + } //$out.= "X-Priority: 3".$this->eol2; $out .= 'Date: '.date("r").$this->eol2; $trackid = $this->trackid; - if ($trackid) - { + if ($trackid) { // References is kept in response and Message-ID is returned into In-Reply-To: $this->msgid = time().'.phpmail-dolibarr-'.$trackid.'@'.$host; $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail @@ -1103,7 +1146,9 @@ class CMailFile $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; } - if (!empty($_SERVER['REMOTE_ADDR'])) $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2; + if (!empty($_SERVER['REMOTE_ADDR'])) { + $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2; + } $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2; $out .= "Mime-Version: 1.0".$this->eol2; @@ -1131,14 +1176,13 @@ class CMailFile $mimedone = 0; $out = ""; - if (is_array($filename_list)) - { + if (is_array($filename_list)) { $filename_list_size = count($filename_list); - for ($i = 0; $i < $filename_list_size; $i++) - { - if ($filename_list[$i]) - { - if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; + for ($i = 0; $i < $filename_list_size; $i++) { + if ($filename_list[$i]) { + if ($mimefilename_list[$i]) { + $filename_list[$i] = $mimefilename_list[$i]; + } $out .= "X-attachments: $filename_list[$i]".$this->eol2; } } @@ -1164,8 +1208,7 @@ class CMailFile $out .= "--".$this->mixed_boundary.$this->eol; - if ($this->atleastoneimage) - { + if ($this->atleastoneimage) { $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out .= $this->eol; $out .= "--".$this->alternative_boundary.$this->eol; @@ -1173,14 +1216,12 @@ class CMailFile // Make RFC821 Compliant, replace bare linefeeds $strContent = preg_replace("/(?global->MAIN_FIX_FOR_BUGGED_MTA)) - { + if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) { $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars } $strContentAltText = ''; - if ($this->msgishtml) - { + if ($this->msgishtml) { // Similar code to forge a text from html is also in smtps.class.php $strContentAltText = preg_replace("/]*>/", " ", $strContent); $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); @@ -1195,10 +1236,8 @@ class CMailFile // TODO Encode main content into base64 and use the chunk_split, or quoted-printable $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content. - if ($this->msgishtml) - { - if ($this->atleastoneimage) - { + if ($this->msgishtml) { + if ($this->atleastoneimage) { $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol; //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message @@ -1208,8 +1247,7 @@ class CMailFile $out .= "--".$this->related_boundary.$this->eol; } - if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part - { + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part before html part $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol; $out .= $this->eol; $out .= "--".$this->alternative_boundary.$this->eol; @@ -1223,8 +1261,7 @@ class CMailFile //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64 $out .= $this->eol.$strContent.$this->eol; - if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part - { + if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part after html part $out .= "--".$this->alternative_boundary."--".$this->eol; } } else { @@ -1236,8 +1273,7 @@ class CMailFile $out .= $this->eol; // Encode images - if ($this->atleastoneimage) - { + if ($this->atleastoneimage) { $out .= $this->write_images($this->images_encoded); // always end related and end alternative after inline images $out .= "--".$this->related_boundary."--".$this->eol; @@ -1263,15 +1299,14 @@ class CMailFile $out = ''; $filename_list_size = count($filename_list); - for ($i = 0; $i < $filename_list_size; $i++) - { - if ($filename_list[$i]) - { + for ($i = 0; $i < $filename_list_size; $i++) { + if ($filename_list[$i]) { dol_syslog("CMailFile::write_files: i=$i"); $encoded = $this->_encode_file($filename_list[$i]); - if ($encoded >= 0) - { - if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i]; + if ($encoded >= 0) { + if ($mimefilename_list[$i]) { + $filename_list[$i] = $mimefilename_list[$i]; + } if (!$mimetype_list[$i]) { $mimetype_list[$i] = "application/octet-stream"; } @@ -1307,10 +1342,8 @@ class CMailFile // phpcs:enable $out = ''; - if (is_array($images_list)) - { - foreach ($images_list as $img) - { + if (is_array($images_list)) { + foreach ($images_list as $img) { dol_syslog("CMailFile::write_images: ".$img["name"]); $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image @@ -1344,16 +1377,14 @@ class CMailFile $_retVal = 0; $timeout = 5; // Timeout in seconds - if (function_exists('fsockopen')) - { + if (function_exists('fsockopen')) { $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER'; $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT'; $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID'; $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW'; $keyfortls = 'MAIN_MAIL_EMAIL_TLS'; $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS'; - if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') - { + if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING'; $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_EMAILING'; $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_EMAILING'; @@ -1363,26 +1394,32 @@ class CMailFile } // If we use SSL/TLS - if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host = 'ssl://'.$host; + if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { + $host = 'ssl://'.$host; + } // tls smtp start with no encryption //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host; dol_syslog("Try socket connection to host=".$host." port=".$port); //See if we can connect to the SMTP server if ($socket = @fsockopen( - $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. - $port, // which Port number to use - $errno, // actual system level error - $errstr, // and any text that goes with the error - $timeout // timeout for reading/writing data over the socket + $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS. + $port, // which Port number to use + $errno, // actual system level error + $errstr, // and any text that goes with the error + $timeout // timeout for reading/writing data over the socket )) { // Windows still does not have support for this timeout function - if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0); + if (function_exists('stream_set_timeout')) { + stream_set_timeout($socket, $timeout, 0); + } dol_syslog("Now we wait for answer 220"); // Check response from Server - if ($_retVal = $this->server_parse($socket, "220")) $_retVal = $socket; + if ($_retVal = $this->server_parse($socket, "220")) { + $_retVal = $socket; + } } else { $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr); } @@ -1405,17 +1442,14 @@ class CMailFile $_retVal = true; // Indicates if Object was created or not $server_response = ''; - while (substr($server_response, 3, 1) != ' ') - { - if (!($server_response = fgets($socket, 256))) - { + while (substr($server_response, 3, 1) != ' ') { + if (!($server_response = fgets($socket, 256))) { $this->error = "Couldn't get mail server response codes"; return false; } } - if (!(substr($server_response, 0, 3) == $response)) - { + if (!(substr($server_response, 0, 3) == $response)) { $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response"; $_retVal = false; } @@ -1437,17 +1471,13 @@ class CMailFile $matches = array(); preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found - if (!empty($matches)) - { + if (!empty($matches)) { $i = 0; - foreach ($matches[1] as $full) - { - if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) // If xxx is 'file=aaa' - { + foreach ($matches[1] as $full) { + if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa' $img = $regs[1]; - if (file_exists($images_dir.'/'.$img)) - { + if (file_exists($images_dir.'/'.$img)) { // Image path in src $src = preg_quote($full, '/'); @@ -1458,8 +1488,7 @@ class CMailFile $this->html_images[$i]["name"] = $img; // Content type - if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg)) - { + if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg)) { $ext = strtolower($reg[1]); $this->html_images[$i]["content_type"] = $this->image_types[$ext]; } @@ -1472,22 +1501,18 @@ class CMailFile } } - if (!empty($this->html_images)) - { + if (!empty($this->html_images)) { $inline = array(); $i = 0; - foreach ($this->html_images as $img) - { + foreach ($this->html_images as $img) { $fullpath = $images_dir.'/'.$img["name"]; // If duplicate images are embedded, they may show up as attachments, so remove them. - if (!in_array($fullpath, $inline)) - { + if (!in_array($fullpath, $inline)) { // Read image file - if ($image = file_get_contents($fullpath)) - { + if ($image = file_get_contents($fullpath)) { // On garde que le nom de l'image preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs); $imgName = $regs[1]; @@ -1538,11 +1563,9 @@ class CMailFile // Boucle sur chaque composant de l'adresse $i = 0; - foreach ($arrayaddress as $val) - { + foreach ($arrayaddress as $val) { $regs = array(); - if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) - { + if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { $name = trim($regs[1]); $email = trim($regs[2]); } else { @@ -1550,8 +1573,7 @@ class CMailFile $email = trim($val); } - if ($email) - { + if ($email) { $i++; $newemail = ''; @@ -1559,31 +1581,32 @@ class CMailFile $newemail = $name ? $name : $email; $newemail = ''.$newemail.''; } - if ($format == 4) - { + if ($format == 4) { $newemail = $name ? $name : $email; } - if ($format == 2) - { + if ($format == 2) { $newemail = $email; } - if ($format == 1 || $format == 3) - { + if ($format == 1 || $format == 3) { $newemail = '<'.$email.'>'; } - if ($format == 0 || $format == 3) - { - if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail = '<'.$email.'>'; - elseif (!$name) $newemail = '<'.$email.'>'; - else $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>'; + if ($format == 0 || $format == 3) { + if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) { + $newemail = '<'.$email.'>'; + } elseif (!$name) { + $newemail = '<'.$email.'>'; + } else { + $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>'; + } } $ret = ($ret ? $ret.',' : '').$newemail; // Stop if we have too much records - if ($maxnumberofemail && $i >= $maxnumberofemail) - { - if (count($arrayaddress) > $maxnumberofemail) $ret .= '...'; + if ($maxnumberofemail && $i >= $maxnumberofemail) { + if (count($arrayaddress) > $maxnumberofemail) { + $ret .= '...'; + } break; } } @@ -1608,10 +1631,8 @@ class CMailFile $arrayaddress = explode(',', $address); // Boucle sur chaque composant de l'adresse - foreach ($arrayaddress as $val) - { - if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) - { + foreach ($arrayaddress as $val) { + if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) { $name = trim($regs[1]); $email = trim($regs[2]); } else { diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 03a5154f23f..2340657ef4e 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -55,6 +55,11 @@ abstract class CommonDocGenerator */ public $extrafieldsCache; + /** + * @var int If set to 1, save the fullname of generated file with path as the main doc when generating a doc with this template. + */ + public $update_main_doc_field; + /** * Constructor * diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index 6afca0c8d35..cc67030ccf6 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -14,6 +14,7 @@ * Copyright (C) 2017 Rui Strecht * Copyright (C) 2018-2020 Frédéric France * Copyright (C) 2018 Josep Lluís Amador + * Copyright (C) 2021 Gauthier VERDOL * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -221,6 +222,12 @@ abstract class CommonObject */ public $statut; + /** + * @var int The object's status + * @see setStatut() + */ + public $status; + /** * @var string * @see getFullAddress() @@ -348,6 +355,13 @@ abstract class CommonObject */ public $model_pdf; + /** + * @var string + * @deprecated + * @see model_pdf + */ + public $modelpdf; + /** * @var string * Contains relative path of last generated main file @@ -601,7 +615,7 @@ abstract class CommonObject if (empty($lastname)) $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : ''))))); $ret = ''; - if ($option && $this->civility_code) + if (!empty($option) && !empty($this->civility_code)) { if ($langs->transnoentitiesnoconv("Civility".$this->civility_code) != "Civility".$this->civility_code) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_code).' '; else $ret .= $this->civility_code.' '; @@ -720,7 +734,7 @@ abstract class CommonObject $out = ''; $outdone = 0; - $coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT); + $coords = $this->getFullAddress(1, ', ', (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) ? $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT : 0)); if ($coords) { if (!empty($conf->use_javascript_ajax)) @@ -956,7 +970,7 @@ abstract class CommonObject * @param int|string $type_contact Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL * @param string $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 + * @return int <0 if KO, 0 if already added, >0 if OK */ public function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0) { @@ -1054,7 +1068,6 @@ abstract class CommonObject { $this->error = $this->db->errno(); $this->db->rollback(); - echo 'err rollback'; return -2; } else { $this->error = $this->db->error(); @@ -1062,7 +1075,9 @@ abstract class CommonObject return -1; } } - } else return 0; + } else { + return 0; + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -1407,7 +1422,7 @@ abstract class CommonObject } elseif (strpos($obj->element, 'supplier') !== false && $obj->element != 'supplier_proposal') { $modulename = 'fournisseur'; } - if ($conf->{$modulename}->enabled) { + if (!empty($conf->{$modulename}->enabled)) { $libelle_element = $langs->trans('ContactDefault_'.$obj->element); $transkey = "TypeContact_".$obj->element."_".$source."_".$obj->code; $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle); @@ -2065,6 +2080,7 @@ abstract class CommonObject $fieldname = 'fk_mode_reglement'; if ($this->element == 'societe') $fieldname = 'mode_reglement'; if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier'; + if (get_class($this) == 'Tva') $fieldname = 'fk_typepayment'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(($id > 0 || $id == '0') ? $id : 'NULL'); @@ -3257,14 +3273,18 @@ abstract class CommonObject * * @param string $origin Linked element type * @param int $origin_id Linked element id + * @param User $f_user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int <=0 if KO, >0 if OK * @see fetchObjectLinked(), updateObjectLinked(), deleteObjectLinked() */ - public function add_object_linked($origin = null, $origin_id = null) + public function add_object_linked($origin = null, $origin_id = null, $f_user = null, $notrigger = 0) { // phpcs:enable + global $user; $origin = (!empty($origin) ? $origin : $this->origin); $origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id); + $f_user = isset($f_user) ? $f_user : $user; // Special case if ($origin == 'order') $origin = 'commande'; @@ -3272,26 +3292,41 @@ abstract class CommonObject if ($origin == 'invoice_template') $origin = 'facturerec'; if ($origin == 'supplierorder') $origin = 'order_supplier'; $this->db->begin(); + $error = 0; - $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; + $sql = "INSERT INTO " . MAIN_DB_PREFIX . "element_element ("; $sql .= "fk_source"; $sql .= ", sourcetype"; $sql .= ", fk_target"; $sql .= ", targettype"; $sql .= ") VALUES ("; $sql .= $origin_id; - $sql .= ", '".$this->db->escape($origin)."'"; - $sql .= ", ".$this->id; - $sql .= ", '".$this->db->escape($this->element)."'"; + $sql .= ", '" . $this->db->escape($origin) . "'"; + $sql .= ", " . $this->id; + $sql .= ", '" . $this->db->escape($this->element) . "'"; $sql .= ")"; - dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG); - if ($this->db->query($sql)) - { + dol_syslog(get_class($this) . "::add_object_linked", LOG_DEBUG); + if ($this->db->query($sql)) { + if (!$notrigger) { + // Call trigger + $this->context['link_origin'] = $origin; + $this->context['link_origin_id'] = $origin_id; + $result = $this->call_trigger('OBJECT_LINK_INSERT', $f_user); + if ($result < 0) { + $error++; + } + // End call triggers + } + } else { + $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error) { $this->db->commit(); return 1; } else { - $this->error = $this->db->lasterror(); $this->db->rollback(); return 0; } @@ -3502,38 +3537,61 @@ abstract class CommonObject * @param string $sourcetype Object source type * @param int $targetid Object target id * @param string $targettype Object target type + * @param User $f_user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 if OK, <0 if KO * @see add_object_linked(), fetObjectLinked(), deleteObjectLinked() */ - public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '') + public function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $f_user = null, $notrigger = 0) { + global $user; $updatesource = false; $updatetarget = false; + $f_user = isset($f_user) ? $f_user : $user; if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true; elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true; - $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET "; - if ($updatesource) - { - $sql .= "fk_source = ".$sourceid; - $sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql .= " WHERE fk_target = ".$this->id; - $sql .= " AND targettype = '".$this->db->escape($this->element)."'"; - } elseif ($updatetarget) - { - $sql .= "fk_target = ".$targetid; - $sql .= ", targettype = '".$this->db->escape($targettype)."'"; - $sql .= " WHERE fk_source = ".$this->id; - $sql .= " AND sourcetype = '".$this->db->escape($this->element)."'"; + $this->db->begin(); + $error = 0; + + $sql = "UPDATE " . MAIN_DB_PREFIX . "element_element SET "; + if ($updatesource) { + $sql .= "fk_source = " . $sourceid; + $sql .= ", sourcetype = '" . $this->db->escape($sourcetype) . "'"; + $sql .= " WHERE fk_target = " . $this->id; + $sql .= " AND targettype = '" . $this->db->escape($this->element) . "'"; + } elseif ($updatetarget) { + $sql .= "fk_target = " . $targetid; + $sql .= ", targettype = '" . $this->db->escape($targettype) . "'"; + $sql .= " WHERE fk_source = " . $this->id; + $sql .= " AND sourcetype = '" . $this->db->escape($this->element) . "'"; } - dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { - return 1; + dol_syslog(get_class($this) . "::updateObjectLinked", LOG_DEBUG); + if ($this->db->query($sql)) { + if (!$notrigger) { + // Call trigger + $this->context['link_source_id'] = $sourceid; + $this->context['link_source_type'] = $sourcetype; + $this->context['link_target_id'] = $targetid; + $this->context['link_target_type'] = $targettype; + $result = $this->call_trigger('OBJECT_LINK_UPDATE', $f_user); + if ($result < 0) { + $error++; + } + // End call triggers + } } else { $this->error = $this->db->lasterror(); + $error++; + } + + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); return -1; } } @@ -3546,13 +3604,17 @@ abstract class CommonObject * @param int $targetid Object target id * @param string $targettype Object target type * @param int $rowid Row id of line to delete. If defined, other parameters are not used. + * @param User $f_user User that create + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @return int >0 if OK, <0 if KO * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked() */ - public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '') + public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0) { + global $user; $deletesource = false; $deletetarget = false; + $f_user = isset($f_user) ? $f_user : $user; if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true; elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true; @@ -3561,37 +3623,113 @@ abstract class CommonObject $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element); $targetid = (!empty($targetid) ? $targetid : $this->id); $targettype = (!empty($targettype) ? $targettype : $this->element); + $this->db->begin(); + $error = 0; - $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element"; - $sql .= " WHERE"; - if ($rowid > 0) - { - $sql .= " rowid = ".$rowid; - } else { - if ($deletesource) - { - $sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'"; - $sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'"; - } elseif ($deletetarget) - { - $sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'"; - $sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'"; + if (!$notrigger) { + // Call trigger + $this->context['link_id'] = $rowid; + $this->context['link_source_id'] = $sourceid; + $this->context['link_source_type'] = $sourcetype; + $this->context['link_target_id'] = $targetid; + $this->context['link_target_type'] = $targettype; + $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user); + if ($result < 0) { + $error++; + } + // End call triggers + } + + if (!$error) { + $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element"; + $sql .= " WHERE"; + if ($rowid > 0) { + $sql .= " rowid = " . $rowid; } else { - $sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')"; - $sql .= " OR"; - $sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')"; + if ($deletesource) { + $sql .= " fk_source = " . $sourceid . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'"; + $sql .= " AND fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "'"; + } elseif ($deletetarget) { + $sql .= " fk_target = " . $targetid . " AND targettype = '" . $this->db->escape($targettype) . "'"; + $sql .= " AND fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "'"; + } else { + $sql .= " (fk_source = " . $this->id . " AND sourcetype = '" . $this->db->escape($this->element) . "')"; + $sql .= " OR"; + $sql .= " (fk_target = " . $this->id . " AND targettype = '" . $this->db->escape($this->element) . "')"; + } + } + + dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG); + if (!$this->db->query($sql)) { + $this->error = $this->db->lasterror(); + $this->errors[] = $this->error; + $error++; } } - dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG); - if ($this->db->query($sql)) - { + if (!$error) { + $this->db->commit(); return 1; } else { - $this->error = $this->db->lasterror(); - $this->errors[] = $this->error; + $this->db->rollback(); + return 0; + } + } + + /** + * Function used to get an array with all items linked to an object id in association table + * + * @param int $fk_object_where id of object we need to get linked items + * @param string $field_select name of field we need to get a list + * @param string $field_where name of field of object we need to get linked items + * @param string $table_element name of association table + * @return array Array of record + */ + static public function getAllItemsLinkedByObjectID($fk_object_where, $field_select, $field_where, $table_element) + { + if (empty($fk_object_where) || empty($field_where) || empty($table_element)) { return -1; } + + global $db; + + $sql = 'SELECT '.$field_select.' FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.((int) $fk_object_where); + $resql = $db->query($sql); + + $TRes = array(); + if (!empty($resql)) { + while ($res = $db->fetch_object($resql)) { + $TRes[] = $res->{$field_select}; + } + } + + return $TRes; + } + + /** + * Function used to remove all items linked to an object id in association table + * + * @param int $fk_object_where id of object we need to remove linked items + * @param string $field_where name of field of object we need to delete linked items + * @param string $table_element name of association table + * @return int <0 if KO, 0 if nothing done, >0 if OK and something done + */ + static public function deleteAllItemsLinkedByObjectID($fk_object_where, $field_where, $table_element) + { + if (empty($fk_object_where) || empty($field_where) || empty($table_element)) { + return -1; + } + + global $db; + + $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table_element.' WHERE '.$field_where.' = '.$fk_object_where; + $resql = $db->query($sql); + + if (empty($resql)) { + return 0; + } + + return 1; } /** @@ -4786,7 +4924,7 @@ abstract class CommonObject $this->result['filename']=$ecmfile->filename;*/ //var_dump($obj->update_main_doc_field);exit; - // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set) + // Update the last_main_doc field into main object (if document generator has property ->update_main_doc_field set) $update_main_doc_field = 0; if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1; if ($update_main_doc_field && !empty($this->table_element)) @@ -5305,6 +5443,7 @@ abstract class CommonObject $mandatorypb = false; if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true; if ($this->array_options[$key] === '') $mandatorypb = true; + if ($attributeType == 'sellist' && $this->array_options[$key] == '0') $mandatorypb = true; if ($mandatorypb) { dol_syslog("Mandatory extra field ".$key." is empty"); @@ -5881,8 +6020,14 @@ abstract class CommonObject } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) { $param['options'] = array($reg[2].':'.$reg[3] => 'N'); $type = 'link'; - } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { - $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4].':'.$reg[5] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3].':'.$reg[4] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[2].':'.$reg[3] => 'N'); $type = 'sellist'; } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) { $param['options'] = array(); @@ -5913,8 +6058,7 @@ abstract class CommonObject $objectid = $this->id; - if ($computed) - { + if ($computed) { if (!preg_match('/^search_/', $keyprefix)) return ''.$langs->trans("AutomaticallyCalculated").''; else return ''; } @@ -5923,26 +6067,20 @@ abstract class CommonObject if (empty($morecss) && !empty($val['css'])) { $morecss = $val['css']; } elseif (empty($morecss)) { - if ($type == 'date') - { + if ($type == 'date') { $morecss = 'minwidth100imp'; - } elseif ($type == 'datetime' || $type == 'link') // link means an foreign key to another primary id - { + } elseif ($type == 'datetime' || $type == 'link') { // link means an foreign key to another primary id $morecss = 'minwidth200imp'; - } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) - { + } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) { $morecss = 'maxwidth75'; } elseif ($type == 'url') { $morecss = 'minwidth400'; - } elseif ($type == 'boolean') - { + } elseif ($type == 'boolean') { $morecss = ''; } else { - if (round($size) < 12) - { + if (round($size) < 12) { $morecss = 'minwidth100'; - } elseif (round($size) <= 48) - { + } elseif (round($size) <= 48) { $morecss = 'minwidth200'; } else { $morecss = 'minwidth400'; @@ -6049,24 +6187,20 @@ abstract class CommonObject $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid'); - if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) - { - if (strpos($InfoFieldList[4], 'extra.') !== false) - { + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { + if (strpos($InfoFieldList[4], 'extra.') !== false) { $keyList = 'main.'.$InfoFieldList[2].' as rowid'; } else { $keyList = $InfoFieldList[2].' as rowid'; } } - if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) - { + if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) { list($parentName, $parentField) = explode('|', $InfoFieldList[3]); $keyList .= ', '.$parentField; } $fields_label = explode('|', $InfoFieldList[1]); - if (is_array($fields_label)) - { + if (is_array($fields_label)) { $keyList .= ', '; $keyList .= implode(', ', $fields_label); } @@ -6343,13 +6477,13 @@ abstract class CommonObject if (!preg_match('/search_/', $keyprefix)) { if (!empty($param_list_array[2])) { // If the entry into $fields is set to add a create button - if ($this->fields[$key]['picto']) { + if (!empty($this->fields[$key]['picto'])) { $morecss .= ' widthcentpercentminusxx'; } else { $morecss .= ' widthcentpercentminusx'; } } else { - if ($this->fields[$key]['picto']) { + if (!empty($this->fields[$key]['picto'])) { $morecss .= ' widthcentpercentminusx'; } } @@ -6461,13 +6595,18 @@ abstract class CommonObject $param['options'] = array(); if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval']; - if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) - { + if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) { $type = 'link'; $param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]); } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) { $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N'); $type = 'sellist'; + } elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N'); + $type = 'sellist'; + } elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) { + $param['options'] = array($reg[1].':'.$reg[2] => 'N'); + $type = 'sellist'; } $langfile = $val['langfile']; @@ -6558,8 +6697,7 @@ abstract class CommonObject $selectkey = "rowid"; $keyList = 'rowid'; - if (count($InfoFieldList) >= 3) - { + if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) { $selectkey = $InfoFieldList[2]; $keyList = $InfoFieldList[2].' as rowid'; } @@ -6753,9 +6891,10 @@ abstract class CommonObject * @param string $keysuffix Suffix string to add after name and id of field (can be used to avoid duplicate names) * @param string $keyprefix Prefix string to add before name and id of field (can be used to avoid duplicate names) * @param string $onetrtd All fields in same tr td. Used by objectline_create.tpl.php for example. + * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...) * @return string */ - public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0) + public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card') { global $db, $conf, $langs, $action, $form, $hookmanager; @@ -6810,7 +6949,7 @@ abstract class CommonObject } $colspan = ''; - if (is_array($params) && count($params) > 0) { + if (is_array($params) && count($params) > 0 && $display_type=='card') { if (array_key_exists('cols', $params)) { $colspan = $params['cols']; } elseif (array_key_exists('colspan', $params)) { // For backward compatibility. Use cols instead now. @@ -6846,7 +6985,7 @@ abstract class CommonObject $value = $getposttemp; } } else { - $value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object. + $value = (!empty($this->array_options["options_".$key]) ? $this->array_options["options_".$key] : ''); // No GET, no POST, no default value, so we take value of object. } //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value); break; @@ -6869,7 +7008,7 @@ abstract class CommonObject } } - $out .= $extrafields->showSeparator($key, $this, ($colspan + 1)); + $out .= $extrafields->showSeparator($key, $this, ($colspan + 1), $display_type); } else { $class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : ''); $csstyle = ''; @@ -6888,10 +7027,11 @@ abstract class CommonObject $domData .= ' data-targetid="'.$this->id.'"'; $html_id = (empty($this->id) ? '' : 'extrarow-'.$this->element.'_'.$key.'_'.$this->id); + if ($display_type=='card') { + if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; } - if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; } - - if ($action == 'selectlines') { $colspan++; } + if ($action == 'selectlines') { $colspan++; } + } // Convert date into timestamp format (value in memory must be a timestamp) if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime'))) @@ -6918,11 +7058,13 @@ abstract class CommonObject $labeltoshow = $langs->trans($label); $helptoshow = $langs->trans($extrafields->attributes[$this->table_element]['help'][$key]); - $out .= ''; - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER) && $action == 'view') { - $out .= ''; + if ($display_type == 'card') { + $out .= ''; + $out .= ''; + $out .= '
attributes[$this->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $helptoshow); else $out .= $labeltoshow; } - $out .= ''; + + $out .= ($display_type == 'card' ? '' : '
'); $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : ''; - - $out .= ''; + if ($display_type == 'card') { + $out .= ''; + } elseif ($display_type == 'line') { + $out .= '
'; + } switch ($mode) { case "view": @@ -6956,15 +7102,18 @@ abstract class CommonObject break; } - $out .= ''; + $out .= ($display_type=='card' ? '' : '
'); /*for($ii = 0; $ii < ($colspan - 1); $ii++) { $out .=''; }*/ - if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= ''; - else $out .= ''; + if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) { + $out .= ($display_type=='card' ? '' : '
'); + } else { + $out .= ($display_type=='card' ? '' : ''); + } $e++; } } @@ -6978,7 +7127,17 @@ abstract class CommonObject { var val = $("select[name=\""+parent_list+"\"]").val(); var parentVal = parent_list + ":" + val; - if(val > 0) { + if(typeof val == "string"){ + if(val != "") { + var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone(); + $("select[name=\""+child_list+"\"] option[parent]").remove(); + $("select[name=\""+child_list+"\"]").append(options); + } else { + var options = orig_select.find("option[parent]").clone(); + $("select[name=\""+child_list+"\"] option[parent]").remove(); + $("select[name=\""+child_list+"\"]").append(options); + } + } else if(val > 0) { var options = orig_select.find("option[parent=\""+parentVal+"\"]").clone(); $("select[name=\""+child_list+"\"] option[parent]").remove(); $("select[name=\""+child_list+"\"]").append(options); @@ -6996,12 +7155,33 @@ abstract class CommonObject var parent = $(this).find("option[parent]:first").attr("parent"); var infos = parent.split(":"); var parent_list = infos[0]; + + //Hide daughters lists + if ($("#"+child_list).val() == 0 && $("#"+parent_list).val() == 0){ + $("#"+child_list).hide(); + //Show mother lists + } else if ($("#"+parent_list).val() != 0){ + $("#"+parent_list).show(); + } + //Show the child list if the parent list value is selected + $("select[name=\""+parent_list+"\"]").click(function() { + if ($(this).val() != 0){ + $("#"+child_list).show() + } + }); + + //When we change parent list $("select[name=\""+parent_list+"\"]").change(function() { showOptions(child_list, parent_list, orig_select[child_list]); + //Select the value 0 on child list after a change on the parent list + $("#"+child_list).val(0).trigger("change"); + //Hide child lists if the parent value is set to 0 + if ($(this).val() == 0){ + $("#"+child_list).hide(); + } }); }); } - setListDependencies(); }); '."\n"; diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 3191e5edd47..1eb3b9911ba 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -697,6 +697,12 @@ class Conf if (!empty($this->global->MAIN_TZUSERINPUTKEY)) $this->tzuserinputkey = $this->global->MAIN_TZUSERINPUTKEY; // 'tzserver' or 'tzuserrel' + if (!empty($this->global->PRODUIT_AUTOFILL_DESC)) { + $this->global->MAIN_NO_CONCAT_DESCRIPTION = 1; + } else { + unset($this->global->MAIN_NO_CONCAT_DESCRIPTION); + } + // For backward compatibility if (isset($this->product)) $this->produit = $this->product; if (isset($this->facture)) $this->invoice = $this->facture; diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 5fcc7b00c91..033ddd8afe3 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -66,6 +66,7 @@ class DolGraph public $labelInterval = -1; public $hideXGrid = false; + public $hideXValues = false; public $hideYGrid = false; public $Legend = array(); @@ -75,6 +76,12 @@ class DolGraph public $showpercent = 0; public $combine = 0; // 0.05 if you want to combine records < 5% into "other" public $graph; // Objet Graph (Artichow, Phplot...) + /** + * @var boolean Mirrors graph values + */ + public $mirrorGraphValues = false; + public $tooltipsTitles = null; + public $tooltipsLabels = null; /** * @var string Error code (or message) @@ -85,6 +92,7 @@ class DolGraph public $bgcolor; // array(R,G,B) public $bgcolorgrid = array(255, 255, 255); // array(R,G,B) public $datacolor; // array(array(R,G,B),...) + public $borderwidth = 1; private $stringtoshow; // To store string to output graph into HTML page @@ -175,6 +183,18 @@ class DolGraph return true; } + /** + * Hide X Values + * + * @param boolean $bool XValues or not + * @return boolean true + */ + public function setHideXValues($bool) + { + $this->hideXValues = $bool; + return true; + } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Hide Y grid @@ -244,9 +264,9 @@ class DolGraph // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Set data + * Set data color * - * @param array $datacolor Data color array(array(R,G,B),array(R,G,B)...) + * @param array $datacolor Data color array(array(R,G,B),array(R,G,B)...) or array('#......','#......'...) * @return void */ public function SetDataColor($datacolor) @@ -255,6 +275,50 @@ class DolGraph $this->datacolor = $datacolor; } + /** + * Set border color + * + * @param array $bordercolor Border Color array(array(R,G,B),array(R,G,B)...) or array('#FFFFFF','#......'...) + * @return void + */ + public function setBorderColor($bordercolor) + { + $this->bordercolor = $bordercolor; + } + + /** + * Set border width + * + * @param int $borderwidth Border Width + * @return void + */ + public function setBorderWidth($borderwidth) + { + $this->borderwidth = $borderwidth; + } + + /** + * Set tooltips labels of the graph + * + * @param array $tooltipsLabels Tooltips Labels array('...','...'...) + * @return void + */ + public function setTooltipsLabels($tooltipsLabels) + { + $this->tooltipsLabels = $tooltipsLabels; + } + + /** + * Set tooltips titles of the graph + * + * @param array $tooltipsTitles Tooltips Titles array('...','...'...) + * @return void + */ + public function setTooltipsTitles($tooltipsTitles) + { + $this->tooltipsTitles = $tooltipsTitles; + } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set type @@ -408,6 +472,17 @@ class DolGraph unset($this->bgcolorgrid); } + /** + * Mirror Values of the graph + * + * @param boolean $mirrorGraphValues Mirror Values if true and doesn't if false + * @return void + */ + public function setMirrorGraphValues($mirrorGraphValues) + { + $this->mirrorGraphValues = $mirrorGraphValues; + } + /** * Is graph ko * @@ -964,7 +1039,7 @@ class DolGraph $array_of_ykeys = array_keys($valarray); $alabelexists = 1; $tmpykey = explode('_', ($array_of_ykeys[$i + ($alabelexists ? 1 : 0)]), 3); - if (!empty($tmpykey[2]) || $tmpykey[2] == '0') { // This is a 'Group by' array + if (isset($tmpykey[2]) && (!empty($tmpykey[2]) || $tmpykey[2] == '0')) { // This is a 'Group by' array $tmpvalue = (array_key_exists('y_' . $tmpykey[1] . '_' . $tmpykey[2], $valarray) ? $valarray['y_' . $tmpykey[1] . '_' . $tmpykey[2]] : $valarray[$i + 1]); $values[$x] = (is_numeric($tmpvalue) ? $tmpvalue : null); $arrayofgroupslegend[$i] = array( @@ -1129,9 +1204,6 @@ class DolGraph else { $type = 'bar'; - $isfunnel = false; - if ($file == 'idgraphleadfunnel') $isfunnel = true; - if (!isset($this->type[$firstlot]) || $this->type[$firstlot] == 'bars') $type = 'bar'; if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'horizontalbars') $type = 'horizontalBar'; if (isset($this->type[$firstlot]) && ($this->type[$firstlot] == 'lines' || $this->type[$firstlot] == 'linesnopoint')) $type = 'line'; @@ -1141,7 +1213,7 @@ class DolGraph $this->stringtoshow .= 'legend: { display: false }, '; } $this->stringtoshow .= 'scales: { xAxes: [{ '; - if ($isfunnel) { // FIXME Remove isfunnel by introducing a method hideXValues() on dolgraph + if ($this->hideXValues) { $this->stringtoshow .= ' ticks: { display: false }, display: true,'; } //$this->stringtoshow .= 'type: \'time\', '; // Need Moment.js @@ -1156,17 +1228,23 @@ class DolGraph } $this->stringtoshow .= ' }] }'; // Add a callback to change label to show only positive value - if ($isfunnel) { + if (is_array($this->tooltipsLabels) || is_array($this->tooltipsTitles)) { $this->stringtoshow .= ', tooltips: { mode: \'nearest\', - callbacks: { - title: function(tooltipItem, data) { - return data.datasets[tooltipItem[0].datasetIndex].label; - }, - label: function(tooltipItem, data) { - return data.datasets[tooltipItem.datasetIndex].data[0][1]; - } - } - },'; + callbacks: {'; + if (is_array($this->tooltipsTitles)) { + $this->stringtoshow .=' + title: function(tooltipItem, data) { + var tooltipsTitle ='.json_encode($this->tooltipsTitles).' + return tooltipsTitle[tooltipItem[0].datasetIndex]; + },'; + } + if (is_array($this->tooltipsLabels)) { + $this->stringtoshow .= 'label: function(tooltipItem, data) { + var tooltipslabels ='.json_encode($this->tooltipsLabels).' + return tooltipslabels[tooltipItem.datasetIndex] + }'; + } + $this->stringtoshow .='}},'; } $this->stringtoshow .= '};'; $this->stringtoshow .= ' @@ -1180,13 +1258,11 @@ class DolGraph labels: ['; $i = 0; - if (!$isfunnel) { - foreach ($legends as $val) // Loop on each serie - { - if ($i > 0) $this->stringtoshow .= ', '; - $this->stringtoshow .= "'".dol_escape_js(dol_trunc($val, 32))."'"; - $i++; - } + foreach ($legends as $val) // Loop on each serie + { + if ($i > 0) $this->stringtoshow .= ', '; + $this->stringtoshow .= "'" . dol_escape_js(dol_trunc($val, 32)) . "'"; + $i++; } //var_dump($arrayofgroupslegend); @@ -1196,14 +1272,15 @@ class DolGraph global $theme_datacolor; //var_dump($arrayofgroupslegend); - $i = 0; $iinstack = 0; + $i = 0; + $iinstack = 0; $oldstacknum = -1; while ($i < $nblot) // Loop on each serie { $foundnegativecolor = 0; $usecolorvariantforgroupby = 0; // We used a 'group by' and we have too many colors so we generated color variants per - if (is_array($arrayofgroupslegend[$i]) && count($arrayofgroupslegend[$i]) > 0) { // If we used a group by. + if (!empty($arrayofgroupslegend) && is_array($arrayofgroupslegend[$i]) && count($arrayofgroupslegend[$i]) > 0) { // If we used a group by. $nbofcolorneeds = count($arrayofgroupslegend); $nbofcolorsavailable = count($theme_datacolor); if ($nbofcolorneeds > $nbofcolorsavailable) { @@ -1242,34 +1319,15 @@ class DolGraph $color = 'rgb(' . $newcolor[0] . ', ' . $newcolor[1] . ', ' . $newcolor[2] . ', 0.9)'; $bordercolor = 'rgb(' . $newcolor[0] . ', ' . $newcolor[1] . ', ' . $newcolor[2] . ')'; } else { // We do not use a 'group by' - if ($isfunnel) { - $bordercolor == 'null'; - if (is_array($this->datacolor[$i])) { - $color = 'rgb(' . $this->datacolor[$i][0] . ', ' . $this->datacolor[$i][1] . ', ' . $this->datacolor[$i][2] . ', 0.9)'; // If datacolor is array(R, G, B) - } else { - // TODO FIXME This logic must be in the caller that set $this->datacolor - $tmp = str_replace('#', '', $this->datacolor[$i]); - if (strpos($tmp, '-') !== false) { - $foundnegativecolor++; - $color = '#FFFFFF'; // If $val is '-123' - } else { - $color = "#" . $tmp; // If $val is '123' or '#123' - $bordercolor = $color; - } - if ($foundnegativecolor) { - if (is_array($this->datacolor[$i])) $color = 'null'; // If datacolor is array(R, G, B) - else { - $tmp = str_replace('#', '', $this->datacolor[$i]); - if (strpos($tmp, '-') !== false) $bordercolor = '#' . str_replace('-', '', $tmp); // If $val is '-123' - else $bordercolor = 'null'; // If $val is '123' or '#123' - } - } - } - $bordercolor == 'null' ? "'rgba(0,0,0,0.2)'" : "'" . $bordercolor . "'"; + if (is_array($this->datacolor[$i])) { + $color = 'rgb(' . $this->datacolor[$i][0] . ', ' . $this->datacolor[$i][1] . ', ' . $this->datacolor[$i][2] . ', 0.9)'; } else { - $color = 'rgb('.$this->datacolor[$i][0].', '.$this->datacolor[$i][1].', '.$this->datacolor[$i][2].', 0.9)'; + $color = $this->datacolor[$i]; + } + if (is_array($this->bordercolor[$i])) { $bordercolor = $color; - //$color = (!empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)); + } else { + $bordercolor = $this->bordercolor[$i]; } } @@ -1278,23 +1336,18 @@ class DolGraph $this->stringtoshow .= '{'; $this->stringtoshow .= 'dolibarrinfo: \'y_' . $i . '\', '; $this->stringtoshow .= 'label: \'' . dol_escape_js(dol_string_nohtmltag($textoflegend)) . '\', '; - $this->stringtoshow .= 'pointStyle: \'' . ($this->type[$i] == 'linesnopoint' ? 'line' : 'circle') . '\', '; + $this->stringtoshow .= 'pointStyle: \'' . ((!empty($this->type[$i]) && $this->type[$i] == 'linesnopoint') ? 'line' : 'circle') . '\', '; $this->stringtoshow .= 'fill: ' . ($type == 'bar' ? 'true' : 'false') . ', '; - if ($isfunnel) { - $this->stringtoshow .= 'borderWidth: \'2\', '; - } elseif ($type == 'bar' || $type == 'horizontalBar') { - $this->stringtoshow .= 'borderWidth: \'1\', '; + if ($type == 'bar' || $type == 'horizontalBar') { + $this->stringtoshow .= 'borderWidth: \''.$this->borderwidth.'\', '; } $this->stringtoshow .= 'borderColor: \'' . $bordercolor . '\', '; $this->stringtoshow .= 'backgroundColor: \'' . $color . '\', '; - if ($arrayofgroupslegend[$i]) $this->stringtoshow .= 'stack: \'' . $arrayofgroupslegend[$i]['stacknum'] . '\', '; - $this->stringtoshow .='data: ['; - if ($isfunnel) { - $this->stringtoshow .= '['.-$serie[$i].','.$serie[$i].']'; - } else { - $this->stringtoshow .= $serie[$i]; - } - $this->stringtoshow .=']'; + if (!empty($arrayofgroupslegend) && !empty($arrayofgroupslegend[$i])) $this->stringtoshow .= 'stack: \'' . $arrayofgroupslegend[$i]['stacknum'] . '\', '; + $this->stringtoshow .= 'data: ['; + + $this->stringtoshow .= $this->mirrorGraphValues ? '[' . -$serie[$i] . ',' . $serie[$i] . ']' : $serie[$i]; + $this->stringtoshow .= ']'; $this->stringtoshow .= '}' . "\n"; $i++; @@ -1318,7 +1371,7 @@ class DolGraph { $value = 0; foreach ($this->data as $valarray) // Loop on each x - { + { $value += $valarray[1]; } return $value; @@ -1361,13 +1414,11 @@ class DolGraph { global $conf; - if ($direction == 'width') - { + if ($direction == 'width') { if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500'); else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width'] - 40)); } - if ($direction == 'height') - { + if ($direction == 'height') { return (empty($conf->dol_optimize_smallscreen) ? ($defaultsize ? $defaultsize : '200') : '160'); } return 0; diff --git a/htdocs/core/class/dolreceiptprinter.class.php b/htdocs/core/class/dolreceiptprinter.class.php index e075005b437..4dfca1186c0 100644 --- a/htdocs/core/class/dolreceiptprinter.class.php +++ b/htdocs/core/class/dolreceiptprinter.class.php @@ -634,13 +634,13 @@ class dolReceiptPrinter extends Printer if ($line->fk_product) { $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); $this->printer->text(strip_tags(htmlspecialchars_decode($line->product_label))."\n"); } else { $spacestoadd = $nbcharactbyline - strlen($line->description) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($line->description.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); } } @@ -653,7 +653,7 @@ class dolReceiptPrinter extends Printer } foreach ($vatarray as $vatkey => $vatvalue) { $spacestoadd = $nbcharactbyline - strlen($vatkey) - 12; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($spaces.$vatkey.'% '.str_pad(price($vatvalue), 10, ' ', STR_PAD_LEFT)."\n"); } break; @@ -680,15 +680,15 @@ class dolReceiptPrinter extends Printer case 'DOL_PRINT_OBJECT_TOTAL': $title = $langs->trans('TotalHT'); $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($title.$spaces.str_pad(price($object->total_ht), 10, ' ', STR_PAD_LEFT)."\n"); $title = $langs->trans('TotalVAT'); $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($title.$spaces.str_pad(price($object->total_tva), 10, ' ', STR_PAD_LEFT)."\n"); $title = $langs->trans('TotalTTC'); $spacestoadd = $nbcharactbyline - strlen($title) - 10; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($title.$spaces.str_pad(price($object->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); break; case 'DOL_LINE_FEED': @@ -778,7 +778,7 @@ class dolReceiptPrinter extends Printer if ($line->special_code == $this->orderprinter) { $spacestoadd = $nbcharactbyline - strlen($line->ref) - strlen($line->qty) - 10 - 1; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($line->ref.$spaces.$line->qty.' '.str_pad(price($line->total_ttc), 10, ' ', STR_PAD_LEFT)."\n"); $this->printer->text(strip_tags(htmlspecialchars_decode($line->desc))."\n"); } @@ -799,14 +799,14 @@ class dolReceiptPrinter extends Printer while ($i < $num) { $row = $this->db->fetch_object($resql); $spacestoadd = $nbcharactbyline - strlen($langs->transnoentitiesnoconv("PaymentTypeShort".$row->code)) - 12; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $amount_payment = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1) ? $row->multicurrency_amount : $row->amount; if ($row->code == "LIQ") $amount_payment = $amount_payment + $row->pos_change; // Show amount with excess received if is cash payment $this->printer->text($spaces.$langs->transnoentitiesnoconv("PaymentTypeShort".$row->code).' '.str_pad(price($amount_payment), 10, ' ', STR_PAD_LEFT)."\n"); if ($row->code == "LIQ" && $row->pos_change > 0) // Print change only in cash payments { $spacestoadd = $nbcharactbyline - strlen($langs->trans("Change")) - 12; - $spaces = str_repeat(' ', $spacestoadd); + $spaces = str_repeat(' ', $spacestoadd > 0 ? $spacestoadd : 0); $this->printer->text($spaces.$langs->trans("Change").' '.str_pad(price($row->pos_change), 10, ' ', STR_PAD_LEFT)."\n"); } $i++; diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index 2daf4c835e9..045ab92f08e 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -924,15 +924,15 @@ class ExtraFields * Return HTML string to put an input field into a page * Code very similar with showInputField of common object * - * @param string $key Key of attribute - * @param string $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value) - * @param string $moreparam To add more parametes on html input tag - * @param string $keysuffix Prefix string to add after name and id of field (can be used to avoid duplicate names) - * @param string $keyprefix Suffix string to add before name and id of field (can be used to avoid duplicate names) - * @param string $morecss More css (to defined size of field. Old behaviour: may also be a numeric) - * @param int $objectid Current object id - * @param string $extrafieldsobjectkey If defined (for example $object->table_element), use the new method to get extrafields data - * @param string $mode 1=Used for search filters + * @param string $key Key of attribute + * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value); for dates in filter mode, a range array('start'=>, 'end'=>) should be provided + * @param string $moreparam To add more parameters on html input tag + * @param string $keysuffix Prefix string to add after name and id of field (can be used to avoid duplicate names) + * @param string $keyprefix Suffix string to add before name and id of field (can be used to avoid duplicate names) + * @param string $morecss More css (to defined size of field. Old behaviour: may also be a numeric) + * @param int $objectid Current object id + * @param string $extrafieldsobjectkey If defined (for example $object->table_element), use the new method to get extrafields data + * @param string $mode 1=Used for search filters * @return string */ public function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '', $mode = 0) @@ -1024,8 +1024,21 @@ class ExtraFields // Do not show current date when field not required (see selectDate() method) if (!$required && $value == '') $value = '-1'; - // TODO Must also support $moreparam - $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); + if ($mode == 1) { + // search filter on a date extrafield shows two inputs to select a date range + $prefill = array( + 'start' => isset($value['start']) ? $value['start'] : '', + 'end' => isset($value['end']) ? $value['end'] : '' + ); + $out = '
' + . $form->selectDate($prefill['start'], $keyprefix.$key.$keysuffix.'_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("From")) + . '
' + . $form->selectDate($prefill['end'], $keyprefix.$key.$keysuffix.'_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to")) + . '
'; + } else { + // TODO Must also support $moreparam + $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1); + } } elseif (in_array($type, array('int', 'integer'))) { $tmp = explode(',', $size); @@ -1097,7 +1110,12 @@ class ExtraFields foreach ($param['options'] as $key => $val) { if ((string) $key == '') continue; - list($val, $parent) = explode('|', $val); + $valarray = explode('|', $val); + $val = $valarray[0]; + $parent = ''; + if (!empty($valarray[1])) { + $parent = $valarray[1]; + } $out .= '