From 472665c03875b50398d4659feb0333812a367128 Mon Sep 17 00:00:00 2001 From: minimexat Date: Mon, 23 Feb 2026 20:05:26 +0100 Subject: [PATCH 01/14] fix(adherents): show cotisation create form for members with existing subscriptions (#37312) Co-authored-by: f-hoedl Co-authored-by: Laurent Destailleur --- htdocs/adherents/subscription.php | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index af357257351..ef829fe6268 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -151,7 +151,7 @@ if (empty($reshook) && $action == 'confirm_create_thirdparty' && $confirm == 'ye } else { $object->socid = $result; - $action = 'addsubscription'; + $action = 'createsubscription'; } } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -250,14 +250,14 @@ if (empty($reshook) && $user->hasRight('adherent', 'cotisation', 'creer') && $ac $langs->load("errors"); $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateSubscription")); setEventMessages($errmsg, null, 'errors'); - $action = 'addsubscription'; + $action = 'createsubscription'; } if (GETPOST('end') && !$datesubend) { $error++; $langs->load("errors"); $errmsg = $langs->trans("ErrorBadDateFormat", $langs->transnoentitiesnoconv("DateEndSubscription")); setEventMessages($errmsg, null, 'errors'); - $action = 'addsubscription'; + $action = 'createsubscription'; } if (!$datesubend) { $datesubend = dol_time_plus_duree(dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit), -1, 'd'); @@ -266,7 +266,7 @@ if (empty($reshook) && $user->hasRight('adherent', 'cotisation', 'creer') && $ac $error++; $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DatePayment")); setEventMessages($errmsg, null, 'errors'); - $action = 'addsubscription'; + $action = 'createsubscription'; } // Check if a payment is mandatory or not @@ -276,7 +276,7 @@ if (empty($reshook) && $user->hasRight('adherent', 'cotisation', 'creer') && $ac $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); setEventMessages($errmsg, null, 'errors'); $error++; - $action = 'addsubscription'; + $action = 'createsubscription'; } else { // If an amount has been provided, we check also fields that becomes mandatory when amount is not null. if (isModEnabled('bank') && GETPOST("paymentsave") != 'none') { @@ -285,26 +285,26 @@ if (empty($reshook) && $user->hasRight('adherent', 'cotisation', 'creer') && $ac $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); setEventMessages($errmsg, null, 'errors'); $error++; - $action = 'addsubscription'; + $action = 'createsubscription'; } if (GETPOST("paymentsave") != 'invoiceonly' && !GETPOST("operation")) { $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); setEventMessages($errmsg, null, 'errors'); $error++; - $action = 'addsubscription'; + $action = 'createsubscription'; } if (GETPOST("paymentsave") != 'invoiceonly' && !(GETPOSTINT("accountid") > 0)) { $errmsg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("FinancialAccount")); setEventMessages($errmsg, null, 'errors'); $error++; - $action = 'addsubscription'; + $action = 'createsubscription'; } } else { if (GETPOSTINT("accountid")) { $errmsg = $langs->trans("ErrorDoNotProvideAccountsIfNullAmount"); setEventMessages($errmsg, null, 'errors'); $error++; - $action = 'addsubscription'; + $action = 'createsubscription'; } } } @@ -337,7 +337,7 @@ if (empty($reshook) && $user->hasRight('adherent', 'cotisation', 'creer') && $ac $db->commit(); } else { $db->rollback(); - $action = 'addsubscription'; + $action = 'createsubscription'; } if (!$error) { @@ -697,11 +697,11 @@ print dol_get_fiche_end(); // Button to create a new subscription if member no draft (-1) neither resiliated (0) neither excluded (-2) if ($user->hasRight('adherent', 'cotisation', 'creer')) { - if ($action != 'addsubscription' && $action != 'create_thirdparty') { + if ($action != 'createsubscription' && $action != 'create_thirdparty') { print '
'; if ($object->status > 0) { - print '"; + print '"; } else { print ''; } @@ -713,7 +713,7 @@ if ($user->hasRight('adherent', 'cotisation', 'creer')) { /* * List of subscriptions */ -if ($action != 'addsubscription' && $action != 'create_thirdparty') { +if ($action != 'createsubscription' && $action != 'create_thirdparty') { $sql = "SELECT d.rowid, d.firstname, d.lastname, d.societe, d.fk_adherent_type as type,"; $sql .= " c.rowid as crowid, c.subscription,"; $sql .= " c.datec, c.fk_type as cfk_type,"; @@ -822,7 +822,7 @@ if ($action != 'addsubscription' && $action != 'create_thirdparty') { } -if (($action != 'addsubscription' && $action != 'create_thirdparty')) { +if (($action != 'createsubscription' && $action != 'create_thirdparty')) { // Show online payment link // The list can be complete by the hook 'doValidatePayment' executed inside getValidOnlinePaymentMethods() include_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php'; @@ -841,7 +841,7 @@ if (($action != 'addsubscription' && $action != 'create_thirdparty')) { /* * Add new subscription form */ -if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->hasRight('adherent', 'cotisation', 'creer')) { +if (($action == 'createsubscription' || $action == 'create_thirdparty') && $user->hasRight('adherent', 'cotisation', 'creer')) { print '
'; print load_fiche_titre($langs->trans("NewCotisation")); From c8111f972656a4d555ed59b112af502f39bbeb0f Mon Sep 17 00:00:00 2001 From: William Mead Date: Mon, 23 Feb 2026 20:07:15 +0100 Subject: [PATCH 02/14] QUAL updated projects API PHPDoc (#37275) * Debug savedemo * Fix mention * Fix pdf font for CZ * Added project API class and methods since tag --------- Co-authored-by: Laurent Destailleur --- htdocs/projet/class/api_projects.class.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/htdocs/projet/class/api_projects.class.php b/htdocs/projet/class/api_projects.class.php index b55ebbc9770..ec19295a425 100644 --- a/htdocs/projet/class/api_projects.class.php +++ b/htdocs/projet/class/api_projects.class.php @@ -28,6 +28,7 @@ require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php'; /** * API class for projects * + * @since 5.0.0 Initial implementation * @access protected * @class DolibarrApiAccess {@requires user,external} */ @@ -68,6 +69,7 @@ class Projects extends DolibarrApi * * Return an array with project information * + * @since 5.0.0 Initial implementation * @param int $id ID of project * @return Object Object with cleaned properties * @@ -97,6 +99,7 @@ class Projects extends DolibarrApi * * Return an array with project information * + * @since 20.0.0 Initial implementation * @param string $ref Ref of project * @return Object Object with cleaned properties * @@ -128,6 +131,7 @@ class Projects extends DolibarrApi * * Return an array with project information * + * @since 20.0.0 Initial implementation * @param string $ref_ext Ref_Ext of project * @return Object Object with cleaned properties * @@ -159,6 +163,7 @@ class Projects extends DolibarrApi * * Return an array with project information * + * @since 20.0.0 Initial implementation * @param string $email_msgid Email msgid of project * @return Object Object with cleaned properties * @@ -190,6 +195,7 @@ class Projects extends DolibarrApi * * Get a list of projects * + * @since 5.0.0 Initial implementation * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -307,6 +313,7 @@ class Projects extends DolibarrApi /** * Create project object * + * @since 5.0.0 Initial implementation * @param array $request_data Request data * @phan-param array $request_data * @phpstan-param array $request_data @@ -390,6 +397,7 @@ class Projects extends DolibarrApi /** * Adds a contact to an project * + * @since 23.0.0 Initial implementation * @param int $id project ID * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if source = 'internal') to link * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING @@ -431,6 +439,7 @@ class Projects extends DolibarrApi /** * Delete a contact type of given project * + * @since 23.0.0 Initial implementation * @param int $id Id of project to update * @param int $contactid Row key of the contact in the array contact_ids. * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). @@ -475,6 +484,7 @@ class Projects extends DolibarrApi * Get tasks of a project. * See also API /tasks * + * @since 5.0.0 Initial implementation * @param int $id Id of project * @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines * @return array @@ -515,6 +525,7 @@ class Projects extends DolibarrApi /** * Get roles a user is assigned to a project with * + * @since 5.0.0 Initial implementation * @param int $id Id of project * @param int $userid Id of user (0 = connected user) * @return array @@ -693,6 +704,7 @@ class Projects extends DolibarrApi /** * Update project general fields (won't touch lines of project) * + * @since 5.0.0 Initial implementation * @param int $id Id of project to update * @param array $request_data Datas * @phan-param ?array $request_data @@ -744,6 +756,7 @@ class Projects extends DolibarrApi /** * Delete project * + * @since 5.0.0 Initial implementation * @param int $id Project ID * * @return array @@ -781,6 +794,7 @@ class Projects extends DolibarrApi * You can test this API with the following input message * { "notrigger": 0 } * + * @since 5.0.0 Initial implementation * @param int $id Project ID * @param int $notrigger 1=Does not execute triggers, 0= execute triggers * @phan-param int<0,1> $notrigger @@ -831,6 +845,7 @@ class Projects extends DolibarrApi /** * Get all timespent * + * @since 23.0.0 Initial implementation * @param string $sortfield Sort field * @param string $sortorder Sort order * @param int $limit Limit for list @@ -1027,6 +1042,7 @@ class Projects extends DolibarrApi * * Return an array with contact information * + * @since 23.0.0 Initial implementation * @param int $id ID of project * @param string $type Type of the contact * @return array Array with cleaned properties @@ -1061,6 +1077,7 @@ class Projects extends DolibarrApi /** * Adds a contact to a project * + * @since 23.0.0 Initial implementation * @param int $id Project ID * @param int $fk_socpeople Id of thirdparty contact (if source = 'external') or id of user (if source = 'internal') to link * @param string $type_contact Type of contact (code). Must a code found into table llx_c_type_contact. For example: BILLING @@ -1121,6 +1138,7 @@ class Projects extends DolibarrApi /** * Delete a contact type of given project * + * @since 23.0.0 Initial implementation * @param int $id Id of project to update * @param int $contactid Row key of the contact in the array contact_ids. * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). @@ -1167,6 +1185,7 @@ class Projects extends DolibarrApi /** * Get timespent of a project (from all its tasks) * + * @since 23.0.0 Initial implementation * @param int $id ID of project * @return array Array of timespent objects * From f919a837213251ea8a69e6da55ef74cb0f2a9d22 Mon Sep 17 00:00:00 2001 From: splohmer <113967431+splohmer@users.noreply.github.com> Date: Mon, 23 Feb 2026 20:08:30 +0100 Subject: [PATCH 03/14] FIX upload of files with multiple spaces via drag'n'drop flow (#37271) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Debug savedemo * Fix mention * FIX upload of files with multiple spaces via drag'n'drop flow Currently there are two ways to upload files to products, orders, etc. via the "old" way and the document tab and the "new" flow via drag'n'drop on the main tab of the object. Both ways triggering completely different code paths. In the end the new way uses dol_sanitzieFileName to sanitize the name of the file and the old way uses dol_string_nohtmltag (both from functions.lib.php). One of the main difference between the two mentioned functions is that in the old way multiple spaces behind each other are replaced by a single space. E.g. "A␠␠B␠␠␠C␠␠D" is tranformed to "A␠B␠C␠D". This is needed to make sure that the files are properly uploaded and can be later also downloaded correctly. How to reproduce? Upload a file like "test␠␠test.txt" via the drag'n'drop flow and try to download it from the document tab. This is not working. You can see the file but cannot download it. The same flow via the input field of the document tab is working correctly. * typo in comment * FIX Phan warnings (unrelated to feature) * FIX Phan warnings (unrelated to feature) * FIX Phan warnings (unrelated to feature) --------- Co-authored-by: Laurent Destailleur --- htdocs/core/class/fileupload.class.php | 11 +++++++---- htdocs/takepos/send.php | 1 - 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/htdocs/core/class/fileupload.class.php b/htdocs/core/class/fileupload.class.php index 1354894cf41..47e4ab90c02 100644 --- a/htdocs/core/class/fileupload.class.php +++ b/htdocs/core/class/fileupload.class.php @@ -100,11 +100,13 @@ class FileUpload dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php'); $parent = new $parentClass($db); - $parent->fetch($object->$parentForeignKey); - if (!empty($parent->socid)) { - $parent->fetch_thirdparty(); + if ($object->$parentForeignKey !== null) { + $parent->fetch((int) $object->$parentForeignKey); + if (!empty($parent->socid)) { + $parent->fetch_thirdparty(); + } + $object->$parentObject = clone $parent; } - $object->$parentObject = clone $parent; $object_ref = dol_sanitizeFileName($object->project->ref).'/'.$object_ref; } @@ -396,6 +398,7 @@ class FileUpload // Remove path information and dots around the filename, to prevent uploading // into different directories or replacing hidden system files. $file_name = basename(dol_sanitizeFileName($name)); + $file_name = preg_replace('/ {2,}/', ' ', $file_name); // replaces multiple spaces into one space like the upload flow via input field // Add missing file extension for known image types: $matches = array(); if (strpos($file_name, '.') === false && preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) { diff --git a/htdocs/takepos/send.php b/htdocs/takepos/send.php index 6d40cb76bbd..044700c89ef 100644 --- a/htdocs/takepos/send.php +++ b/htdocs/takepos/send.php @@ -144,7 +144,6 @@ if ($action == "send" && $user->hasRight('takepos', 'run')) { $object->context['email_msgid'] = $mail->msgid; // Same code as in actions_sendmail.inc.php - // if ($triggersendname === 'BILL_SENTBYMAIL' && $object instanceof Facture) { // Always true ($triggersendname is set above, and $object = $invoice = Facture object // If sending email for invoice, we increase the counter of invoices sent by email $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET email_sent_counter = email_sent_counter + 1"; $sql .= " WHERE rowid = ".((int) $object->id); From 6041233c4bce2483daeb8bd87c5d6212076271e3 Mon Sep 17 00:00:00 2001 From: Lucky <93642903+LuckyRoussel98@users.noreply.github.com> Date: Mon, 23 Feb 2026 22:09:42 +0300 Subject: [PATCH 04/14] Fix_massaction_withdraw_control (#37237) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CI * CI * CI * CI * Clean code. File not used. * CSS * CSS * Fix phpunit * More legal info * CI * Fix CI * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Protect module * Add currency * CSS * WIP LNE * Fix navigation * cs * Debug registration process * Debug setup navigation * CI * CI * Factorize code * Fix CI * Fix CI * Fix CI * CI * CI * CI * CI * Disable phan on v23 * CI * CI * FIX: missing include for blockedlog lib (#37165) * Debug CI * fix ternary always true (#37161) * fix ternary always true * Update requests.php * Update registration.php --------- Co-authored-by: Laurent Destailleur * CI * FIX: missing include for blockedlog lib (#37165) * FIX #37134 Use json_encode for IMAP search logging in EmailCollector (#37135) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch) as each line becomes a separate log entry. Using json_encode() produces single-line structured output that works correctly with all log aggregation tools. Co-authored-by: Laurent Destailleur * Populate syslog with placeholder (#37163) Co-authored-by: Laurent Destailleur * Doc * datamodel for user change password next time (#37155) * Qual: Update phan baseline (#37172) * Fix typo in file path (#37160) Co-authored-by: Laurent Destailleur * Fix phpunit * Complete call to setStatus so we have a trigy as 4th parameter (help to fix the #37129) * FIX Product - Warning on admin (#37157) Co-authored-by: Laurent Destailleur * FIX Product - Warning on admin + CSS (#37158) * FIX Product - Warning on admin * CSS --------- Co-authored-by: Laurent Destailleur * CI * CI * CI * Avoid error if include fails * More functions in blacklist (even if nw we use the whitelist by default) * #37166 [SQL] add: email template for ticket admin creation (#37182) * Replace var_export with new function formatLogObject (#37178) * FIX BOM - Class product missing, column offset and information recording (form/input overlap) in admin (#37177) * FIX BOM - Class product missing in admin * Fix column offset and information recording (form/input overlap) * ci * ci * FIX Intracommreport - Warning & link problem on tab (#37176) * FIX Bank transfer admin - Warning & save 0 on constant PAYMENTBYBANKTRANSFER_ADDDAYS (#37175) * Look and feel v24 * Update default time handling in index.php (#37150) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix CI * Add template in migration * fix phpdoc comment (#37184) * fix phpdoc comment * fix phpdoc comment --------- Co-authored-by: Laurent Destailleur * CI * Fix phpstan * Replace var_export by formatLogObject (continued) (#37188) Co-authored-by: Laurent Destailleur * Debug amount suggested on membership public form * Issue 36923 Fix session title handling in survey creation (#37105) * Issue 36923 Fix session title handling in survey creation * Change input field to use id attribute for title --------- Co-authored-by: Laurent Destailleur * fix phpstan errors blocking action baseline (#37189) * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * refresh baseline * QUAL Replace var_export() with json_encode() in dol_syslog() calls (#37138) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch, Graylog) as each line becomes a separate log entry. json_encode() produces single-line structured output that works correctly with all log aggregation tools. This pattern is already used elsewhere in Dolibarr (accountancy, install modules). Files changed: - core/class/commoninvoice.class.php (payment intent logging) - core/class/commonobject.class.php (payment terms logging) - core/modules/mailings/advthirdparties.modules.php (mailing targets) - core/modules/oauth/google_oauthcallback.php (userinfo logging) - core/modules/oauth/generic_oauthcallback.php (userinfo logging) - public/payment/newpayment.php (GET/POST debug logging) - public/payment/paymentok.php (payment tag logging) - public/stripe/ipn.php (Stripe event data logging) - paypal/lib/paypal.lib.php (PayPal response logging) - api/index.php (API debug logging) - stripe/class/stripe.class.php (payment/setup intent logging) Co-authored-by: f-hoedl Co-authored-by: Laurent Destailleur * Fix CI * CI * Check if upload_max_filesize is not empty * clean code * Debug v23 * CI * Fix #33521 VAT total false (#36990) * - Fix #33521 VAT total false - Fix some warnings - Fix : delete $this->vat_rate * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php --------- Co-authored-by: vmaury Co-authored-by: Laurent Destailleur * NEW #25829 Automatically send the invoice generated from a template (#36967) * Update DB * ADD email template * Ajout d'une clé de trad * Ajout des traductions * Suppression des traductions, sauf en_US * Add flag auto send * Modif form + cron auto send * Suppression auto_send * correction loopError * ajout du selected au model de mail * Prise en compte default model * Fix pre-commit * ménage * precommit * Correction Phan * Correction Phan * Correction, double cal du trigger --------- Co-authored-by: Laurent Destailleur * Develop force user change pass userclass (#37174) * datamodel for user change password next time * add force_pass_change in user object * Initialize force_pass_change to 0 --------- Co-authored-by: Laurent Destailleur * Another step for #37171 * Qual: Partial phan run on PR's, complete run on integration branches (#37186) * Qual: Partial phan run on PR's, complete on main # Qual: Partial phan run on PR's, complete on main The selection is based on the branch name. To run a complete phan run in a PR, the branch name of the PR must include phan_full. This can help to fix remaining phan issue before re-integrating to the develop branch. * qual: Update workflow and pre-commit configurations - Enable phan workflow by uncommenting the relevant lines - Update actionlint version to v1.7.10 - Add manual stage to actionlint hook in pre-commit-config.yaml * qual: Update Phan analysis conditions The conditions for running Phan analysis have been updated to include an additional check for branches containing 'phan_full'. * qual: Update Phan workflow - Replace github.event.ref with github.ref_name - Add FILE_CHANGE_LIST environment variable for better file handling - Update file list creation and usage in the workflow * qual: Update Phan workflow conditions Fix the branch reference (head_ref in PR, ref_name otherwise) * Add step for debug information * Remove debug step * Fix: Missing initialisations members/new.php Following a suppression of assignments, the variables disabledphy and disabledmor were undefined. * fix: Update budget selection dropdown arguments in member creation form Correct the arguments in the member creation form. * qual: Add cs2pr to phan workflow - Add cs2pr to the tools list in the phan workflow - Change the output mode of phan to checkstyle - Add a step to add results to PR as Github notices - Add a step to provide phan log as artifact * qual: Update Phan workflow to use environment variable for file list The change fixes the Phan workflow to use the environment variable `$FILE_CHANGED_LIST` to clear the file --------- Co-authored-by: Laurent Destailleur * Fix phan * Fix phan * Merge branch '23.0' of git@github.com:Dolibarr/dolibarr.git into 23.0 * Doc * Qual: Fix ambigious redirect error on Phan workflow (#37200) # Qual: Fix ambigious redirect error on Phan workflow Rewrote the shell command that is supposed to suppress a file contents but is flagged by the environment. * PHPStan > Update baseline (#37197) Co-authored-by: Dolibot * Typo fix (#37195) * Debug v23 - filters on agenda pages * css * css * css * qual: Update PHPStan workflow to run on all files in integration (#37207) The PHPStan workflow has been updated to run on all files in integration branches. * Fix CI * Add hook in isEditable() * Debug v23 * CLOSE #37190 ODT Templates for thirdparties - Birthday is returned in epoch format (#37198) Co-authored-by: Laurent Destailleur * fix: Remove HTML from accounting menu tooltips in eldy theme (#37203) Co-authored-by: Laurent Destailleur * Qual: Update spelling (#37199) * Qual: Update spelling for pre-select variants # Qual: Update spelling for pre-select variants In English, preselect is without the hyphen. Update text and made some translations related to preselect. * Qual: Update composant to component and/or adequate translation. # Qual: Update composant to component and/or adequate translation. "Composant(s)" was mostly referenced in french file/class comments. Updated * Qual: Fix misspellings related to "criteria" # Qual: Fix misspellings related to "criteria" * Qual: Fix produt misspellings # Qual: Fix produt misspellings Change 'produt' to 'product'. * Qual: Update French comments with "composants" #Qual: Update French comments with "composants" - Translating French comments to English (avoid codespell notice) * Qual: Fixed typo 'bad practive' to 'bad practice' # Qual: Fixed typo 'bad practive' to 'bad practice' * Qual: Update phan.yml to exclude specific files from analysis - Added file exclusion pattern to match phan configuration - Added check for empty file list to avoid unnecessary phan execution * Qual: Update file filtering in phan.yml workflow The change updates the file filtering process in the phan.yml workflow to correctly redirect the output of the grep command to a temporary file. * Qual: Ignore $systemfunction always exists --------- Co-authored-by: Laurent Destailleur * Error handling methods for commonobject (#37201) * Error handling methods for commonobject (#37201) * NEW Can request and force user to change its password (#37196) * force user to change password : redirect to user card on login * force user to change password : redirect to user card on login * redirect to a dedicated page * bad old idea : self change passwd on user card + edit mode and rights: it makes a hole on security check * only apply on dolibarr auth mode context * only on dolibarr auth mode context * Fix force_pass_change SQL assignment logic --------- Co-authored-by: Laurent Destailleur * Doc * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Prepare 23.0 * Qual: Ignore exit code from `grep -v` in phan flow (#37213) # Qual: Ignore exit code from `grep -v` in phan flow `grep -v` returns 1 when the resulting filtered list is empty and would stop the execution. This is fixed with `|| true` to have a final exit code that is 0. * WIP LNE * Debug v23 * Debug v23 * WIP LNE * FIX Bad header name * Fix CSP for ping * Compatibility with multicompany * Debug * Fix include * Fix_massaction_withdraw_control Include pending transfer receipt amounts in bank transfer request validation This code ensures that when creating a new bank transfer request for a supplier invoice, the system also checks for amounts that are already in generated but unprocessed transfer receipts. Summary: The second query ($sqlPending2) retrieves pending amounts from the prelevement_lignes table where the transfer receipt has been created but not yet executed (status = 0 or NULL). This prevents users from requesting a bank transfer that would exceed the invoice total by accounting for: Pending requests not yet included in any transfer receipt Amounts already included in transfer receipts waiting to be processed * FIX phpdoc on createFixedAmountDiscount() (#37212) * FIX phpdoc on createFixedAmountDiscount * FIX phpdoc --------- Co-authored-by: Laurent Destailleur * Fix in card css modal display (#36569) * Fix display of cards in a modal * fix php stan * fix php stan * Try a change to force CI --------- Co-authored-by: Laurent Destailleur * More complete data on pings. * Debug v23 * Debug initdemo * Debug initdemo * Debug initdemo * Debug v23 * Update initdemo * Update initdemo * Cleaner GET call * Add id of perm in url * Init demo for v24 * Fix translation of "various payment" (not english, not pro) with the term used in english to mean "Opérations diverses (OD)" * Sync transifex * CSS * Trans * Doc * Trans * Debug v23 * Debug v23 * Trans * Debug v24 * Debug v23 * Debug v23 * WIP * Debug v23 * Debug v23 * Debug v24 * Work on LNE * WIP LNE * Debug v24 * Doc * Translation * Sync transifex * Debug * Debug * Debug * Responsive * Dev control archive integrity * Debug * Update supplier_proposal.lang (#37238) * add company name on dropdown contract list (#37245) * Clean dump file * Fix CI * FIX #37246 Modifying resteapayer calculation for credit note (#37247) * Add 'type' parameter to completeTabsHead hook (#37235) * #37257 FIX for piesemicircle (#37258) * Fix #37227 Fix #37233 * Fix #37227 Fix #37233 * QUAL French comment in English (#37225) * Edit label of $fields * QUAL French comment in English * Bump actions/upload-artifact from 4 to 6 (#37250) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 6. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v4...v6) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Laurent Destailleur * UI/UX : Transfert feedback css from experimental to core (#37226) * Transfert feedback css from experimental to core * fix php phan * Fix phan * Fix phan * Fix phan * Missing label * Debug * traduction for massaction withdrawal control * Add method to chech if invoice can be replaced * Fix return * Debug v24 * Fix CI * fix commoninvoice.class.php (#37267) * fix commoninvoice.class.php * Update commoninvoice.class.php * CI * CI * Debug v23 * CI * Fix CI * Debug v23 * clean code pdf.lib.php (#37265) * clean code pdf.lib.php * Update pdf.lib.php * Update pdf.lib.php --------- Co-authored-by: Laurent Destailleur * FixCI * FIX: linktoref should be able to receive more than 255 chars (#37262) Co-authored-by: Laurent Destailleur * NEW Increase satement decription to 12 on card payment, 22 on sepa * CI * Restore deleted file * Add $dolibarr_main_restrict_eval_methods to install step1.php (#37268) Since this variable has a significant impact in future versions of Dolibarr, it is preferable that it be directly included in the conf.php file created during installation. Co-authored-by: Laurent Destailleur --------- Signed-off-by: dependabot[bot] Co-authored-by: Laurent Destailleur Co-authored-by: Laurent Destailleur Co-authored-by: Yamil Esteban Garcia <120027058+developmentOYR@users.noreply.github.com> Co-authored-by: Noé Cendrier <81741011+altairis-noe@users.noreply.github.com> Co-authored-by: Frédéric FRANCE Co-authored-by: minimexat Co-authored-by: hansemschnokeloch Co-authored-by: Eric - CAP-REL <1468823+rycks@users.noreply.github.com> Co-authored-by: MDW Co-authored-by: Alexandre SPANGARO Co-authored-by: evarisk-kilyan Co-authored-by: Vanyo Co-authored-by: jeremydassaud <49372108+jeremydassaud@users.noreply.github.com> Co-authored-by: f-hoedl Co-authored-by: Vincent Maury Co-authored-by: vmaury Co-authored-by: Vincent Penel Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Dolibot Co-authored-by: Joris Le Blansch Co-authored-by: intelliking Co-authored-by: Benjamin Falière <121813548+BenjaminFlr@users.noreply.github.com> Co-authored-by: John BOTELLA <68917336+thersane-john@users.noreply.github.com> Co-authored-by: Charlène Benke <1179011+defrance@users.noreply.github.com> Co-authored-by: demiton Co-authored-by: Jyhere Co-authored-by: Delthair <41671350+Delthair@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- htdocs/fourn/facture/list.php | 34 ++++++++++++++++++++++++++++++++-- htdocs/langs/en_US/bills.lang | 1 + htdocs/langs/fr_FR/bills.lang | 1 + 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 3a4e100a982..e094ec390a3 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -420,9 +420,39 @@ if (empty($reshook)) { $numprlv = $db->num_rows($result_sql); } - if ($numprlv > 0) { + // Calculate pending amount to check if more requests can be made + $pending = 0; + // Get pending requests open with no transfer receipt yet + $sqlPending1 = "SELECT SUM(pfd.amount) as amount"; + $sqlPending1 .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pfd"; + $sqlPending1 .= " WHERE pfd.fk_facture_fourn = ".((int) $objecttmp->id); + $sqlPending1 .= " AND pfd.traite = 0"; + $resPending1 = $db->query($sqlPending1); + if ($resPending1) { + $objPending1 = $db->fetch_object($resPending1); + if ($objPending1) { + $pending += (float) $objPending1->amount; + } + } + $db->free($resPending1); + // Get pending request with a transfer receipt generated but not yet processed + $sqlPending2 = "SELECT SUM(pl.amount) as amount"; + $sqlPending2 .= " FROM ".$db->prefix()."prelevement_lignes as pl"; + $sqlPending2 .= " INNER JOIN ".$db->prefix()."prelevement as p ON p.fk_prelevement_lignes = pl.rowid"; + $sqlPending2 .= " WHERE p.fk_facture_fourn = ".((int) $objecttmp->id); + $sqlPending2 .= " AND (pl.statut IS NULL OR pl.statut = 0)"; + $resPending2 = $db->query($sqlPending2); + if ($resPending2) { + if ($objPending2 = $db->fetch_object($resPending2)) { + $pending += (float) $objPending2->amount; + } + } + $db->free($resPending2); + $remaintopaylesspendingdebit = $objecttmp->resteapayer - $pending; + // Check remaining amount (allows multiple partial requests as long as total doesn't exceed invoice amount) + if ($remaintopaylesspendingdebit <= 0) { $error++; - setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings'); + setEventMessages($objecttmp->ref.' '.$langs->trans("AmountRequestedAlreadyReachesTotal"), $objecttmp->errors, 'warnings'); } elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'VIR') { $langs->load("errors"); $error++; diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang index 352802d3b02..cf36e105bfd 100644 --- a/htdocs/langs/en_US/bills.lang +++ b/htdocs/langs/en_US/bills.lang @@ -721,3 +721,4 @@ InvoiceSentFromTemplate=Invoice %s sent from recurring invoice template %s InvoiceSentFromTemplateError=Failed to send invoice %s from recurring invoice template %s : %s BillStatusValidatedWithSendind=Validated (needs to be paid) and sending sendAutoEmailInvoiceKO=Failed to send email from %s to %s +AmountRequestedAlreadyReachesTotal=The amount requested already reaches the total of the invoice diff --git a/htdocs/langs/fr_FR/bills.lang b/htdocs/langs/fr_FR/bills.lang index a2f91b13861..6973f03e94e 100644 --- a/htdocs/langs/fr_FR/bills.lang +++ b/htdocs/langs/fr_FR/bills.lang @@ -715,6 +715,7 @@ DisputeWon=Victoire en litige DisputeClosed=Litige clos Dispute=Différend Sales=Ventes +AmountRequestedAlreadyReachesTotal=Le montant demandé atteint déjà le total de la facture AutoSendEmail=Envoi automatique d'e-mails EmailTemplateForAutoSend=Modèle d'e-mail pour l'envoi automatique InvoiceSentFromTemplate=facture %s envoyé depuis le modèle récurrent facture %s From 3d88e03c88c4301fa1cc4ff18e90217298c56bc8 Mon Sep 17 00:00:00 2001 From: John BOTELLA <68917336+thersane-john@users.noreply.github.com> Date: Mon, 23 Feb 2026 20:11:39 +0100 Subject: [PATCH 05/14] UIUX : Dolibarr js context from experimental to core (#37228) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * NEW Use the js lib into htdocs/public/includes instead of htdocs/includes * New LNE Collect of buisness informations (#37084) * Working LNE ping * remove GPDA * Add of other informations * remove testing var * fix Ci * fix Ci * fix ci * fix CI * Fix Ci * fix Ci --------- Co-authored-by: Lucas Marcouiller * CI * CI * CI * CI * Clean code. File not used. * CSS * CSS * Fix phpunit * More legal info * CI * Fix CI * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Fix: IRPF tax not applied when creating invoice from project times (#37077) * Remove 'supplier_invoice' from old path array * Update module path in arrayforoldpath Sorry Eldy, I was confused. You are absolutely right, it is already corrected. * Replace localtax2 assignment with get_localtax function Error when creating an invoice with personal income tax from project times. The rate does not apply * Refactor localtax1 calculation using get_localtax --------- Co-authored-by: Laurent Destailleur * Protect module * Add currency * CSS * WIP LNE * Fix navigation * cs * Debug registration process * Debug setup navigation * CI * CI * Factorize code * Fix CI * Fix CI * Fix CI * CI * CI * CI * CI * Disable phan on v23 * CI * CI * FIX: missing include for blockedlog lib (#37165) * Debug CI * fix ternary always true (#37161) * fix ternary always true * Update requests.php * Update registration.php --------- Co-authored-by: Laurent Destailleur * CI * FIX: missing include for blockedlog lib (#37165) * FIX #37134 Use json_encode for IMAP search logging in EmailCollector (#37135) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch) as each line becomes a separate log entry. Using json_encode() produces single-line structured output that works correctly with all log aggregation tools. Co-authored-by: Laurent Destailleur * Populate syslog with placeholder (#37163) Co-authored-by: Laurent Destailleur * Doc * datamodel for user change password next time (#37155) * Qual: Update phan baseline (#37172) * Fix typo in file path (#37160) Co-authored-by: Laurent Destailleur * Fix phpunit * Complete call to setStatus so we have a trigy as 4th parameter (help to fix the #37129) * FIX Product - Warning on admin (#37157) Co-authored-by: Laurent Destailleur * FIX Product - Warning on admin + CSS (#37158) * FIX Product - Warning on admin * CSS --------- Co-authored-by: Laurent Destailleur * CI * CI * CI * Avoid error if include fails * More functions in blacklist (even if nw we use the whitelist by default) * #37166 [SQL] add: email template for ticket admin creation (#37182) * Replace var_export with new function formatLogObject (#37178) * FIX BOM - Class product missing, column offset and information recording (form/input overlap) in admin (#37177) * FIX BOM - Class product missing in admin * Fix column offset and information recording (form/input overlap) * ci * ci * FIX Intracommreport - Warning & link problem on tab (#37176) * FIX Bank transfer admin - Warning & save 0 on constant PAYMENTBYBANKTRANSFER_ADDDAYS (#37175) * Look and feel v24 * Update default time handling in index.php (#37150) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix file path comment in supplier invoice module (#37133) Co-authored-by: Laurent Destailleur * Fix CI * Add template in migration * fix phpdoc comment (#37184) * fix phpdoc comment * fix phpdoc comment --------- Co-authored-by: Laurent Destailleur * CI * Fix phpstan * Replace var_export by formatLogObject (continued) (#37188) Co-authored-by: Laurent Destailleur * Debug amount suggested on membership public form * Issue 36923 Fix session title handling in survey creation (#37105) * Issue 36923 Fix session title handling in survey creation * Change input field to use id attribute for title --------- Co-authored-by: Laurent Destailleur * fix phpstan errors blocking action baseline (#37189) * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * fix phpstan errors blocking action baseline * refresh baseline * QUAL Replace var_export() with json_encode() in dol_syslog() calls (#37138) var_export() produces multiline output that breaks log aggregators (Loki, Splunk, Elasticsearch, Graylog) as each line becomes a separate log entry. json_encode() produces single-line structured output that works correctly with all log aggregation tools. This pattern is already used elsewhere in Dolibarr (accountancy, install modules). Files changed: - core/class/commoninvoice.class.php (payment intent logging) - core/class/commonobject.class.php (payment terms logging) - core/modules/mailings/advthirdparties.modules.php (mailing targets) - core/modules/oauth/google_oauthcallback.php (userinfo logging) - core/modules/oauth/generic_oauthcallback.php (userinfo logging) - public/payment/newpayment.php (GET/POST debug logging) - public/payment/paymentok.php (payment tag logging) - public/stripe/ipn.php (Stripe event data logging) - paypal/lib/paypal.lib.php (PayPal response logging) - api/index.php (API debug logging) - stripe/class/stripe.class.php (payment/setup intent logging) Co-authored-by: f-hoedl Co-authored-by: Laurent Destailleur * Fix CI * CI * Check if upload_max_filesize is not empty * clean code * Debug v23 * CI * Fix #33521 VAT total false (#36990) * - Fix #33521 VAT total false - Fix some warnings - Fix : delete $this->vat_rate * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * - Fix #33521 VAT total false - Fix some warnings - Fix :delete $this->tva array (replaced by $this->tva_array) * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php * Update pdf_octopus.modules.php --------- Co-authored-by: vmaury Co-authored-by: Laurent Destailleur * NEW #25829 Automatically send the invoice generated from a template (#36967) * Update DB * ADD email template * Ajout d'une clé de trad * Ajout des traductions * Suppression des traductions, sauf en_US * Add flag auto send * Modif form + cron auto send * Suppression auto_send * correction loopError * ajout du selected au model de mail * Prise en compte default model * Fix pre-commit * ménage * precommit * Correction Phan * Correction Phan * Correction, double cal du trigger --------- Co-authored-by: Laurent Destailleur * Develop force user change pass userclass (#37174) * datamodel for user change password next time * add force_pass_change in user object * Initialize force_pass_change to 0 --------- Co-authored-by: Laurent Destailleur * Another step for #37171 * Qual: Partial phan run on PR's, complete run on integration branches (#37186) * Qual: Partial phan run on PR's, complete on main # Qual: Partial phan run on PR's, complete on main The selection is based on the branch name. To run a complete phan run in a PR, the branch name of the PR must include phan_full. This can help to fix remaining phan issue before re-integrating to the develop branch. * qual: Update workflow and pre-commit configurations - Enable phan workflow by uncommenting the relevant lines - Update actionlint version to v1.7.10 - Add manual stage to actionlint hook in pre-commit-config.yaml * qual: Update Phan analysis conditions The conditions for running Phan analysis have been updated to include an additional check for branches containing 'phan_full'. * qual: Update Phan workflow - Replace github.event.ref with github.ref_name - Add FILE_CHANGE_LIST environment variable for better file handling - Update file list creation and usage in the workflow * qual: Update Phan workflow conditions Fix the branch reference (head_ref in PR, ref_name otherwise) * Add step for debug information * Remove debug step * Fix: Missing initialisations members/new.php Following a suppression of assignments, the variables disabledphy and disabledmor were undefined. * fix: Update budget selection dropdown arguments in member creation form Correct the arguments in the member creation form. * qual: Add cs2pr to phan workflow - Add cs2pr to the tools list in the phan workflow - Change the output mode of phan to checkstyle - Add a step to add results to PR as Github notices - Add a step to provide phan log as artifact * qual: Update Phan workflow to use environment variable for file list The change fixes the Phan workflow to use the environment variable `$FILE_CHANGED_LIST` to clear the file --------- Co-authored-by: Laurent Destailleur * Fix phan * Fix phan * Merge branch '23.0' of git@github.com:Dolibarr/dolibarr.git into 23.0 * Doc * Qual: Fix ambigious redirect error on Phan workflow (#37200) # Qual: Fix ambigious redirect error on Phan workflow Rewrote the shell command that is supposed to suppress a file contents but is flagged by the environment. * PHPStan > Update baseline (#37197) Co-authored-by: Dolibot * Typo fix (#37195) * Debug v23 - filters on agenda pages * css * css * css * qual: Update PHPStan workflow to run on all files in integration (#37207) The PHPStan workflow has been updated to run on all files in integration branches. * Fix CI * Add hook in isEditable() * Debug v23 * CLOSE #37190 ODT Templates for thirdparties - Birthday is returned in epoch format (#37198) Co-authored-by: Laurent Destailleur * fix: Remove HTML from accounting menu tooltips in eldy theme (#37203) Co-authored-by: Laurent Destailleur * Qual: Update spelling (#37199) * Qual: Update spelling for pre-select variants # Qual: Update spelling for pre-select variants In English, preselect is without the hyphen. Update text and made some translations related to preselect. * Qual: Update composant to component and/or adequate translation. # Qual: Update composant to component and/or adequate translation. "Composant(s)" was mostly referenced in french file/class comments. Updated * Qual: Fix misspellings related to "criteria" # Qual: Fix misspellings related to "criteria" * Qual: Fix produt misspellings # Qual: Fix produt misspellings Change 'produt' to 'product'. * Qual: Update French comments with "composants" #Qual: Update French comments with "composants" - Translating French comments to English (avoid codespell notice) * Qual: Fixed typo 'bad practive' to 'bad practice' # Qual: Fixed typo 'bad practive' to 'bad practice' * Qual: Update phan.yml to exclude specific files from analysis - Added file exclusion pattern to match phan configuration - Added check for empty file list to avoid unnecessary phan execution * Qual: Update file filtering in phan.yml workflow The change updates the file filtering process in the phan.yml workflow to correctly redirect the output of the grep command to a temporary file. * Qual: Ignore $systemfunction always exists --------- Co-authored-by: Laurent Destailleur * Error handling methods for commonobject (#37201) * Error handling methods for commonobject (#37201) * NEW Can request and force user to change its password (#37196) * force user to change password : redirect to user card on login * force user to change password : redirect to user card on login * redirect to a dedicated page * bad old idea : self change passwd on user card + edit mode and rights: it makes a hole on security check * only apply on dolibarr auth mode context * only on dolibarr auth mode context * Fix force_pass_change SQL assignment logic --------- Co-authored-by: Laurent Destailleur * Doc * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Setup easier to understand between INVOICE_CHECK_POSTERIOR_DATE and FAC_FORCE_DATE_VALIDATION * Prepare 23.0 * Qual: Ignore exit code from `grep -v` in phan flow (#37213) # Qual: Ignore exit code from `grep -v` in phan flow `grep -v` returns 1 when the resulting filtered list is empty and would stop the execution. This is fixed with `|| true` to have a final exit code that is 0. * WIP LNE * Debug v23 * Debug v23 * WIP LNE * FIX Bad header name * Fix CSP for ping * Compatibility with multicompany * Debug * Fix include * Transfert feedback css from experimental to core * Dolibarr JS context Tools from experiemntal to Core * Fix lang public mode * fix php phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix phan * Fix multi instance of Dolibarr on same Domain * remove french comment * FIX phpdoc on createFixedAmountDiscount() (#37212) * FIX phpdoc on createFixedAmountDiscount * FIX phpdoc --------- Co-authored-by: Laurent Destailleur * Fix path * Fix in card css modal display (#36569) * Fix display of cards in a modal * fix php stan * fix php stan * Try a change to force CI --------- Co-authored-by: Laurent Destailleur * More complete data on pings. * Debug v23 * Debug initdemo * Debug initdemo * Debug initdemo * Debug v23 * Update initdemo * Update initdemo * Cleaner GET call * Add id of perm in url * Init demo for v24 * Fix translation of "various payment" (not english, not pro) with the term used in english to mean "Opérations diverses (OD)" * Sync transifex * CSS * Trans * Doc * Trans * Debug v23 * Debug v23 * Trans * Debug v24 * Debug v23 * Debug v23 * WIP * Debug v23 * Debug v23 * Debug v24 * Work on LNE * WIP LNE * Debug v24 * Doc * Translation * Sync transifex * Debug * Debug * Debug * Responsive * Dev control archive integrity * Debug * Update supplier_proposal.lang (#37238) * add company name on dropdown contract list (#37245) * Clean dump file * Fix CI * FIX #37246 Modifying resteapayer calculation for credit note (#37247) * Add 'type' parameter to completeTabsHead hook (#37235) * #37257 FIX for piesemicircle (#37258) * Fix #37227 Fix #37233 * Fix #37227 Fix #37233 * QUAL French comment in English (#37225) * Edit label of $fields * QUAL French comment in English * Bump actions/upload-artifact from 4 to 6 (#37250) Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 6. - [Release notes](https://github.com/actions/upload-artifact/releases) - [Commits](https://github.com/actions/upload-artifact/compare/v4...v6) --- updated-dependencies: - dependency-name: actions/upload-artifact dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Laurent Destailleur * UI/UX : Transfert feedback css from experimental to core (#37226) * Transfert feedback css from experimental to core * fix php phan * Fix phan * Fix phan * Fix phan * Missing label * Debug * Debug savedemo * Fix mention --------- Signed-off-by: dependabot[bot] Co-authored-by: Laurent Destailleur Co-authored-by: Lucas Marcouiller <45882981+Hystepik@users.noreply.github.com> Co-authored-by: Lucas Marcouiller Co-authored-by: Laurent Destailleur Co-authored-by: Yamil Esteban Garcia <120027058+developmentOYR@users.noreply.github.com> Co-authored-by: Noé Cendrier <81741011+altairis-noe@users.noreply.github.com> Co-authored-by: Frédéric FRANCE Co-authored-by: minimexat Co-authored-by: hansemschnokeloch Co-authored-by: Eric - CAP-REL <1468823+rycks@users.noreply.github.com> Co-authored-by: MDW Co-authored-by: Alexandre SPANGARO Co-authored-by: evarisk-kilyan Co-authored-by: Vanyo Co-authored-by: jeremydassaud <49372108+jeremydassaud@users.noreply.github.com> Co-authored-by: f-hoedl Co-authored-by: Vincent Maury Co-authored-by: vmaury Co-authored-by: Vincent Penel Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Dolibot Co-authored-by: Joris Le Blansch Co-authored-by: intelliking Co-authored-by: Benjamin Falière <121813548+BenjaminFlr@users.noreply.github.com> Co-authored-by: Charlène Benke <1179011+defrance@users.noreply.github.com> Co-authored-by: demiton Co-authored-by: Jyhere Co-authored-by: Delthair <41671350+Delthair@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../tools/ui/class/documentation.class.php | 57 +++++++++---------- .../dolibarr-context/index.php | 29 +++++----- .../dolibarr-context/langs-tool.php | 23 +++----- htdocs/main.inc.php | 38 ++++++++++++- .../dolibarr-context.mock.js | 0 .../dolibarr-context.umd.js | 0 .../dolibarr-tool.langs.js | 24 +++++++- .../dolibarr-tool.seteventmessage.js | 0 .../langs}/langs-tool-interface.php | 8 +-- 9 files changed, 112 insertions(+), 67 deletions(-) rename htdocs/admin/tools/ui/{experimental/experiments => }/dolibarr-context/index.php (96%) rename htdocs/admin/tools/ui/{experimental/experiments => }/dolibarr-context/langs-tool.php (87%) rename htdocs/{admin/tools/ui/experimental/experiments/dolibarr-context/assets => public/includes/dolibarr-js-context}/dolibarr-context.mock.js (100%) rename htdocs/{admin/tools/ui/experimental/experiments/dolibarr-context/assets => public/includes/dolibarr-js-context}/dolibarr-context.umd.js (100%) rename htdocs/{admin/tools/ui/experimental/experiments/dolibarr-context/assets => public/includes/dolibarr-js-context}/dolibarr-tool.langs.js (89%) rename htdocs/{admin/tools/ui/experimental/experiments/dolibarr-context/assets => public/includes/dolibarr-js-context}/dolibarr-tool.seteventmessage.js (100%) rename htdocs/{admin/tools/ui/experimental/experiments/dolibarr-context => public/langs}/langs-tool-interface.php (89%) diff --git a/htdocs/admin/tools/ui/class/documentation.class.php b/htdocs/admin/tools/ui/class/documentation.class.php index aabc27c4724..e79cd369afc 100644 --- a/htdocs/admin/tools/ui/class/documentation.class.php +++ b/htdocs/admin/tools/ui/class/documentation.class.php @@ -236,7 +236,34 @@ class Documentation ) ); - + // Elements + $this->menu['UxDolibarrContext'] = array( + 'url' => dol_buildpath($this->baseUrl.'/dolibarr-context/index.php', 1), + 'icon' => 'fab fa-fort-awesome', + 'submenu' => array( + 'UxDolibarrContextHowItWork' => array( + 'url' => dol_buildpath($this->baseUrl.'/dolibarr-context/index.php', 1), + 'icon' => 'fab fa-fort-awesome', + 'submenu' => array(), + 'summary' => array( + 'Introduction' => '#titlesection-basicusage', + 'ConsoleHelp' => '#titlesection-console-help', + 'JSDolibarrhooks' => '#titlesection-hooks', + 'JSDolibarrhooksReadyVsInit' => '#titlesection-event-init-vs-ready', + 'JSDolibarrAwaitHooks' => '#titlesection-await-hooks', + 'ExampleOfCreatingNewContextTool' => '#titlesection-create-tool-example', + 'SetEventMessageTool' => '#titlesection-tool-seteventmessage', + 'SetAndUseContextVars' => '#titlesection-contextvars', + ), + ), + 'UxDolibarrContextLangsTool' => array( + 'url' => dol_buildpath($this->baseUrl.'/dolibarr-context/langs-tool.php', 1), + 'icon' => 'far fa-flag', + 'submenu' => array(), + 'summary' => array(), + ), + ) + ); // Elements $this->menu['ExperimentalUx'] = array( @@ -253,34 +280,6 @@ class Documentation 'ExperimentalUxContributionTitle' => '#experimental-ux-contribution', ), ), - 'UxDolibarrContext' => array( - 'url' => dol_buildpath($this->baseUrl.'/experimental/experiments/dolibarr-context/index.php', 1), - 'icon' => 'fas fa-flask', - 'submenu' => array( - 'UxDolibarrContextHowItWork' => array( - 'url' => dol_buildpath($this->baseUrl.'/experimental/experiments/dolibarr-context/index.php', 1), - 'icon' => 'fas fa-flask', - 'submenu' => array(), - 'summary' => array( - 'Introduction' => '#titlesection-basicusage', - 'ConsoleHelp' => '#titlesection-console-help', - 'JSDolibarrhooks' => '#titlesection-hooks', - 'JSDolibarrhooksReadyVsInit' => '#titlesection-event-init-vs-ready', - 'JSDolibarrAwaitHooks' => '#titlesection-await-hooks', - 'ExampleOfCreatingNewContextTool' => '#titlesection-create-tool-example', - 'SetEventMessageTool' => '#titlesection-tool-seteventmessage', - 'SetAndUseContextVars' => '#titlesection-contextvars', - ), - ), - 'UxDolibarrContextLangsTool' => array( - 'url' => dol_buildpath($this->baseUrl.'/experimental/experiments/dolibarr-context/langs-tool.php', 1), - 'icon' => 'fas fa-flask', - 'submenu' => array(), - 'summary' => array(), - ), - ), - 'summary' => array(), - ), ) ); diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/index.php b/htdocs/admin/tools/ui/dolibarr-context/index.php similarity index 96% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/index.php rename to htdocs/admin/tools/ui/dolibarr-context/index.php index 2dc299f64ab..c52afe96474 100644 --- a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/index.php +++ b/htdocs/admin/tools/ui/dolibarr-context/index.php @@ -18,7 +18,7 @@ */ // Load Dolibarr environment -require '../../../../../../main.inc.php'; +require '../../../../main.inc.php'; /** * @var DoliDB $db @@ -43,13 +43,10 @@ $documentation = new Documentation($db); $group = 'ExperimentalUx'; $experimentName = 'UxDolibarrContext'; -$experimentAssetsPath = $documentation->baseUrl . '/experimental/experiments/dolibarr-context/assets/'; $js = [ '/includes/ace/src/ace.js', '/includes/ace/src/ext-statusbar.js', '/includes/ace/src/ext-language_tools.js', - $experimentAssetsPath . '/dolibarr-context.umd.js', - $experimentAssetsPath . '/dolibarr-tool.seteventmessage.js', ]; $css = []; @@ -154,7 +151,7 @@ $documentation->showSidebar(); ?> ' Dolibarr.debugMode(false);', '', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); ?>
@@ -205,7 +202,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?>

Practical usage

@@ -247,7 +244,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?> Open your console F12 and click on ', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?>

@@ -403,7 +400,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?> Open your console F12 and click on @@ -469,7 +466,7 @@ $documentation->showSidebar(); ?> '});', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?>

Protected Tools

@@ -488,7 +485,7 @@ $documentation->showSidebar(); ?> ' }', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?>

Reading Tools

@@ -504,7 +501,7 @@ $documentation->showSidebar(); ?> ' if(Dolibarr.checkToolExist(\'Tool name to check\')){/* ... */}else{/* ... */}; ', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?> @@ -551,7 +548,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); ?> + $documentation->showCode($lines, 'php'); ?> ', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); ?> @@ -645,7 +642,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); ?> @@ -660,7 +657,7 @@ $documentation->showSidebar(); ?> ' });', '', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); ?> diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool.php b/htdocs/admin/tools/ui/dolibarr-context/langs-tool.php similarity index 87% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool.php rename to htdocs/admin/tools/ui/dolibarr-context/langs-tool.php index 696ed2e48a6..d8e571983d6 100644 --- a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool.php +++ b/htdocs/admin/tools/ui/dolibarr-context/langs-tool.php @@ -18,7 +18,7 @@ */ // Load Dolibarr environment -require '../../../../../../main.inc.php'; +require '../../../../main.inc.php'; /** * @var DoliDB $db @@ -43,14 +43,11 @@ $documentation = new Documentation($db); $group = 'ExperimentalUx'; $experimentName = 'UxDolibarrContextLangsTool'; -$experimentAssetsPath = $documentation->baseUrl . '/experimental/experiments/dolibarr-context/assets/'; +$experimentAssetsPath = dolBuildUrl('/public/includes/dolibarr-js-context'); $js = [ '/includes/ace/src/ace.js', '/includes/ace/src/ext-statusbar.js', - '/includes/ace/src/ext-language_tools.js', - $experimentAssetsPath . '/dolibarr-context.umd.js', - $experimentAssetsPath . '/dolibarr-tool.langs.js', - $experimentAssetsPath . '/dolibarr-tool.seteventmessage.js', + '/includes/ace/src/ext-language_tools.js' ]; $css = []; @@ -62,13 +59,7 @@ $documentation->view = [$group, 'UxDolibarrContext', $experimentName]; // Output sidebar $documentation->showSidebar(); ?> - +
showBreadCrumb(); ?> @@ -107,11 +98,11 @@ $documentation->showSidebar(); ?> 'Dolibarr.setContextVars( DOL_VERSION,', ' \'MAIN_LANG_DEFAULT\' => $langs->getDefaultLang(),', - ' \'DOL_LANG_INTERFACE_URL\' => dol_buildpath(\'admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool-interface.php\',1),', + ' \'DOL_LANG_INTERFACE_URL\' => dol_buildpath(\'public/langs/langs-tool-interface.php\', 1),', ']) ?>);', '', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); ?>
@@ -171,7 +162,7 @@ $documentation->showSidebar(); ?> '});', '', ); - echo $documentation->showCode($lines, 'php'); + $documentation->showCode($lines, 'php'); print implode("\n", $lines); ?> diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 3189c8246ea..8a57776ff94 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -45,7 +45,7 @@ // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined. $micro_start_time = 0; // Used as global var into printCommonFooter() if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO'])) { - list($usec, $sec) = explode(" ", microtime()); + [$usec, $sec] = explode(" ", microtime()); $micro_start_time = ((float) $usec + (float) $sec); // Add Xdebug code coverage //define('XDEBUGCOVERAGE',1); @@ -1814,6 +1814,42 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr $themeparam .= '&THEME_SATURATE_RATIO='.GETPOSTINT('THEME_SATURATE_RATIO'); } + + /** + * ==================================== + * DEFINE DOLIBARR JS CONTEXT AND TOOLS + * ==================================== + * see Documentation at admin/tools/ui/dolibarr-context/index.php + */ + $jsContextVars = [ + 'DOL_VERSION' => DOL_VERSION, + 'DOL_URL_ROOT' => DOL_URL_ROOT, + ]; + + $jsContextPathUrl = DOL_URL_ROOT . '/public/includes/dolibarr-js-context'; + $jsContextFiles = [ + 'dolibarr-context.umd.js', // The js Dolibarr context definition + 'dolibarr-tool.seteventmessage.js' // The first tools to help dev for easy event in js + ]; + + if (! defined('NOREQUIRETRAN')) { + // Langs tool see Documentation at admin/tools/ui/dolibarr-context/index.php + $jsContextFiles[] = 'dolibarr-tool.langs.js'; + $jsContextVars['MAIN_LANG_DEFAULT'] = $langs->getDefaultLang();// For langs tool + $jsContextVars['DOL_LANG_INTERFACE_URL'] = dol_buildpath('public/langs/langs-tool-interface.php', 1);// For langs tool + } + + // Load context and all js tools + foreach ($jsContextFiles as $jsContextFile) { + print ''."\n"; + } + + // DEFINE FIRST NEEDED JS CONTEXT VARS + print ''."\n"; + + // -- END OF DEFINITION OF DOLIBARR JS CONTEXT AND TOOLS + + if (getDolGlobalString('MAIN_ENABLE_FONT_ROBOTO')) { print ''."\n"; print ''."\n"; diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-context.mock.js b/htdocs/public/includes/dolibarr-js-context/dolibarr-context.mock.js similarity index 100% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-context.mock.js rename to htdocs/public/includes/dolibarr-js-context/dolibarr-context.mock.js diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-context.umd.js b/htdocs/public/includes/dolibarr-js-context/dolibarr-context.umd.js similarity index 100% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-context.umd.js rename to htdocs/public/includes/dolibarr-js-context/dolibarr-context.umd.js diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-tool.langs.js b/htdocs/public/includes/dolibarr-js-context/dolibarr-tool.langs.js similarity index 89% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-tool.langs.js rename to htdocs/public/includes/dolibarr-js-context/dolibarr-tool.langs.js index adeefc27ddb..becfdff5f32 100644 --- a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-tool.langs.js +++ b/htdocs/public/includes/dolibarr-js-context/dolibarr-tool.langs.js @@ -24,8 +24,14 @@ document.addEventListener('Dolibarr:Init', function(e) { * @returns {Promise} */ async function openDB() { + + // Generate a unique name per instance + const path = Dolibarr.getContextVar('DOL_URL_ROOT'); // or a unique Dolibarr identifier if available + const hashedPath = await hashString(path); + const dbName = `DolibarrLangs_${hashedPath}`; + return new Promise((resolve, reject) => { - const request = indexedDB.open('DolibarrLangs', 1); + const request = indexedDB.open(dbName, 1); request.onupgradeneeded = e => { const db = e.target.result; if (!db.objectStoreNames.contains('langs')) db.createObjectStore('langs'); @@ -35,6 +41,22 @@ document.addEventListener('Dolibarr:Init', function(e) { }); } + // Create a secure DB name + async function getSafeDbName() { + const path = window.location.pathname; + const hashedPath = await hashString(path); + return `DolibarrLangs_${hashedPath}`; + } + + // Simple function to generate a hash from a string + async function hashString(str) { + const encoder = new TextEncoder(); + const data = encoder.encode(str); + const hashBuffer = await crypto.subtle.digest('SHA-1', data); + const hashArray = Array.from(new Uint8Array(hashBuffer)); + return hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); + } + /** * Get cached translation for a domain + locale * @param {string} domain diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-tool.seteventmessage.js b/htdocs/public/includes/dolibarr-js-context/dolibarr-tool.seteventmessage.js similarity index 100% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/assets/dolibarr-tool.seteventmessage.js rename to htdocs/public/includes/dolibarr-js-context/dolibarr-tool.seteventmessage.js diff --git a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool-interface.php b/htdocs/public/langs/langs-tool-interface.php similarity index 89% rename from htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool-interface.php rename to htdocs/public/langs/langs-tool-interface.php index 2404220fc31..179c9f04fc2 100644 --- a/htdocs/admin/tools/ui/experimental/experiments/dolibarr-context/langs-tool-interface.php +++ b/htdocs/public/langs/langs-tool-interface.php @@ -17,17 +17,17 @@ */ //if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db -//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs //if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters //if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters -//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) +if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) //if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu //if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php //if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -//if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. +if (! defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session). This include the NOIPCHECK too. //if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip //if (! defined("MAIN_LANG_DEFAULT")) define('MAIN_LANG_DEFAULT', 'auto'); // Force lang to a particular value //if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler @@ -36,7 +36,7 @@ if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // I // Load Dolibarr environment -require '../../../../../../main.inc.php'; +require '../../main.inc.php'; /** From ff146c471323122ff2b97c7f549971b749cbe7e3 Mon Sep 17 00:00:00 2001 From: Eric - CAP-REL <1468823+rycks@users.noreply.github.com> Date: Mon, 23 Feb 2026 20:12:44 +0100 Subject: [PATCH 06/14] handle race condition user with no right - prevent infinite loop (#37220) --- htdocs/langs/en_US/errors.lang | 1 + htdocs/user/card.php | 31 ++++++++++++++++++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang index e6b74e2d5bd..14ac4a79e3f 100644 --- a/htdocs/langs/en_US/errors.lang +++ b/htdocs/langs/en_US/errors.lang @@ -467,3 +467,4 @@ SomeShipmentExists=Error, there is some shipment linked to the order. Deletion r WarningEvaluationEmptyValidate=Can't validate evaluation, levels on skills not defined ErrorBadParametersForDirectDebitFileCreate=Can't create bank transfer file: expected format parameter is not provided. ErrorBadParametersForDirectDebitFileCreateDids=Can't create bank transfer file: IDs of existing payment requests are not provided. +UserDoesNotHaveRightsToChangeHisPassword=That user doesn't have the rights to change his own password diff --git a/htdocs/user/card.php b/htdocs/user/card.php index 56cbebb1175..4078819a665 100644 --- a/htdocs/user/card.php +++ b/htdocs/user/card.php @@ -1222,7 +1222,12 @@ if ($action == 'create' || $action == 'adduserldap') { if ($_SESSION["dol_authmode"] == 'dolibarr') { print ''.$langs->trans("ForcePasswordChange").''; print ''; - print ''; + if ($object->hasRight('user', 'self', 'password')) { + print ''; + } else { + print ''; + print $langs->trans("UserDoesNotHaveRightsToChangeHisPassword"); + } print ''; print "\n"; } @@ -2025,10 +2030,15 @@ if ($action == 'create' || $action == 'adduserldap') { if ($_SESSION["dol_authmode"] == 'dolibarr') { print ''.$langs->trans("ForcePasswordChange").''; print ''; - if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) { - print 'force_pass_change ? ' checked="checked"' : '').'>'; + if ($object->hasRight('user', 'self', 'password')) { + if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') < 2) { + print 'force_pass_change ? ' checked="checked"' : '').'>'; + } else { + print yn($object->force_pass_change); + } } else { - print yn($object->force_pass_change); + print ''; + print $langs->trans("UserDoesNotHaveRightsToChangeHisPassword"); } print ''; print "\n"; @@ -2714,11 +2724,18 @@ if ($action == 'create' || $action == 'adduserldap') { if ($_SESSION["dol_authmode"] == 'dolibarr') { print ''; print ''.$form->editfieldkey('ForcePasswordChange', 'forcepasswordchange', '', $object, 0).''; - if ($permissiontoedit) { - print 'force_pass_change ? ' checked="checked"' : '').'>'; + + if ($object->hasRight('user', 'self', 'password')) { + if ($permissiontoedit) { + print 'force_pass_change ? ' checked="checked"' : '').'>'; + } else { + print 'force_pass_change ? ' checked="checked"' : '').'>'; + } } else { - print 'force_pass_change ? ' checked="checked"' : '').'>'; + print ''; + print $langs->trans("UserDoesNotHaveRightsToChangeHisPassword"); } + print ''; } From a70547281197d9847618eb5b352be43eecbaa716 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 24 Feb 2026 14:16:34 +0100 Subject: [PATCH 07/14] Add usleep --- htdocs/blockedlog/lib/blockedlog.lib.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/blockedlog/lib/blockedlog.lib.php b/htdocs/blockedlog/lib/blockedlog.lib.php index a29815486b6..3c1a744d776 100644 --- a/htdocs/blockedlog/lib/blockedlog.lib.php +++ b/htdocs/blockedlog/lib/blockedlog.lib.php @@ -426,6 +426,7 @@ function callApiToPushCounter($id, $signature, $test, $previousid, $previoussign include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; try { $tmpresult = getURLContent($url_for_ping, 'POST', $data, 1, $addheaders, array('https'), 0, -1, $timeoutconnect, $timeoutresponse, array(), '_dolibarrpushcounter'); + usleep(1000); // Add a warning in log in case of error if ($tmpresult['http_code'] != 200) { From 36b07475dc1c3d93308372901b12b8ae16f80e9e Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Tue, 24 Feb 2026 17:30:44 +0100 Subject: [PATCH 08/14] Typo (#37326) --- htdocs/langs/en_US/companies.lang | 2 +- htdocs/societe/card.php | 6 +++--- htdocs/societe/class/societe.class.php | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/langs/en_US/companies.lang b/htdocs/langs/en_US/companies.lang index ba066b9b9de..9fcda8b5a2d 100644 --- a/htdocs/langs/en_US/companies.lang +++ b/htdocs/langs/en_US/companies.lang @@ -351,7 +351,7 @@ VATIntraManualCheck=You can also check manually on the European Commission websi ErrorVATCheckMS_UNAVAILABLE=Check not possible. Check service is not provided by the member state (%s). NorProspectNorCustomer=Not prospect, nor customer JuridicalStatus=Business entity type -CompnanyBirthDate=Εstablishment date of company +CompanyBirthDate=Establishment date of company Workforce=Workforce Staff=Employees ProspectLevelShort=Potential diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 3820ccbff53..7b54fa4819c 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -1917,7 +1917,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($canvasdisplayactio print ''; // Date birth - print ''.$form->editfieldkey('CompnanyBirthDate', 'birth', '', $object, 0).''; + print ''.$form->editfieldkey('CompanyBirthDate', 'birth', '', $object, 0).''; print ''; print $form->selectDate($object->birth, 'birth', 0, 0, 1, "", 1); print ''; @@ -2792,7 +2792,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($canvasdisplayactio print ''; // Date birth - print ''.$form->editfieldkey('CompnanyBirthDate', 'birth', '', $object, 0).''; + print ''.$form->editfieldkey('CompanyBirthDate', 'birth', '', $object, 0).''; print ''; print $form->selectDate($object->birth, 'birth', 0, 0, 1, "", 1); print ''; @@ -3328,7 +3328,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($canvasdisplayactio print ''.$langs->trans('JuridicalStatus').''.dolPrintHTML($object->forme_juridique).''; // Date birth - print ''.$langs->trans('CompnanyBirthDate').''.dol_print_date($object->birth).''; + print ''.$langs->trans('CompanyBirthDate').''.dol_print_date($object->birth).''; // Capital print ''.$langs->trans('Capital').''; diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index b117fe625fd..40478415920 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -209,7 +209,7 @@ class Societe extends CommonObject 'fk_effectif' => array('type' => 'integer', 'label' => 'Workforce', 'enabled' => 1, 'visible' => -1, 'position' => 170), 'fk_typent' => array('type' => 'integer', 'label' => 'ThirdPartyType', 'enabled' => 1, 'visible' => -1, 'position' => 175, 'csslist' => 'minwidth200'), 'fk_forme_juridique' => array('type' => 'integer', 'label' => 'JuridicalStatus', 'enabled' => 1, 'visible' => -1, 'position' => 180), - 'birth' => array('type' => 'date', 'label' => 'CompnanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182), + 'birth' => array('type' => 'date', 'label' => 'CompanyBirthDate', 'enabled' => 1, 'visible' => -1, 'position' => 182), 'fk_currency' => array('type' => 'varchar(3)', 'label' => 'Currency', 'enabled' => 1, 'visible' => -1, 'position' => 185), 'siren' => array('type' => 'varchar(128)', 'label' => 'Idprof1', 'enabled' => 1, 'visible' => -1, 'position' => 190), 'siret' => array('type' => 'varchar(128)', 'label' => 'Idprof2', 'enabled' => 1, 'visible' => -1, 'position' => 195), From bb8285cb4d2fbebc8e12a9ef35356c98d768b6b5 Mon Sep 17 00:00:00 2001 From: Ahmed Galadima <36524318+glimz@users.noreply.github.com> Date: Tue, 24 Feb 2026 17:32:46 +0100 Subject: [PATCH 09/14] Fix recruitment API candidature creation validation (#37331) Signed-off-by: Ahmed Galadima Co-authored-by: Ahmed Galadima --- .../class/api_recruitments.class.php | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/htdocs/recruitment/class/api_recruitments.class.php b/htdocs/recruitment/class/api_recruitments.class.php index 1acf80676d7..0b32a2fdfed 100644 --- a/htdocs/recruitment/class/api_recruitments.class.php +++ b/htdocs/recruitment/class/api_recruitments.class.php @@ -375,7 +375,7 @@ class Recruitments extends DolibarrApi } // Check mandatory fields - $result = $this->_validate($request_data); + $result = $this->_validate($request_data, $this->jobposition); foreach ($request_data as $field => $value) { if ($field === 'caller') { @@ -415,16 +415,16 @@ class Recruitments extends DolibarrApi } // Check mandatory fields - $result = $this->_validate($request_data); + $result = $this->_validate($request_data, $this->candidature); foreach ($request_data as $field => $value) { if ($field === 'caller') { // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller - $this->jobposition->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09'); + $this->candidature->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09'); continue; } - $this->jobposition->$field = $this->_checkValForAPI($field, $value, $this->jobposition); + $this->candidature->$field = $this->_checkValForAPI($field, $value, $this->candidature); } // Clean data @@ -686,25 +686,26 @@ class Recruitments extends DolibarrApi * Validate fields before create or update object * * @param ?array $data Array of data to validate + * @param CommonObject $object Object to validate against * @return array * * @throws RestException */ - private function _validate($data) + private function _validate($data, $object) { if ($data === null) { $data = array(); } - $jobposition = array(); - foreach ($this->jobposition->fields as $field => $propfield) { - if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || empty($propfield['notnull']) || $propfield['notnull'] != 1) { - continue; // Not a mandatory field + $result = array(); + foreach ($object->fields as $field => $propfield) { + if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat', 'ref')) || empty($propfield['notnull']) || $propfield['notnull'] != 1 || !empty($propfield['noteditable']) || isset($propfield['default'])) { + continue; // Not a mandatory field or auto-generated field or has default value } if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); } - $jobposition[$field] = $data[$field]; + $result[$field] = $data[$field]; } - return $jobposition; + return $result; } } From 84e509394cb4e83f1599b90768292f15166eb79c Mon Sep 17 00:00:00 2001 From: MDW Date: Tue, 24 Feb 2026 17:35:35 +0100 Subject: [PATCH 10/14] Fix: CI (#37324) * Fix: key is never 'PAYMENT_CUSTOMER_CREATE' * Fix: Update include path and formatting - Update include path for versionmod.inc.php - Apply code formatting * Qual: Ignore phpstan notice # Qual: Ignore phpstan notice - Country code is already FR, but test can be useful in the future, so ignoring the notice. - Code formatting * Qual: Try exact match to suppress phpstan notice # Qual: Try exact match to suppress phpstan notice --- htdocs/blockedlog/admin/blockedlog_list.php | 28 ++++++-------- htdocs/blockedlog/admin/registration.php | 42 +++++++++++---------- htdocs/blockedlog/ajax/block-info.php | 4 +- htdocs/core/modules/modBlockedLog.class.php | 33 ++++++++-------- 4 files changed, 53 insertions(+), 54 deletions(-) diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index f225a46d1eb..e69f0c84617 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -2,7 +2,7 @@ /* Copyright (C) 2017 ATM Consulting * Copyright (C) 2017-2018 Laurent Destailleur * Copyright (C) 2018-2025 Frédéric France - * Copyright (C) 2024-2025 MDW + * Copyright (C) 2024-2026 MDW * Copyright (C) 2024 Alexandre Spangaro * * This program is free software; you can redistribute it and/or modify @@ -652,25 +652,21 @@ if (is_array($blocks)) { $totaltoshow += $value; } - if ($key == 'PAYMENT_CUSTOMER_CREATE') { - print $langs->trans("Total").': '; - print price($totaltoshow); - } else { - print $langs->trans("HT").': '; - print price($totalhttoshow); + print $langs->trans("HT").': '; + print price($totalhttoshow); - //print '
'; - print '   '; + //print '
'; + print '   '; - print $langs->trans("VAT").': '; - print price($totalvattoshow); + print $langs->trans("VAT").': '; + print price($totalvattoshow); - //print '
'; - print '   '; + //print '
'; + print '   '; + + print $langs->trans("TTC").': '; + print price($totaltoshow); - print $langs->trans("TTC").': '; - print price($totaltoshow); - } print ''; // Details link diff --git a/htdocs/blockedlog/admin/registration.php b/htdocs/blockedlog/admin/registration.php index 6628b3cb3da..2eccee308b7 100644 --- a/htdocs/blockedlog/admin/registration.php +++ b/htdocs/blockedlog/admin/registration.php @@ -2,6 +2,7 @@ /* Copyright (C) 2017 ATM Consulting * Copyright (C) 2017-2018 Laurent Destailleur * Copyright (C) 2024 Frédéric France + * Copyright (C) 2026 MDW * * 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 @@ -115,69 +116,69 @@ if ($action == 'update') { //Company $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_NAME", $company_name, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_EMAIL", $company_email, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_COUNTRY_CODE", $company_country_code, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_IDPROF1", $company_idprof1, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_ADDRESS", $company_address, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_STATE", $company_state, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_ZIP", $company_zip, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "BLOCKEDLOG_REGISTRATION_TOWN", $company_town, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } //IT Provider $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_NAME", $provider_name, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_MAIL", $provider_email, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_COUNTRY", $provider_country_id, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_IDPROF1", $provider_idprof1, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_ADDRESS", $provider_address, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_STATE", $provider_state, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_ZIP", $provider_zip, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } $res = dolibarr_set_const($db, "MAIN_INFO_ITPROVIDER_TOWN", $provider_town, 'chaine', 0, '', $conf->entity); if ($res <= 0) { - $error ++; + $error++; } } if (!$error) { @@ -185,7 +186,7 @@ if ($action == 'update') { //setEventMessages("SetupSaved", null, 'mesgs'); $urltouse = $_SERVER["PHP_SELF"]."?mode=forceregistration"; - $urltouse .= (($withtab && GETPOST('origin')) ? '&withtab='.$withtab: ''); + $urltouse .= (($withtab && GETPOST('origin')) ? '&withtab='.$withtab : ''); $urltouse .= (GETPOST('origin') ? '&origin='.GETPOST('origin') : ''); header("Location: ".$urltouse); @@ -212,14 +213,14 @@ if (GETPOST('withtab', 'alpha')) { $title = $langs->trans("BrowseBlockedLog"); } -$help_url="EN:Module_Unalterable_Archives_-_Logs|FR:Module_Archives_-_Logs_Inaltérable"; +$help_url = "EN:Module_Unalterable_Archives_-_Logs|FR:Module_Archives_-_Logs_Inaltérable"; llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-blockedlog page-admin_blockedlog'); if (GETPOST('withtab', 'alpha')) { $linkback = ''.img_picto($langs->trans("BackToModuleList"), 'back', 'class="pictofixedwidth"').''.$langs->trans("BackToModuleList").''; } else { - $linkback=''; + $linkback = ''; } $morehtmlcenter = ''; @@ -290,7 +291,8 @@ if (in_array($mysoc->country_code, array('FR'))) { print info_admin($htmltext, 0, 0, $color); $htmltext = ''; - if ($mysoc->country_code == 'FR') { + // @phpstan-ignore-next-line Country code is already FR because of in_array('FR') test above + if ($mysoc->country_code === 'FR') { $htmltext .= $langs->trans("UnalterableLogTool1FR").'
'; } diff --git a/htdocs/blockedlog/ajax/block-info.php b/htdocs/blockedlog/ajax/block-info.php index 380a595b6ae..62385f80eed 100644 --- a/htdocs/blockedlog/ajax/block-info.php +++ b/htdocs/blockedlog/ajax/block-info.php @@ -2,7 +2,7 @@ /* Copyright (C) 2017 Laurent Destailleur * Copyright (C) 2017 ATM Consulting * Copyright (C) 2024-2025 Frédéric France - * Copyright (C) 2024 MDW + * Copyright (C) 2024-2026 MDW * * 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 @@ -239,7 +239,7 @@ function formatObject($objtoshow, $prefix, $parentelement = '') } } if (empty($label) && !empty($otherlabels[$key])) { - if (preg_match('/^invoiceline/', $prefix) && $key == 'ref') { + if (preg_match('/^invoiceline/', $prefix) && $key === 'ref') { $label = $langs->trans("ProductRef"); } else { $label = $langs->trans($otherlabels[$key]); diff --git a/htdocs/core/modules/modBlockedLog.class.php b/htdocs/core/modules/modBlockedLog.class.php index 93a70125851..a52318fee02 100644 --- a/htdocs/core/modules/modBlockedLog.class.php +++ b/htdocs/core/modules/modBlockedLog.class.php @@ -1,5 +1,6 @@ + * Copyright (C) 2026 MDW * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -24,7 +25,7 @@ */ include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; include_once DOL_DOCUMENT_ROOT.'/blockedlog/lib/blockedlog.lib.php'; -include_once DOL_DOCUMENT_ROOT.'/versionmod.inc.php'; +include_once DOL_DOCUMENT_ROOT.'/blockedlog/versionmod.inc.php'; /** @@ -73,14 +74,14 @@ class modBlockedLog extends DolibarrModules // Dependencies //------------- $this->hidden = false; // A condition to disable module - $this->depends = array('always'=>'modFacture'); // List of modules id that must be enabled if this module is enabled + $this->depends = array('always' => 'modFacture'); // List of modules id that must be enabled if this module is enabled $this->requiredby = array(); // List of modules id to disable if this one is disabled $this->conflictwith = array(); // List of modules id this module is in conflict with $this->langfiles = array('blockedlog'); $this->warnings_activation = array(); $this->warnings_activation_ext = array(); - $this->warnings_unactivation = array('FR'=>'BlockedLogAreRequiredByYourCountryLegislation'); + $this->warnings_unactivation = array('FR' => 'BlockedLogAreRequiredByYourCountryLegislation'); // Currently, activation is not automatic because only companies (in France) making invoices to non business customers must // enable this module. @@ -102,7 +103,7 @@ class modBlockedLog extends DolibarrModules // Constants //----------- $this->const = array( - 1=>array('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY', 'chaine', 'FR', 'This is list of country code where the module may be mandatory', 0, 'current', 0) + 1 => array('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY', 'chaine', 'FR', 'This is list of country code where the module may be mandatory', 0, 'current', 0) ); // New pages on tabs @@ -128,19 +129,19 @@ class modBlockedLog extends DolibarrModules // ----------------- $r = 0; $this->menu[$r] = array( - 'fk_menu'=>'fk_mainmenu=tools', // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode - 'mainmenu'=>'tools', - 'leftmenu'=>'blockedlogbrowser', - 'type'=>'left', // This is a Left menu entry - 'titre'=>'BrowseBlockedLog', + 'fk_menu' => 'fk_mainmenu=tools', // Use 'fk_mainmenu=xxx' or 'fk_mainmenu=xxx,fk_leftmenu=yyy' where xxx is mainmenucode and yyy is a leftmenucode + 'mainmenu' => 'tools', + 'leftmenu' => 'blockedlogbrowser', + 'type' => 'left', // This is a Left menu entry + 'titre' => 'BrowseBlockedLog', 'prefix' => img_picto('', $this->picto, 'class="paddingright pictofixedwidth"'), - 'url'=>'/blockedlog/admin/blockedlog_list.php?mainmenu=tools&leftmenu=blockedlogbrowser', - 'langs'=>'blockedlog', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. - 'position'=>200, - 'enabled'=>'isModEnabled("blockedlog")', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. - 'perms'=>'$user->hasRight("blockedlog", "read")', // Use 'perms'=>'$user->hasRight("mymodule","level1","level2")' if you want your menu with a permission rules - 'target'=>'', - 'user'=>2, // 0=Menu for internal users, 1=external users, 2=both + 'url' => '/blockedlog/admin/blockedlog_list.php?mainmenu=tools&leftmenu=blockedlogbrowser', + 'langs' => 'blockedlog', // Lang file to use (without .lang) by module. File must be in langs/code_CODE/ directory. + 'position' => 200, + 'enabled' => 'isModEnabled("blockedlog")', // Define condition to show or hide menu entry. Use '$conf->mymodule->enabled' if entry must be visible if module is enabled. Use '$leftmenu==\'system\'' to show if leftmenu system is selected. + 'perms' => '$user->hasRight("blockedlog", "read")', // Use 'perms'=>'$user->hasRight("mymodule","level1","level2")' if you want your menu with a permission rules + 'target' => '', + 'user' => 2, // 0=Menu for internal users, 1=external users, 2=both ); $r++; } From 65516a3f9952c3dbdb36cd7c441335f3572db3b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Charl=C3=A8ne=20Benke?= <1179011+defrance@users.noreply.github.com> Date: Tue, 24 Feb 2026 17:41:12 +0100 Subject: [PATCH 11/14] Refactor notification type handling in card.php (#37321) * Refactor notification type handling in card.php we have email and sms feature but it seems that sms is not well manager Furthermore, it's not possible to manage other notifications (on a smartphone app, for example). Ideally, this should be put in a dictionary. * Initialize num variable before query execution * Update card.php --- htdocs/user/notify/card.php | 39 ++++++++++++++----------------------- 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/htdocs/user/notify/card.php b/htdocs/user/notify/card.php index 14742c13239..3e40c0b0bd5 100644 --- a/htdocs/user/notify/card.php +++ b/htdocs/user/notify/card.php @@ -1,11 +1,12 @@ - * Copyright (C) 2004-2014 Laurent Destailleur - * Copyright (C) 2010-2014 Juanjo Menent - * Copyright (C) 2015 Marcos García - * Copyright (C) 2016 Abbes Bahfir - * Copyright (C) 2024-2025 Frédéric France - * Copyright (C) 2024 MDW +/* Copyright (C) 2003 Rodolphe Quiedeville + * Copyright (C) 2004-2014 Laurent Destailleur + * Copyright (C) 2010-2014 Juanjo Menent + * Copyright (C) 2015 Marcos García + * Copyright (C) 2016 Abbes Bahfir + * Copyright (C) 2024-2025 Frédéric France + * Copyright (C) 2024 MDW + * Copyright (C) 2026 Charlene Benke * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -159,7 +160,7 @@ if (getDolGlobalString('MAIN_HTML_TITLE') && preg_match('/thirdpartynameonly/', $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-user page-notify_card'); - +$type = array('email' => $langs->trans("EMail"), 'sms' => $langs->trans("SMS")); if ($result > 0) { $langs->load("other"); @@ -252,6 +253,7 @@ if ($result > 0) { $sql .= " AND n.entity IN (".getEntity('notify_def').')'; $resql = $db->query($sql); + $num = 0; if ($resql) { $num = $db->num_rows($resql); } else { @@ -305,7 +307,6 @@ if ($result > 0) { print img_picto('', 'object_action', '', 0, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1); print ''; print ''; - $type = array('email' => $langs->trans("EMail")); print $form->selectarray("typeid", $type); print ''; print ''; @@ -354,12 +355,7 @@ if ($result > 0) { print ''; print ''; - if ($obj->type == 'email') { - print $langs->trans("Email"); - } - if ($obj->type == 'sms') { - print $langs->trans("SMS"); - } + print $type[$obj->type]; print ''; print ''.img_delete().''; print ''; @@ -460,9 +456,9 @@ if ($result > 0) { } print '
'; - if (isset($optioncss) && $optioncss != '') { - print ''; - } + //if (isset($optioncss) && $optioncss != '') { + // print ''; + //} print ''; print ''; print ''; @@ -516,12 +512,7 @@ if ($result > 0) { print img_picto('', 'object_action', '', 0, 0, 0, '', 'pictofixedwidth').$label; print ''; print ''; - if ($obj->type == 'email') { - print $langs->trans("Email"); - } - if ($obj->type == 'sms') { - print $langs->trans("Sms"); - } + print $type[$obj->type]; print ''; // TODO Add link to object here for other types /*print ''; From a7a5e211c21872215a74989eeede208fa9b97de3 Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Tue, 24 Feb 2026 17:50:20 +0100 Subject: [PATCH 12/14] NEW Accountancy - Transaction template system (#37286) * NEW Accountancy - Transaction template system * CI * CI * CI * CI * CI --------- Co-authored-by: Laurent Destailleur --- htdocs/accountancy/admin/template/card.php | 651 ++++++++++++++++ htdocs/accountancy/admin/template/list.php | 701 ++++++++++++++++++ htdocs/accountancy/bookkeeping/card.php | 125 +++- .../class/bookkeepingtemplate.class.php | 561 ++++++++++++++ .../class/bookkeepingtemplateline.class.php | 368 +++++++++ htdocs/core/lib/accounting.lib.php | 27 +- htdocs/core/menus/init_menu_auguria.sql | 3 +- htdocs/core/menus/standard/eldy.lib.php | 11 +- htdocs/langs/en_US/accountancy.lang | 21 +- 9 files changed, 2447 insertions(+), 21 deletions(-) create mode 100644 htdocs/accountancy/admin/template/card.php create mode 100644 htdocs/accountancy/admin/template/list.php create mode 100644 htdocs/accountancy/class/bookkeepingtemplate.class.php create mode 100644 htdocs/accountancy/class/bookkeepingtemplateline.class.php diff --git a/htdocs/accountancy/admin/template/card.php b/htdocs/accountancy/admin/template/card.php new file mode 100644 index 00000000000..d6bd5e6c8f6 --- /dev/null +++ b/htdocs/accountancy/admin/template/card.php @@ -0,0 +1,651 @@ + + * + * 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 accountancy/admin/template/card.php + * \ingroup accountancy + * \brief Page to create/edit/view bookkeeping template + */ + +// Load Dolibarr environment +require '../../../main.inc.php'; +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php'; +require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/accountingaccount.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeepingtemplate.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeepingtemplateline.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("accountancy", "other")); + +// Set needed objects +$accountingaccount = new AccountingAccount($db); +$formaccounting = new FormAccounting($db); + +// Get parameters +$id = GETPOST('id', 'int'); +$code = GETPOST('code', 'alpha'); +$lineid = GETPOSTINT('lineid'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'bookkeepingtemplatecard'; +$backtopage = GETPOST('backtopage', 'alpha'); +$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); + +// Initialize technical objects +$object = new BookkeepingTemplate($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->accounting->dir_output . '/temp/massgeneration/' . $user->id; +$hookmanager->initHooks(array($object->element . 'card', 'globalcard')); + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Initialize array of search criteria +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_' . $key, 'alpha')) { + $search[$key] = GETPOST('search_' . $key, 'alpha'); + } +} + +if (empty($action) && empty($id) && empty($code)) { + $action = 'view'; +} + +// Load object +include DOL_DOCUMENT_ROOT . '/core/actions_fetchobject.inc.php'; + +if ($id > 0 && empty($object->id)) { + dol_print_error($db, 'Failed to load object'); +} + +// Security check +$permissiontoread = $user->hasRight('accounting', 'chartofaccount'); +$permissiontoadd = $user->hasRight('accounting', 'chartofaccount'); +$permissiontodelete = $user->hasRight('accounting', 'chartofaccount'); +$permissionnote = $user->hasRight('accounting', 'chartofaccount'); +$permissiondellink = $user->hasRight('accounting', 'chartofaccount'); + +$upload_dir = $conf->accounting->multidir_output[isset($object->entity) ? $object->entity : 1]; + +if (!$permissiontoread) { + accessforbidden(); +} + +$form = new Form($db); +$formfile = new FormFile($db); + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + $error = 0; + + $backurlforlist = DOL_URL_ROOT . '/accountancy/admin/template/list.php'; + + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = DOL_URL_ROOT . '/accountancy/admin/template/card.php?id=' . ((!empty($id) && $id > 0) ? $id : '__ID__'); + } + } + } + + $triggermodname = 'ACCOUNTING_BOOKKEEPINGTEMPLATE_MODIFY'; + + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT . '/core/actions_addupdatedelete.inc.php'; + + // Actions when linking object each other + include DOL_DOCUMENT_ROOT . '/core/actions_dellink.inc.php'; + + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT . '/core/actions_printing.inc.php'; + + // Action to build doc + include DOL_DOCUMENT_ROOT . '/core/actions_builddoc.inc.php'; + + // Actions to send emails + $triggersendname = 'ACCOUNTING_BOOKKEEPINGTEMPLATE_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_BOOKKEEPINGTEMPLATE_TO'; + $trackid = 'bookkeepingtemplate' . $object->id; + include DOL_DOCUMENT_ROOT . '/core/actions_sendmails.inc.php'; +} + +// Action to add a new line +if ($action == 'addline' && $permissiontoadd) { + $error = 0; + + // Get line data from POST + $general_account = GETPOST('general_account', 'alphanohtml'); + $subledger_account = GETPOST('subledger_account', 'alphanohtml'); + if ($subledger_account == '-1') { + $subledger_account = null; + } + $subledger_label = GETPOST('subledger_label', 'alphanohtml'); + $operation_label = GETPOST('operation_label', 'alphanohtml'); + $debit = price2num(GETPOST('debit', 'alpha')); + $credit = price2num(GETPOST('credit', 'alpha')); + + // Validation + if (((float) $debit != 0.0) && ((float) $credit != 0.0)) { + $error++; + setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); + $action = 'edit'; + } + + if (empty($general_account) || $general_account == '-1') { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountNumber")), null, 'errors'); + $action = 'edit'; + } + + if (!$error) { + // Fetch account label + $accountingaccount->fetch(0, $general_account, 1); + $general_label = $accountingaccount->label; + + // Create line object + $line = new BookkeepingTemplateLine($db); + $line->fk_transaction_template = $object->id; + $line->general_account = $general_account; + $line->general_label = $general_label; + $line->subledger_account = $subledger_account; + $line->subledger_label = $subledger_label; + $line->operation_label = $operation_label; + $line->debit = $debit; + $line->credit = $credit; + + $result = $line->create($user, 0); + + if ($result < 0) { + $error++; + setEventMessages($line->error, $line->errors, 'errors'); + $action = 'edit'; + } else { + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $object->id); + exit; + } + } +} + +// Action to update a line +if ($action == 'updateline' && $permissiontoadd) { + $error = 0; + + // Get line data from POST + $general_account = GETPOST('general_account', 'alphanohtml'); + $subledger_account = GETPOST('subledger_account', 'alphanohtml'); + if ($subledger_account == '-1') { + $subledger_account = null; + } + $subledger_label = GETPOST('subledger_label', 'alphanohtml'); + $operation_label = GETPOST('operation_label', 'alphanohtml'); + $debit = price2num(GETPOST('debit', 'alpha')); + $credit = price2num(GETPOST('credit', 'alpha')); + + // Validation + if (((float) $debit != 0.0) && ((float) $credit != 0.0)) { + $error++; + setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); + $action = 'editline'; + } + + if (empty($general_account) || $general_account == '-1') { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("AccountNumber")), null, 'errors'); + $action = 'editline'; + } + + if (!$error) { + // Fetch account label + $accountingaccount->fetch(0, $general_account, 1); + $general_label = $accountingaccount->label; + + // Load and update line + $line = new BookkeepingTemplateLine($db); + $result = $line->fetch($lineid); + + if ($result > 0) { + $line->general_account = $general_account; + $line->general_label = $general_label; + $line->subledger_account = $subledger_account; + $line->subledger_label = $subledger_label; + $line->operation_label = $operation_label; + $line->debit = $debit; + $line->credit = $credit; + + $result = $line->update($user, 0); + + if ($result < 0) { + $error++; + setEventMessages($line->error, $line->errors, 'errors'); + $action = 'editline'; + } else { + setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $object->id); + exit; + } + } else { + $error++; + setEventMessages($line->error, $line->errors, 'errors'); + } + } +} + +// Action to delete a line +if ($action == 'confirm_deleteline' && $confirm == 'yes' && $permissiontodelete) { + $result = $object->deleteLine($user, $lineid); + if ($result > 0) { + setEventMessages($langs->trans('RecordDeleted'), null, 'mesgs'); + header("Location: " . $_SERVER["PHP_SELF"] . "?id=" . $object->id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } +} + +/* + * View + */ + +$title = $langs->trans('BookkeepingTemplate') . " - " . $langs->trans('Card'); +if ($action == 'create') { + $title = $langs->trans("NewBookkeepingTemplate"); +} +$help_url = ''; + +llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-accountancy page-admin-template-card'); + +// Update fields properties in realtime +if (!empty($conf->use_javascript_ajax)) { + print "\n" . '' . "\n"; +} + +// Part to create +if ($action == 'create') { + if (empty($permissiontoadd)) { + accessforbidden('NotEnoughPermissions', 0, 1); + } + + print load_fiche_titre($title, '', 'object_' . $object->picto); + + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(array(), ''); + + print '' . "\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_add.tpl.php'; + + print '
' . "\n"; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel("Create"); + + print ''; + + dol_set_focus('input[name="code"]'); +} + +// Part to edit record +if (($id || $code) && $action == 'edit') { + print load_fiche_titre($langs->trans("BookkeepingTemplate"), '', 'object_' . $object->picto); + + print '
'; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print '' . "\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_edit.tpl.php'; + + print '
'; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel(); + + print '
'; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $head = accountingTransactionTemplatePrepareHead($object); + + print dol_get_fiche_head($head, 'card', $langs->trans("BookkeepingTemplate"), -1, $object->picto, 0, '', '', 0, '', 1); + + $formconfirm = ''; + + // Confirmation to delete template + if ($action == 'delete') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteBookkeepingTemplate'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1); + } + + // Confirmation to delete line + if ($action == 'deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); + } + + // Clone confirmation + if ($action == 'clone') { + // Create an array for form + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->code), 'confirm_clone', $formquestion, 'yes', 1); + } + + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + // Object card + $linkback = '' . $langs->trans("BackToList") . ''; + + $morehtmlref = '
'; + $morehtmlref .= '
'; + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'code', $morehtmlref); + + print '
'; + print '
'; + print '
'; + print '' . "\n"; + + // Common attributes + $keyforbreak = ''; + include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php'; + + print '
'; + print '
'; + print '
'; + + print '
'; + + print dol_get_fiche_end(); + + // Buttons for actions + if ($action != 'presend' && $action != 'editline' && $action != 'addline') { + print '
' . "\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + + if (empty($reshook)) { + // Modify + if ($permissiontoadd) { + print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit&token=' . newToken(), '', $permissiontoadd); + } + + // Clone + if ($permissiontoadd) { + print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=clone&token=' . newToken(), '', $permissiontoadd); + } + + // Delete + print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=delete&token=' . newToken(), '', $permissiontodelete); + } + print '
' . "\n"; + } + + // Lines section + print '
'; + if (!empty($object->table_element_line)) { + // Show object lines + $result = $object->getLinesArray(); + + print '
'; + print ''; + print ''; + print ''; + print ''; + print ''; + + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + // Define required variables for ajaxrow.tpl.php + $fk_element = 'fk_transaction_template'; + $table_element_line = $object->table_element_line; + include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php'; + } + + print '
'; + print ''; + + // Show header + print ''; + print_liste_field_titre("AccountAccountingShort"); + print_liste_field_titre("SubledgerAccount"); + print_liste_field_titre("LabelOperation"); + print_liste_field_titre("AccountingDebit", "", "", "", "", 'class="right"'); + print_liste_field_titre("AccountingCredit", "", "", "", "", 'class="right"'); + print_liste_field_titre("Action", "", "", "", "", 'width="60"', "", "", 'center '); + print "\n"; + + $i = 0; + + // Show existing lines + foreach ($object->lines as $line) { + // Line in view mode + if ($action != 'editline' || GETPOST('lineid', 'int') != $line->id) { + print ''; + print ''; + $resultfetch = $accountingaccount->fetch(0, $line->general_account, true); + print ''; + print ''; + print ''; + print ''; + print ''; + + // Edit link + print ''; + print ''; + } + + // Line in edit mode + if ($action == 'editline' && GETPOST('lineid', 'int') == $line->id) { + print ''; + print ''; + + // Account number + print ''; + + // Subledger account + print ''; + + // Operation label + print ''; + + // Debit + print ''; + + // Credit + print ''; + + // Save button + print ''; + + print ''; + } + + $i++; + } + + // Form to add new line + if ($action != 'editline' && $permissiontoadd) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } + + print '
'; + if ($resultfetch > 0) { + print $accountingaccount->getNomUrl(0, 1, 1, '', 0); + } else { + print dol_escape_htmltag($line->general_account).' ('.$langs->trans("AccountRemovedFromCurrentChartOfAccount").')'; + } + print ''.length_accounta($line->subledger_account ?? ''); + if (!empty($line->subledger_label)) { + print ' - '.dol_escape_htmltag($line->subledger_label).''; + } + print '' . ($line->operation_label ? dol_escape_htmltag($line->operation_label) : '') . '' . ($line->debit ? price($line->debit) : '') . '' . ($line->credit ? price($line->credit) : '') . ''; + if ($permissiontoadd) { + print 'id . '">'; + print img_edit('', 0, 'class="marginrightonly"'); + print '  '; + } + + // Delete link + if ($permissiontodelete) { + print ''; + print img_delete(); + print ''; + } + print '
'; + print $formaccounting->select_account((GETPOSTISSET("accountingaccount_number") ? GETPOST("accountingaccount_number", "alpha") : $line->general_account), 'general_account', 1, array(), 1, 1, 'minwidth200 maxwidth500'); + 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 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 (getDolGlobalString('ACCOUNTANCY_COMBO_FOR_AUX')) { + print $formaccounting->select_auxaccount((GETPOSTISSET("subledger_account") ? GETPOST("subledger_account", "alpha") : $line->subledger_account), 'subledger_account', 1, 'maxwidth250', '', 'subledger_label'); + } else { + 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 '
'; + print 'operation_label).'">'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'; + print ''; + print '
'; + print $formaccounting->select_account('', 'general_account', 1, [], 1, 1, 'maxwidth300'); + 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 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 (getDolGlobalString('ACCOUNTANCY_COMBO_FOR_AUX')) { + print $formaccounting->select_auxaccount('', 'subledger_account', 1, 'maxwidth250', '', 'subledger_label'); + } else { + print ''; + } + print '
'; + print '
'; + print '
'; + + print '
'; + } + print '
'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/admin/template/list.php b/htdocs/accountancy/admin/template/list.php new file mode 100644 index 00000000000..6a23692fb2a --- /dev/null +++ b/htdocs/accountancy/admin/template/list.php @@ -0,0 +1,701 @@ + + * + * 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 accountancy/admin/template/list.php + * \ingroup accountancy + * \brief List page for bookkeeping templates + */ + +// Load Dolibarr environment +require '../../../main.inc.php'; + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ + +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplate.class.php'; + +// Load translation files required by the page +$langs->loadLangs(array("accountancy", "other")); + +// Get parameters +$action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; +$massaction = GETPOST('massaction', 'alpha'); +$show_files = GETPOST('show_files', 'int'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'alpha'); +$toselect = GETPOST('toselect', 'array'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'bookkeepingtemplatelist'; +$backtopage = GETPOST('backtopage', 'alpha'); +$optioncss = GETPOST('optioncss', 'aZ'); +$mode = GETPOST('mode', 'aZ'); + +// Load variable for pagination +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page"); +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new BookkeepingTemplate($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->accounting->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array($contextpage)); + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); + $sortfield = "t.".key($object->fields); +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criteria +$search_all = trim(GETPOST('search_all', 'alphanohtml')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_'.$key.'_dtstartmonth'), GETPOSTINT('search_'.$key.'_dtstartday'), GETPOSTINT('search_'.$key.'_dtstartyear')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_'.$key.'_dtendmonth'), GETPOSTINT('search_'.$key.'_dtendday'), GETPOSTINT('search_'.$key.'_dtendyear')); + } +} + +// List of fields to search into when doing a "search in all" +$fieldstosearchall = array(); +foreach ($object->fields as $key => $val) { + if (!empty($val['searchall'])) { + $fieldstosearchall['t.'.$key] = $val['label']; + } +} + +// Definition of array of fields for columns +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields['t.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>(abs($visible) != 3 && dol_eval($val['enabled'], 1)), + 'position'=>$val['position'], + 'help'=> isset($val['help']) ? $val['help'] : '' + ); + } +} + +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +// Security check +$permissiontoread = $user->hasRight('accounting', 'chartofaccount'); +$permissiontoadd = $user->hasRight('accounting', 'chartofaccount'); +$permissiontodelete = $user->hasRight('accounting', 'chartofaccount'); + +if (!$permissiontoread) { + accessforbidden(); +} + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $toselect = array(); + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; + } + + // Mass actions + $objectclass = 'BookkeepingTemplate'; + $objectlabel = 'BookkeepingTemplate'; + $uploaddir = $conf->accounting->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; +} + +/* + * View + */ + +$form = new Form($db); + +$now = dol_now(); + +$title = $langs->trans("BookkeepingTemplates"); +$help_url = ''; +$morejs = array(); +$morecss = array(); + +// Build and execute select +$sql = 'SELECT '; +$sql .= $object->getFieldList('t'); + +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : ''); + } +} + +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); + +$sqlfields = $sql; + +$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; + +if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} + +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); +$sql .= $hookmanager->resPrint; + +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity('accounting').")"; +} else { + $sql .= " WHERE 1 = 1"; +} + +foreach ($search as $key => $val) { + if (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); + if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) { + if ($search[$key] == '-1') { + $search[$key] = ''; + $modesearch = 2; + } elseif ($search[$key] === '0' && (!isset($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval']))) { + $search[$key] = ''; + $modesearch = 2; + } + } + if ($search[$key] != '') { + $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t.".$db->escape($columnName)." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t.".$db->escape($columnName)." <= '".$db->idate($search[$key])."'"; + } + } + } + } +} + +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} + +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; + +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); +$sql .= $hookmanager->resPrint; + +// Count total nb of records +$nbtotalofrecords = ''; +if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { + $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql); + $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount); + $resql = $db->query($sqlforcount); + if ($resql) { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } + + if (($page * $limit) > $nbtotalofrecords) { + $page = 0; + $offset = 0; + } + $db->free($resql); +} + +// Complete request and execute it with limit +$sql .= $db->order($sortfield, $sortorder); +if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); +} + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + +// Direct jump if only one record found +if ($num == 1 && getDolGlobalInt('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".DOL_URL_ROOT.'/accountancy/admin/template/card.php?id='.((int) $id)); + exit; +} + +// Output page +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist'); + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.((int) $limit); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} + +foreach ($search as $key => $val) { + if (is_array($search[$key])) { + foreach ($search[$key] as $skey) { + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } + } elseif (preg_match('/(_dtstart|_dtend)$/', $key) && !empty($val)) { + $param .= '&search_'.$key.'month='.((int) GETPOST('search_'.$key.'month', 'int')); + $param .= '&search_'.$key.'day='.((int) GETPOST('search_'.$key.'day', 'int')); + $param .= '&search_'.$key.'year='.((int) GETPOST('search_'.$key.'year', 'int')); + } elseif ($search[$key] != '') { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} + +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +// Add $param from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array(); +if (!empty($permissiontodelete)) { + $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
'."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +$newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('NewBookkeepingTemplate'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/accountancy/admin/template/card.php?action=create', '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendBookkeepingTemplateRef"; +$modelmail = "bookkeepingtemplate"; +$objecttmp = new BookkeepingTemplate($db); +$trackid = 'bookkeepingtemplate'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + $setupstring = ''; + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + $setupstring .= $key."=".$val.";"; + } + print ''."\n"; + print '
'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'
'."\n"; +} + +$moreforfilter = ''; + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} + +if (!empty($moreforfilter)) { + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$selectedfields = ($mode != 'kanban' ? $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')) : ''); +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
'; +print ''."\n"; + +// Fields title search +print ''; + +// Action column +if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; +} + +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} + +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); +print $hookmanager->resPrint; + +// Action column +if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; +} +print ''."\n"; + +$totalarray = array(); +$totalarray['nbfield'] = 0; + +// Fields title label +print ''; + +// Action column +if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); + $totalarray['nbfield']++; +} + +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + $cssforfield = preg_replace('/small\s*/', '', $cssforfield); + if (!empty($arrayfields['t.'.$key]['checked'])) { + print_liste_field_titre($arrayfields['t.'.$key]['label'], $_SERVER["PHP_SELF"], 't.'.$key, '', $param, '', $sortfield, $sortorder, $cssforfield.' '); + $totalarray['nbfield']++; + } +} + +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + +// Hook fields +$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); +print $hookmanager->resPrint; + +// Action column +if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); + $totalarray['nbfield']++; +} +print ''."\n"; + +// Loop on record +$i = 0; +$savnbfield = $totalarray['nbfield']; +$totalarray = array(); +$totalarray['nbfield'] = 0; +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; + } + + $object->setVarsFromFetchObj($obj); + + // Show here line of result + $j = 0; + print ''; + + // Action column + if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->showOutputField($val, $key, (string) $object->id, ''); + } elseif ($key == 'code') { + // Display code with link to card using getNomUrl + print $object->getNomUrl(1); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure']) && $val['isameasure'] == 1) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } + if (!isset($totalarray['val'])) { + $totalarray['val'] = array(); + } + if (!isset($totalarray['val']['t.'.$key])) { + $totalarray['val']['t.'.$key] = 0; + } + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + + // Fields from hook + $parameters = array('arrayfields'=>$arrayfields, 'object'=>$object, 'obj'=>$obj, 'i'=>$i, 'totalarray'=>&$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); + print $hookmanager->resPrint; + + // Action column + if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + print ''."\n"; + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; +} + +$db->free($resql); + +$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); +print $hookmanager->resPrint; + +print '
'; + $searchpicto = $form->showFilterButtons('left'); + print $searchpicto; + print ''; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100'.($key == 'status' ? ' search_status width100 onrightofpage' : ''), 1); + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) { + print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', $cssforfield.' maxwidth250', 1); + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
'; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + } elseif ($key == 'lang') { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin = new FormAdmin($db); + print $formadmin->select_language($search[$key], 'search_lang', 0, [], 1, 0, 0, 'minwidth150 maxwidth200', 2); + } else { + print ''; + } + print '
'; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'; + if ($massactionbutton || $massaction) { + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print ''; + if ($massactionbutton || $massaction) { + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print '
'.$langs->trans("NoRecordFound").'
'."\n"; +print '
'."\n"; + +print '
'."\n"; + +if (in_array('builddoc', array_keys($arrayofmassactions)) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_accounting', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index 5870fd54bf4..82015cd539a 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -1,7 +1,7 @@ * Copyright (C) 2013-2017 Florian Henry - * Copyright (C) 2013-2025 Alexandre Spangaro + * Copyright (C) 2013-2026 Alexandre Spangaro * Copyright (C) 2017 Laurent Destailleur * Copyright (C) 2018-2024 Frédéric France * Copyright (C) 2024-2025 MDW @@ -38,6 +38,8 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; require_once DOL_DOCUMENT_ROOT.'/accountancy/class/lettering.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplate.class.php'; +require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplateline.class.php'; /** * @var Conf $conf @@ -313,14 +315,79 @@ if (empty($reshook)) { $action = 'create'; } else { - $reshook = $hookmanager->executeHooks('afterCreateBookkeeping', $parameters, $object, $action); + // Transaction created successfully + $piece_num = $object->piece_num; - if ($mode != '_tmp') { - setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); + // Check if a template was selected + $template_id = GETPOSTINT('template_id'); + + if ($template_id > 0) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplate.class.php'; + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplateline.class.php'; + + $template = new BookkeepingTemplate($db); + $result_template = $template->fetch($template_id); + + if ($result_template > 0 && !empty($template->lines)) { + $db->begin(); + $error_template = 0; + + foreach ($template->lines as $templateline) { + $bookkeeping = new BookKeeping($db); + + // Set common fields from the form + $bookkeeping->doc_date = $date_start; + $bookkeeping->doc_type = GETPOST('doctype', 'alpha'); + $bookkeeping->piece_num = $piece_num; + $bookkeeping->doc_ref = GETPOST('docref', 'alpha'); + $bookkeeping->code_journal = $journal_code; + $bookkeeping->journal_label = $journal_label; + $bookkeeping->fk_doc = 0; + $bookkeeping->fk_docdet = 0; + $bookkeeping->ref = GETPOST('ref', 'alpha') ? GETPOST('ref', 'alpha') : $object->ref; + + // Set fields from template line + $bookkeeping->numero_compte = $templateline->general_account; + $bookkeeping->label_compte = $templateline->general_label; + $bookkeeping->subledger_account = $templateline->subledger_account; + $bookkeeping->subledger_label = $templateline->subledger_label; + $bookkeeping->label_operation = $templateline->operation_label; + $bookkeeping->debit = (float) $templateline->debit; + $bookkeeping->credit = (float) $templateline->credit; + + // Backward compatibility + if ((float) $bookkeeping->debit != 0.0) { + $bookkeeping->montant = $bookkeeping->debit; + $bookkeeping->amount = $bookkeeping->debit; + $bookkeeping->sens = 'D'; + } + if ((float) $bookkeeping->credit != 0.0) { + $bookkeeping->montant = $bookkeeping->credit; + $bookkeeping->amount = $bookkeeping->credit; + $bookkeeping->sens = 'C'; + } + + $result_line = $bookkeeping->createStd($user, 0, '_tmp'); + + if ($result_line < 0) { + $error_template++; + setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors'); + break; + } + } + + if (!$error_template) { + $db->commit(); + setEventMessages($langs->trans('TemplateLinesLoaded', count($template->lines)), null, 'mesgs'); + } else { + $db->rollback(); + } + } } - $action = ''; - $id = $object->id; - $piece_num = (int) $object->piece_num; + + // Redirect to the transaction + header("Location: ".$_SERVER["PHP_SELF"]."?piece_num=".$piece_num."&mode=_tmp"); + exit; } } } @@ -570,15 +637,47 @@ if ($action == 'create') { } else { print ''.$langs->trans("Automatic").''; } + print ''; + + // Template + print ''; + print ''.$langs->trans("BookkeepingTemplate").''; + print ''; + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeepingtemplate.class.php'; + + $sql = "SELECT rowid, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_transaction_template"; + $sql .= " WHERE entity IN (".getEntity('accounting').")"; + $sql .= " ORDER BY code ASC"; + + $resql = $db->query($sql); + $templates = array(); + + if ($resql) { + $num = $db->num_rows($resql); + $i = 0; + while ($i < $num) { + $obj = $db->fetch_object($resql); + $templates[$obj->rowid] = $obj->code.' - '.$obj->label; + $i++; + } + $db->free($resql); + } + + if (count($templates) > 0) { + print ''; + } else { + print ''.$langs->trans("NoTemplateAvailable").''; + } + print ''; print ''; - /* - print ''; - print '' . $langs->trans("Doctype") . ''; - print ''; - print ''; - */ $reshookAddLine = $hookmanager->executeHooks('bookkeepingAddLine', $parameters, $object, $action); print ''; diff --git a/htdocs/accountancy/class/bookkeepingtemplate.class.php b/htdocs/accountancy/class/bookkeepingtemplate.class.php new file mode 100644 index 00000000000..03ae539e049 --- /dev/null +++ b/htdocs/accountancy/class/bookkeepingtemplate.class.php @@ -0,0 +1,561 @@ + + * + * 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 accountancy/class/bookkeepingtemplate.class.php + * \ingroup accountancy + * \brief This file is a CRUD class file for BookkeepingTemplate (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php'; +require_once DOL_DOCUMENT_ROOT . '/accountancy/class/bookkeepingtemplateline.class.php'; + +/** + * Class for BookkeepingTemplate + */ +class BookkeepingTemplate extends CommonObject +{ + /** + * @var string ID of module. + */ + public $module = 'accountancy'; + + /** + * @var string ID to identify managed object. + */ + public $element = 'accounting_transaction_template'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'accounting_transaction_template'; + + /** + * @var int<0,1>|string 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 1; + + /** + * @var int<0,1> Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 1; + + /** + * @var string String with name of icon for bookkeepingtemplate. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'bookkeepingtemplate@accountancy' if picto is file 'img/object_bookkeepingtemplate.png'. + */ + public $picto = 'fa-list'; + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'langfile' the key of the language file for translation. + * 'enabled' is a condition when the field must be managed. + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwritten by the Setup of Default Values if the field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array|string,position:int,notnull?:int,visible:int<-6,6>|string,alwayseditable?:int<0,1>|string,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,cssview?:string,csslist?:string,help?:string,showoncombobox?:int<0,4>|string,disabled?:int<0,1>,arrayofkeyval?:array,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>,showonheader?:int<0,1>,searchmulti?:int<0,1>,picto?:string}> Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields = array( + "rowid" => array("type" => "integer", "label" => "TechnicalID", "enabled" => 1, 'position' => 1, 'notnull' => 1, "visible" => 0, "noteditable" => 1, "index" => 1, "css" => "left", "comment" => "Id"), + "entity" => array("type" => "integer", "label" => "Entity", "enabled" => 1, 'position' => 5, 'notnull' => 1, "visible" => 0, "index" => 1, "default" => '1'), + "code" => array("type" => "varchar(128)", "label" => "Code", "enabled" => 1, 'position' => 10, 'notnull' => 1, "visible" => 1, "index" => 2, "searchall" => 1, "css" => "minwidth300", "help" => "UniqueCodeForTemplate"), + "label" => array("type" => "varchar(255)", "label" => "Label", "enabled" => 1, 'position' => 20, 'notnull' => 0, "visible" => 1, "css" => "minwidth300"), + "date_creation" => array("type" => "datetime", "label" => "DateCreation", "enabled" => 1, 'position' => 500, 'notnull' => 1, "visible" => -2), + "tms" => array("type" => "timestamp", "label" => "DateModification", "enabled" => 1, 'position' => 501, 'notnull' => 0, "visible" => -2), + "fk_user_creat" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserAuthor", "picto" => "user", "enabled" => 1, 'position' => 510, 'notnull' => 1, "visible" => "-2", "csslist" => "tdoverflowmax150"), + "fk_user_modif" => array("type" => "integer:User:user/class/user.class.php", "label" => "UserModif", "picto" => "user", "enabled" => 1, 'position' => 511, 'notnull' => -1, "visible" => "-2", "csslist" => "tdoverflowmax150"), + "import_key" => array("type" => "varchar(14)", "label" => "ImportId", "enabled" => 1, 'position' => 1000, 'notnull' => -1, "visible" => -2), + ); + // END MODULEBUILDER PROPERTIES + + /** + * @var int ID + */ + public $rowid; + + /** + * @var int Entity + */ + public $entity; + + /** + * @var string Code + */ + public $code; + + /** + * @var string Label + */ + public $label; + + /** + * @var int Unix timestamp of creation date + */ + public $date_creation; + + /** + * @var int Unix timestamp of last modification + */ + public $tms; + + /** + * @var int User ID who created + */ + public $fk_user_creat; + + /** + * @var int|null User ID who modified + */ + public $fk_user_modif; + + /** + * @var string|null Import key + */ + public $import_key; + + /** + * @var string Name of subtable line + */ + public $table_element_line = 'accounting_transaction_template_det'; + + /** + * @var BookkeepingTemplateLine[] Array of subtable lines + */ + public $lines = array(); + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'], $this->fields['code']) && is_array($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (!isModEnabled('multicompany') && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = (string) $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = 0) + { + $resultcreate = $this->createCommon($user, $notrigger); + return $resultcreate; + } + + /** + * Clone an object into another one + * + * @param User $user User that creates + * @param int $fromid Id of object to clone + * @return mixed New object created, <0 if KO + */ + public function createFromClone(User $user, $fromid) + { + global $langs, $extrafields; + $error = 0; + + dol_syslog(__METHOD__, LOG_DEBUG); + + $object = new self($this->db); + + $this->db->begin(); + + // Load source object + $result = $object->fetchCommon($fromid); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } + + // Reset some properties + unset($object->id); + unset($object->fk_user_creat); + + // Clear fields + $object->code = "COPY_" . $object->code; + $object->label = $langs->trans("CopyOf") . " " . $object->label; + $object->date_creation = dol_now(); + + // Create clone + $object->context['createfromclone'] = 'createfromclone'; + $result = $object->createCommon($user); + + if ($result < 0) { + $error++; + $this->setErrorsFromObject($object); + } + + if (!$error) { + // Copy Attached Lines + $this->getLinesArray(); + foreach ($this->lines as $linetoclone) { + // Clear some info + unset($linetoclone->id); + unset($linetoclone->fk_user_creat); + $linetoclone->fk_transaction_template = $object->id; + + // Save in DB + $linetoclone->createCommon($user); + } + } + + unset($object->context['createfromclone']); + + // End + if (!$error) { + $this->db->commit(); + return $object; + } else { + $this->db->rollback(); + return -1; + } + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param string $code Code + * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields + * @param int $nolines 0=Default to load lines, 1=No lines + * @return int Return integer <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $code = null, $noextrafields = 0, $nolines = 0) + { + $result = $this->fetchCommon($id, $code, '', $noextrafields); + if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) { + $this->fetchLines($noextrafields); + } + return $result; + } + + /** + * Load object lines in memory from the database + * + * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields + * @return BookkeepingTemplateLine[]|int Array of line objects if OK, <0 if KO + */ + public function fetchLines($noextrafields = 0) + { + $this->lines = array(); + + $objectline = new BookkeepingTemplateLine($this->db); + $result = $objectline->fetchAll('ASC', 'rowid', 0, 0, array('customsql' => 'fk_transaction_template = ' . ((int) $this->id))); + + if (is_numeric($result)) { + $this->setErrorsFromObject($objectline); + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = 0) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0) + { + global $conf, $langs; + + $error = 0; + + $this->db->begin(); + + // Delete the Lines first + $obj_line = new BookkeepingTemplateLine($this->db); + + $sql = "DELETE FROM ".$this->db->prefix().$obj_line->table_element; + $sql .= " WHERE fk_transaction_template = ".((int) $this->id); + + dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + $error++; + dol_syslog(get_class($this)."::delete error deleting lines: ".$this->db->lasterror(), LOG_ERR); + } + + if (empty($error)) { + // Call trigger + if (!$notrigger) { + $result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user); + if ($result < 0) { + $error++; + } + } + } + + if (empty($error)) { + // Delete main object + $sql = "DELETE FROM ".$this->db->prefix().$this->table_element; + $sql .= " WHERE rowid = ".((int) $this->id); + + dol_syslog(get_class($this)."::delete sql=".$sql, LOG_DEBUG); + + $resql = $this->db->query($sql); + if (!$resql) { + $this->errors[] = $this->db->lasterror(); + $this->error = $this->db->lasterror(); + $error++; + dol_syslog(get_class($this)."::delete error deleting main object: ".$this->db->lasterror(), LOG_ERR); + } + } + + // Commit or rollback + if (empty($error)) { + $this->db->commit(); + return 1; + } else { + $this->error = implode(', ', $this->errors); + $this->db->rollback(); + return -1; + } + } + + /** + * Delete a line of object in database + * + * @param User $user User that delete + * @param int $idline Id of line to delete + * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers + * @return int >0 if OK, <0 if KO + */ + public function deleteLine(User $user, $idline, $notrigger = 0) + { + $tmpline = new BookkeepingTemplateLine($this->db); + if ($tmpline->fetch($idline) > 0) { + return $tmpline->delete($user); + } + + return -1; + } + + /** + * Create an array of lines + * + * @return BookkeepingTemplateLine[]|int array of BookkeepingTemplateLine objects if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new BookkeepingTemplateLine($this->db); + $result = $objectline->fetchAll('ASC', 'rowid', 0, 0, array('customsql' => 'fk_transaction_template = ' . ((int) $this->id))); + + if (is_numeric($result)) { + $this->setErrorsFromObject($objectline); + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Returns the reference to the following non used object depending on the active numbering module. + * + * @return string Object free reference + */ + public function getNextNumRef() + { + global $langs, $conf; + $langs->load("accountancy"); + + // Standard numbering - Generate a code based on timestamp + $code = 'TPL' . dol_print_date(dol_now(), '%Y%m%d%H%M%S'); + + return $code; + } + + /** + * Return a link to the object card (with optionally the picto) + * + * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto) + * @param string $option On what the link point to ('nolink', ...) + * @param int $notooltip 1=Disable tooltip + * @param string $morecss Add more css on link + * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking + * @return string String with URL + */ + public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1) + { + global $conf, $langs, $hookmanager; + + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; + } + + $result = ''; + + $label = img_picto('', $this->picto) . ' ' . $langs->trans("BookkeepingTemplate") . ''; + if (isset($this->code)) { + $label .= '
' . $langs->trans('Code') . ': ' . $this->code; + } + if (isset($this->label)) { + $label .= '
' . $langs->trans('Label') . ': ' . $this->label; + } + + $url = DOL_URL_ROOT . '/accountancy/admin/template/card.php?id=' . $this->id; + + if ($option != 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } + + $linkclose = ''; + if (empty($notooltip)) { + if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) { + $label = $langs->trans("ShowBookkeepingTemplate"); + $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') { + $linkstart = ''; + if ($option == 'nolink') { + $linkend = ''; + } else { + $linkend = ''; + } + + $result .= $linkstart; + + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + + if ($withpicto != 2) { + $result .= $this->code; + } + + $result .= $linkend; + + return $result; + } + + /** + * Return label of status + * + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function getLibStatut($mode = 0) + { + return $this->LibStatut(1, $mode); + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + + /** + * Return label of a given status + * + * @param int $status Status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto + * @return string Label of status + */ + public function LibStatut($status, $mode = 0) + { + // phpcs:enable + global $langs; + + return ''; + } +} diff --git a/htdocs/accountancy/class/bookkeepingtemplateline.class.php b/htdocs/accountancy/class/bookkeepingtemplateline.class.php new file mode 100644 index 00000000000..df470a812c7 --- /dev/null +++ b/htdocs/accountancy/class/bookkeepingtemplateline.class.php @@ -0,0 +1,368 @@ + + * + * 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 accountancy/class/bookkeepingtemplateline.class.php + * \ingroup accountancy + * \brief This file is a CRUD class file for BookkeepingTemplateLine (Create/Read/Update/Delete) + */ + +// Put here all includes required by your class file +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php'; + +/** + * Class for BookkeepingTemplateLine + */ +class BookkeepingTemplateLine extends CommonObject +{ + /** + * @var string ID of module. + */ + public $module = 'accountancy'; + + /** + * @var string ID to identify managed object. + */ + public $element = 'accounting_transaction_template_det'; + + /** + * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management. + */ + public $table_element = 'accounting_transaction_template_det'; + + /** + * @var int<0,1>|string 0=No test on entity, 1=Test with field entity, 2=Test with link by societe + */ + public $ismultientitymanaged = 0; + + /** + * @var int<0,1> Does object support extrafields ? 0=No, 1=Yes + */ + public $isextrafieldmanaged = 0; + + /** + * @var string String with name of icon for bookkeepingtemplateline. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'bookkeepingtemplateline@accountancy' if picto is file 'img/object_bookkeepingtemplateline.png'. + */ + public $picto = 'fa-file'; + + /** + * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password') + * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)" + * 'label' the translation key. + * 'langfile' the key of the language file for translation. + * 'enabled' is a condition when the field must be managed. + * 'position' is the sort order of field. + * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0). + * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing) + * 'noteditable' says if field is not editable (1 or 0) + * 'default' is a default value for creation (can still be overwritten by the Setup of Default Values if the field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created. + * 'index' if we want an index in database. + * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...). + * 'searchall' is 1 if we want to search in this field when making a search from the quick search button. + * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8). + * 'css' is the CSS style to use on field. For example: 'maxwidth200' + * 'help' is a string visible as a tooltip on field + * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record + * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code. + * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel") + * 'comment' is not used. You can store here any text of your choice. It is not used by application. + * + * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor. + */ + + // BEGIN MODULEBUILDER PROPERTIES + /** + * @var array|string,position:int,notnull?:int,visible:int<-6,6>|string,alwayseditable?:int<0,1>|string,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,cssview?:string,csslist?:string,help?:string,showoncombobox?:int<0,4>|string,disabled?:int<0,1>,arrayofkeyval?:array,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>,showonheader?:int<0,1>,searchmulti?:int<0,1>}> Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. + */ + public $fields = array( + "rowid" => array("type"=>"integer", "label"=>"TechnicalID", "enabled"=>1, 'position'=>1, 'notnull'=>1, "visible"=>0, "noteditable"=>1, "index"=>1, "css"=>"left", "comment"=>"Id"), + "fk_transaction_template" => array("type"=>"integer", "label"=>"Template", "enabled"=>1, 'position'=>5, 'notnull'=>1, "visible"=>0, "noteditable"=>1, "foreignkey"=>"accounting_transaction_template.rowid"), + "general_account" => array("type"=>"varchar(32)", "label"=>"AccountNumber", "enabled"=>1, 'position'=>10, 'notnull'=>1, "visible"=>1, "css"=>"minwidth100"), + "general_label" => array("type"=>"varchar(255)", "label"=>"AccountLabel", "enabled"=>1, 'position'=>20, 'notnull'=>1, "visible"=>1, "css"=>"minwidth200"), + "subledger_account" => array("type"=>"varchar(32)", "label"=>"SubledgerAccount", "enabled"=>1, 'position'=>30, 'notnull'=>0, "visible"=>1, "css"=>"minwidth100"), + "subledger_label" => array("type"=>"varchar(255)", "label"=>"SubledgerLabel", "enabled"=>1, 'position'=>40, 'notnull'=>0, "visible"=>1, "css"=>"minwidth200"), + "operation_label" => array("type"=>"varchar(255)", "label"=>"OperationLabel", "enabled"=>1, 'position'=>50, 'notnull'=>0, "visible"=>1, "css"=>"minwidth200"), + "debit" => array("type"=>"double(24,8)", "label"=>"Debit", "enabled"=>1, 'position'=>60, 'notnull'=>0, "visible"=>1, "css"=>"maxwidth75 right"), + "credit" => array("type"=>"double(24,8)", "label"=>"Credit", "enabled"=>1, 'position'=>70, 'notnull'=>0, "visible"=>1, "css"=>"maxwidth75 right"), + ); + // END MODULEBUILDER PROPERTIES + + /** + * @var int ID + */ + public $rowid; + + /** + * @var int Foreign key to accounting transaction template + */ + public $fk_transaction_template; + + /** + * @var string General account number + */ + public $general_account; + + /** + * @var string|null General account label/description + */ + public $general_label; + + /** + * @var string|null Subledger account number (auxiliary account) + */ + public $subledger_account; + + /** + * @var string|null Subledger account label/description + */ + public $subledger_label; + + /** + * @var string Debit amount (stored as string for precision) + */ + public $debit; + + /** + * @var string Credit amount (stored as string for precision) + */ + public $credit; + + /** + * @var string|null Sense/direction (D for debit, C for credit) + */ + public $sens; + + /** + * @var int|null Line position/order + */ + public $position; + + /** + * @var integer|''|null Creation date + */ + public $date_creation; + + /** + * @var int + */ + public $tms; + + /** + * @var int|null User ID who created this line + */ + public $fk_user_creat; + + /** + * @var int|null User ID who last modified this line + */ + public $fk_user_modif; + + + /** + * Constructor + * + * @param DoliDb $db Database handler + */ + public function __construct(DoliDB $db) + { + global $conf, $langs; + + $this->db = $db; + + if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + + // Unset fields that are disabled + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { + unset($this->fields[$key]); + } + } + + // Translate some data of arrayofkeyval + if (is_object($langs)) { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); + } + } + } + } + } + + /** + * Create object into database + * + * @param User $user User that creates + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, Id of created object if OK + */ + public function create(User $user, $notrigger = 0) + { + $resultcreate = $this->createCommon($user, $notrigger); + return $resultcreate; + } + + /** + * Load object in memory from the database + * + * @param int $id Id object + * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields + * @return int Return integer <0 if KO, 0 if not found, >0 if OK + */ + public function fetch($id, $noextrafields = 0) + { + $result = $this->fetchCommon($id, '', '', $noextrafields); + return $result; + } + + /** + * Load list of objects in memory from the database. + * + * @param string $sortorder Sort Order + * @param string $sortfield Sort field + * @param int $limit limit + * @param int $offset Offset + * @param array $filter Filter array. Example array('mystringfield'=>'value', 'myintfield'=>4, 'customsql'=>...) + * @param string $filtermode Filter mode (AND or OR) + * @return BookkeepingTemplateLine[]|int Array of BookkeepingTemplateLine objects if OK, <0 if KO + */ + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { + dol_syslog(__METHOD__, LOG_DEBUG); + + $records = array(); + + $sql = "SELECT "; + $sql .= $this->getFieldList('t'); + $sql .= " FROM ".$this->db->prefix().$this->table_element." as t"; + if (isset($this->isextrafieldmanaged) && $this->isextrafieldmanaged == 1) { + $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid"; + } + $sql .= " WHERE 1 = 1"; + + // Manage filter + $sqlwhere = array(); + if (count($filter) > 0) { + foreach ($filter as $key => $value) { + if ($key === 'customsql') { + // Never use 'customsql' with a value from user input since it is injected as is. The value must be hard coded. + $sqlwhere[] = $value; + continue; + } + + $columnName = preg_replace('/^t\./', '', $key); + + if (isset($this->fields[$columnName])) { + $type = $this->fields[$columnName]['type']; + if (preg_match('/^integer/', $type)) { + if (is_int($value)) { + // single value + $sqlwhere[] = $key . " = " . intval($value); + } elseif (is_array($value)) { + if (empty($value)) { + continue; + } + $sqlwhere[] = $key . ' IN (' . $this->db->sanitize(implode(',', array_map('intval', $value))) . ')'; + } + continue; + } elseif (in_array($type, array('date', 'datetime', 'timestamp'))) { + $sqlwhere[] = $key . " = '" . $this->db->idate($value) . "'"; + continue; + } + } + + // when the $key doesn't fall into the previously handled categories, we do as if the column were a varchar/text + if (is_array($value) && count($value)) { + $escapedValues = array(); + foreach ($value as $v) { + $escapedValues[] = $this->db->escape($v); + } + $value = implode(',', $escapedValues); + $sqlwhere[] = $key . ' IN (' . $this->db->sanitize($value, 1) . ')'; + } elseif (is_scalar($value)) { + if (strpos($value, '%') === false) { + $sqlwhere[] = $key . " = '" . $this->db->sanitize($this->db->escape($value)) . "'"; + } else { + $sqlwhere[] = $key . " LIKE '%" . $this->db->escape($this->db->escapeforlike($value)) . "%'"; + } + } + } + } + if (count($sqlwhere) > 0) { + $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")"; + } + + if (!empty($sortfield)) { + $sql .= $this->db->order($sortfield, $sortorder); + } + if (!empty($limit)) { + $sql .= $this->db->plimit($limit, $offset); + } + + $resql = $this->db->query($sql); + if ($resql) { + $num = $this->db->num_rows($resql); + $i = 0; + while ($i < ($limit ? min($limit, $num) : $num)) { + $obj = $this->db->fetch_object($resql); + + $record = new self($this->db); + $record->setVarsFromFetchObj($obj); + + $records[$record->id] = $record; + + $i++; + } + $this->db->free($resql); + + return $records; + } else { + $this->errors[] = 'Error '.$this->db->lasterror(); + dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR); + + return -1; + } + } + + /** + * Update object into database + * + * @param User $user User that modifies + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, >0 if OK + */ + public function update(User $user, $notrigger = 0) + { + return $this->updateCommon($user, $notrigger); + } + + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int Return integer <0 if KO, >0 if OK + */ + public function delete(User $user, $notrigger = 0) + { + return $this->deleteCommon($user, $notrigger); + } +} diff --git a/htdocs/core/lib/accounting.lib.php b/htdocs/core/lib/accounting.lib.php index 9f51ec39673..5d39e074202 100644 --- a/htdocs/core/lib/accounting.lib.php +++ b/htdocs/core/lib/accounting.lib.php @@ -1,6 +1,6 @@ - * Copyright (C) 2013-2025 Alexandre Spangaro + * Copyright (C) 2013-2026 Alexandre Spangaro * Copyright (C) 2014 Florian Henry * Copyright (C) 2019 Eric Seigne * Copyright (C) 2021-2026 Frédéric France @@ -105,6 +105,31 @@ function accounting_transaction_prepare_head(BookKeeping $object, $mode = '', $t return $head; } +/** + * Prepare array with list of tabs for accounting transaction template + * + * @param BookkeepingTemplate $object Bookkeeping template + * @return array Array of tabs to show + */ +function accountingTransactionTemplatePrepareHead(BookkeepingTemplate $object) +{ + global $langs, $conf; + + $h = 0; + $head = array(); + + $head[$h][0] = dolBuildUrl(DOL_URL_ROOT.'/accountancy/admin/template/card.php', ['id' => $object->id]); + $head[$h][1] = $langs->trans("BookkeepingTemplate"); + $head[$h][2] = 'card'; + $h++; + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'accounting_template_transaction'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'accounting_template_transaction', 'remove'); + + return $head; +} + /** * Return accounting account without zero on the right * diff --git a/htdocs/core/menus/init_menu_auguria.sql b/htdocs/core/menus/init_menu_auguria.sql index 54f02b8c94b..3701b84b757 100644 --- a/htdocs/core/menus/init_menu_auguria.sql +++ b/htdocs/core/menus/init_menu_auguria.sql @@ -296,7 +296,8 @@ insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, left insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2461__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_vat', 2451__+MAX_llx_menu__, '/admin/dict.php?id=10&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuVatAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 52, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2462__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_tax', 2451__+MAX_llx_menu__, '/admin/dict.php?id=7&from=accountancy&search_country_id=__MYCOUNTRYID__&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuTaxAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 53, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && isModEnabled("expensereport") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2463__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_expensereport', 2451__+MAX_llx_menu__, '/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuExpenseReportAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 54, __ENTITY__); -insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2464__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_product', 2451__+MAX_llx_menu__, '/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuProductsAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 55, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2464__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_template', 2451__+MAX_llx_menu__, '/accountancy/admin/template/list.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuListBookkeepingTemplates', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 55, __ENTITY__); +insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2465__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_product', 2451__+MAX_llx_menu__, '/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuProductsAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 60, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2466__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_closure', 2451__+MAX_llx_menu__, '/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin', 'MenuClosureAccounts', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 70, __ENTITY__); insert into llx_menu (module, enabled, menu_handler, type, rowid, mainmenu, leftmenu, fk_menu, url, titre, level, langs, perms, target, usertype, position, entity) values ('', 'isModEnabled("accounting") && $leftmenu=="accountancy_admin"', __HANDLER__, 'left', 2470__+MAX_llx_menu__, 'accountancy', 'accountancy_admin_report_group', 2451__+MAX_llx_menu__, '/accountancy/admin/report_list.php?id=45&mainmenu=accountancy&leftmenu=accountancy_admin', 'AccountingReport', 2, 'accountancy', '$user->hasRight("accounting","chartofaccount")', '', 0, 75, __ENTITY__); diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 6bd2c467de3..4c06713d889 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -9,7 +9,7 @@ * Copyright (C) 2021 Gauthier VERDOL * Copyright (C) 2022-2023 Solution Libre SAS * Copyright (C) 2024-2025 MDW - * Copyright (C) 2024-2025 Alexandre Spangaro + * Copyright (C) 2024-2026 Alexandre Spangaro * Copyright (C) 2025 Josep Lluís Amador * * This program is free software; you can redistribute it and/or modify @@ -1763,12 +1763,13 @@ function get_left_menu_accountancy($mainmenu, &$newmenu, $usemenuhider = 1, $lef if (isModEnabled('expensereport')) { $newmenu->add("/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuExpenseReportAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_default', 100); } - $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_product', 110); - $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 120); + $newmenu->add("/accountancy/admin/template/list.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuListBookkeepingTemplates"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_template', 110); + $newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuProductsAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_product', 120); + $newmenu->add("/accountancy/admin/closure.php?mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("MenuClosureAccounts"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_closure', 130); if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2) { - $newmenu->add("/accountancy/admin/report_list.php?id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingReport"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_report', 125); + $newmenu->add("/accountancy/admin/report_list.php?id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingReport"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_report', 140); } - $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingCategory"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_chart', 130); + $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", $langs->trans("AccountingCategory"), 1, $user->hasRight('accounting', 'chartofaccount'), '', $mainmenu, 'accountancy_admin_chart', 145); } // Transfer in accounting diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 85c7c57c6d1..eb8ddebcdf4 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -372,7 +372,26 @@ ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE=Activate the management of VAT revers ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE_DESC=When this option is enabled, you can define that a supplier or a given vendor invoice must be transferred into accountancy differently: A additional debit and a credit line will generated into the accounting on 2 given accounts from the chart of account defined into the "%s" setup page. ACCOUNTING_ENABLE_TABONTHIRDPARTY=Activate a tab on third-party cards to view the subsidiary ledger ACCOUNTING_ENABLE_TABONTHIRDPARTY_DESC=When this option is enabled, a new tab is showing in third-party cards to view and manage accounting for the third-party as to reconcile, print & more - +## Template +MenuListBookkeepingTemplates=Bookkeeping templates +BookkeepingTemplates=Bookkeeping templates +BookkeepingTemplate=Bookkeeping template +ShowBookkeepingTemplate=Show bookkeeping template +ListBookkeepingTemplates=List of bookkeeping templates +NewBookkeepingTemplate=New bookkeeping template +NoTemplateAvailable=No template available +CreateBookkeepingTemplate=Create bookkeeping template +ModifyBookkeepingTemplate=Modify bookkeeping template +DeleteBookkeepingTemplate=Delete bookkeeping template +BookkeepingTemplateCard=Bookkeeping template card +ConfirmDeleteBookkeepingTemplate=Are you sure you want to delete this bookkeeping template? +BookkeepingTemplateDeleted=Bookkeeping template deleted +BookkeepingTemplateCreated=Bookkeeping template created +NoBookkeepingTemplate=No bookkeeping +TemplateLinesLoaded=Template lines loaded +TemplateLabel=Template label +TemplateLine=Template line +TemplateLines=Template lines ## Export NotExportLettering=Do not export the matching code when generating the file NotifiedExportDate=Flag not yet exported lines as Exported (to modify a line flagged as exported, you will need to delete the whole transaction and re-transfert it into accounting) From df352dfbb3fed7d895d9b45658b366fb03ff15f6 Mon Sep 17 00:00:00 2001 From: Pierre Ardoin <32256817+mapiolca@users.noreply.github.com> Date: Tue, 24 Feb 2026 17:53:24 +0100 Subject: [PATCH 13/14] NEW Support for __AUTHOREMAIL__ in fixed notifications (#37285) * Update notification.php * Update notify.class.php * Update mails.lang * Update mails.lang * Update notify.class.php --------- Co-authored-by: Laurent Destailleur --- htdocs/admin/notification.php | 9 +- htdocs/core/class/notify.class.php | 144 ++++++++++++++++++++--------- htdocs/langs/en_US/mails.lang | 1 + htdocs/langs/fr_FR/mails.lang | 1 + 4 files changed, 108 insertions(+), 47 deletions(-) diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php index b8fdfa13b4a..23afb9d83a8 100644 --- a/htdocs/admin/notification.php +++ b/htdocs/admin/notification.php @@ -5,7 +5,8 @@ * Copyright (C) 2015 Bahfir Abbes * Copyright (C) 2020 Thibault FOUCART * Copyright (C) 2022 Anthony Berton - * Copyright (C) 2024-2025 Frédéric France + * Copyright (C) 2024-2025 Frédéric France + * Copyright (C) 2026 Pierre Ardoin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -487,14 +488,14 @@ foreach ($listofnotifiedevents as $notifiedevent) { $showwarning = 0; foreach ($arrayemail as $keydet => $valuedet) { $valuedet = trim($valuedet); - if (!empty($valuedet) && !isValidEmail($valuedet, 1)) { + if (!empty($valuedet) && $valuedet != '__SUPERVISOREMAIL__' && $valuedet != '__AUTHOREMAIL__' && !isValidEmail($valuedet, 1)) { $showwarning++; } } if (getDolGlobalString($param) && $showwarning) { $s .= ' '.img_warning($langs->trans("ErrorBadEMail")); } - print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2); + print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword").'
'.$langs->trans("YouCanAlsoUseAuthorKeyword"), 1, 'help', '', 0, 2); print '
'; $inputfieldalreadyshown++; @@ -502,7 +503,7 @@ foreach ($listofnotifiedevents as $notifiedevent) { // New entry input fields if (empty($inputfieldalreadyshown) || !$codehasnotrigger) { $s = ''; // Do not use type="email" here, we must be able to enter a list of email with , separator. - print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2); + print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
'.$langs->trans("YouCanAlsoUseSupervisorKeyword").'
'.$langs->trans("YouCanAlsoUseAuthorKeyword"), 1, 'help', '', 0, 2); } print ''; diff --git a/htdocs/core/class/notify.class.php b/htdocs/core/class/notify.class.php index 486a23eade2..e08c16782d4 100644 --- a/htdocs/core/class/notify.class.php +++ b/htdocs/core/class/notify.class.php @@ -9,6 +9,7 @@ * Copyright (C) 2024 Jon Bendtsen * Copyright (C) 2024 MDW * Copyright (C) 2024-2025 Frédéric France + * Copyright (C) 2026 Pierre Ardoin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -582,17 +583,10 @@ class Notify foreach ($tmpemail as $key2 => $val2) { $newval2 = trim($val2); if ($newval2 == '__SUPERVISOREMAIL__') { - if ($user->fk_user > 0) { - $tmpuser = new User($this->db); - $tmpuser->fetch($user->fk_user); - if ($tmpuser->email) { - $newval2 = trim($tmpuser->email); - } else { - $newval2 = ''; - } - } else { - $newval2 = ''; - } + $newval2 = $this->getSupervisorEmail(); + } + if ($newval2 == '__AUTHOREMAIL__') { + $newval2 = $this->getAuthorEmail($object); } if ($newval2) { $isvalid = isValidEmail($newval2, 0); @@ -984,22 +978,8 @@ class Notify $labeltouse = !empty($labeltouse) ? $labeltouse : ''; - // Replace keyword __SUPERVISOREMAIL__ - if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) { - $newval = ''; - if ($user->fk_user > 0) { - $supervisoruser = new User($this->db); - $supervisoruser->fetch($user->fk_user); - if ($supervisoruser->email) { - $newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); - } - } - dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval); - $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto); - $sendto = preg_replace('/,\s*,/', ',', $sendto); // in some case you can have $sendto like "email, __SUPERVISOREMAIL__ , otheremail" then you have "email, , othermail" and it's not valid - $sendto = preg_replace('/^[\s,]+/', '', $sendto); // Clean start of string - $sendto = preg_replace('/[\s,]+$/', '', $sendto); // Clean end of string - } + $sendto = $this->replaceSpecialRecipientToken($sendto, '__SUPERVISOREMAIL__', $this->getSupervisorEmail(1)); + $sendto = $this->replaceSpecialRecipientToken($sendto, '__AUTHOREMAIL__', $this->getAuthorEmail($object, 1)); $parameters = array('notifcode' => $notifcode, 'sendto' => $sendto, 'from' => $from, 'file' => $filename_list, 'mimefile' => $mimetype_list, 'filename' => $mimefilename_list, 'outputlangs' => $outputlangs, 'labeltouse' => $labeltouse); if (!isset($action)) { @@ -1315,22 +1295,8 @@ class Notify $message = nl2br($message); } - // Replace keyword __SUPERVISOREMAIL__ - if (preg_match('/__SUPERVISOREMAIL__/', $sendto)) { - $newval = ''; - if ($user->fk_user > 0) { - $supervisoruser = new User($this->db); - $supervisoruser->fetch($user->fk_user); - if ($supervisoruser->email) { - $newval = trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); - } - } - dol_syslog("Replace the __SUPERVISOREMAIL__ key into recipient email string with ".$newval); - $sendto = preg_replace('/__SUPERVISOREMAIL__/', $newval, $sendto); - $sendto = preg_replace('/,\s*,/', ',', $sendto); // in some case you can have $sendto like "email, __SUPERVISOREMAIL__ , otheremail" then you have "email, , othermail" and it's not valid - $sendto = preg_replace('/^[\s,]+/', '', $sendto); // Clean start of string - $sendto = preg_replace('/[\s,]+$/', '', $sendto); // Clean end of string - } + $sendto = $this->replaceSpecialRecipientToken($sendto, '__SUPERVISOREMAIL__', $this->getSupervisorEmail(1)); + $sendto = $this->replaceSpecialRecipientToken($sendto, '__AUTHOREMAIL__', $this->getAuthorEmail($object, 1)); if ($sendto) { $parameters = array('notifcode' => $notifcode, 'sendto' => $sendto, 'from' => $from, 'file' => $filename_list, 'mimefile' => $mimetype_list, 'filename' => $mimefilename_list, 'subject' => &$subject, 'message' => &$message); @@ -1393,4 +1359,96 @@ class Notify return -1 * $error; } } + + /** + * Return supervisor email. + * + * @param int<0,1> $withLabel 1=Return "Firstname Lastname ", 0=Return "email" + * @return string + */ + private function getSupervisorEmail($withLabel = 0) + { + global $user; + + if (empty($user->fk_user) || $user->fk_user <= 0) { + return ''; + } + + $supervisoruser = new User($this->db); + $supervisoruser->fetch($user->fk_user); + if (empty($supervisoruser->email)) { + return ''; + } + + if ($withLabel) { + return trim(dolGetFirstLastname($supervisoruser->firstname, $supervisoruser->lastname).' <'.$supervisoruser->email.'>'); + } + + return trim((string) $supervisoruser->email); + } + + /** + * Return author email of object. + * + * @param CommonObject|null $object Object used to resolve author + * @param int<0,1> $withLabel 1=Return "Firstname Lastname ", 0=Return "email" + * @return string + */ + private function getAuthorEmail($object, $withLabel = 0) + { + if (!is_object($object)) { + return ''; + } + + $author = null; + + if (isset($object->user_author) && is_object($object->user_author) && !empty($object->user_author->email)) { + $author = $object->user_author; + } else { + $authorid = 0; + foreach (array('fk_user_author', 'user_author_id', 'fk_user_creat') as $fieldname) { + if (!empty($object->$fieldname)) { + $authorid = (int) $object->$fieldname; + break; + } + } + if ($authorid > 0) { + $author = new User($this->db); + $author->fetch($authorid); + } + } + + if (empty($author) || empty($author->email)) { + return ''; + } + + if ($withLabel) { + return trim(dolGetFirstLastname($author->firstname, $author->lastname).' <'.$author->email.'>'); + } + + return trim((string) $author->email); + } + + /** + * Replace a special token inside recipient list. + * + * @param string $sendto Recipient list + * @param string $token Token to replace + * @param string $replacement Replacement value + * @return string + */ + private function replaceSpecialRecipientToken($sendto, $token, $replacement) + { + if (!preg_match('/'.preg_quote($token, '/').'/', $sendto)) { + return $sendto; + } + + dol_syslog("Replace the ".$token." key into recipient email string with ".$replacement); + $sendto = preg_replace('/'.preg_quote($token, '/').'/', $replacement, $sendto); + $sendto = preg_replace('/,\s*,/', ',', $sendto); // In some case you can have $sendto like "email, __SUPERVISOREMAIL__ , otheremail" then you have "email, , othermail" and it's not valid + $sendto = preg_replace('/^[\s,]+/', '', $sendto); // Clean start of string + $sendto = preg_replace('/[\s,]+$/', '', $sendto); // Clean end of string + + return $sendto; + } } diff --git a/htdocs/langs/en_US/mails.lang b/htdocs/langs/en_US/mails.lang index 1bed9994a79..a486296dcac 100644 --- a/htdocs/langs/en_US/mails.lang +++ b/htdocs/langs/en_US/mails.lang @@ -152,6 +152,7 @@ MailSendSetupIs=Configuration of email sending has been setup to '%s'. This mode MailSendSetupIs2=You must first go, with an admin account, into menu %sHome - Setup - EMails%s to change parameter '%s' to use mode '%s'. With this mode, you can enter setup of the SMTP server provided by your Internet Service Provider and use Mass emailing feature. MailSendSetupIs3=If you have any questions on how to setup your SMTP server, you can ask to %s. YouCanAlsoUseSupervisorKeyword=You can also add the keyword __SUPERVISOREMAIL__ to have email being sent to the supervisor of user (works only if an email is defined for this supervisor) +YouCanAlsoUseAuthorKeyword=You can also add the keyword __AUTHOREMAIL__ to have email being sent to the author of the document (works only if an email is defined for this author) NbOfTargetedContacts=Current number of targeted contact emails UseFormatFileEmailToTarget=Imported file must have format email;name;firstname;other UseFormatInputEmailToTarget=Enter a string with format email;name;firstname;other diff --git a/htdocs/langs/fr_FR/mails.lang b/htdocs/langs/fr_FR/mails.lang index 0236792f970..8c5d17a86f6 100644 --- a/htdocs/langs/fr_FR/mails.lang +++ b/htdocs/langs/fr_FR/mails.lang @@ -152,6 +152,7 @@ MailSendSetupIs=La configuration d'envoi d'emails a été définir sur '%s'. Ce MailSendSetupIs2=Vous devez d'abord aller, avec un compte d'administrateur, dans le menu %sAccueil - Configuration - EMails%s pour changer le paramètre '%s' pour utiliser le mode '%s'. Avec ce mode, vous pouvez entrer le paramétrage du serveur SMTP fourni par votre fournisseur de services Internet et utiliser la fonction d'envoi d'email en masse. MailSendSetupIs3=Si vous avez des questions sur la façon de configurer votre serveur SMTP, vous pouvez demander à %s. YouCanAlsoUseSupervisorKeyword=Vous pouvez également ajouter le mot-clé __SUPERVISOREMAIL__ pour avoir les emails envoyés au responsable hiérarchique de l'utilisateur (ne fonctionne que si un email est défini pour ce responsable) +YouCanAlsoUseAuthorKeyword=Vous pouvez également ajouter le mot-clé __AUTHOREMAIL__ pour avoir les emails envoyés à l'auteur du document (ne fonctionne que si un email est défini pour cet auteur) NbOfTargetedContacts=Nombre courant d'emails de contacts cibles UseFormatFileEmailToTarget=Le fichier d'import doit être au format email;name;firstname;other UseFormatInputEmailToTarget=Saisissez une chaîne de caractères au format email;nom;prénom;autre From db3df89ee28cd0da9021d2bf9c0c225b43f55522 Mon Sep 17 00:00:00 2001 From: Lucky <93642903+LuckyRoussel98@users.noreply.github.com> Date: Tue, 24 Feb 2026 20:06:31 +0300 Subject: [PATCH 14/14] New options for withdraw control (#37179) * New options for withdraw control Add a new option "WITHDRAW_STRICT_CHECK_AMOUNT" Transfer request control is based solely on the supplier invoice amount: By default, once a request is made, even if its amount is less than the invoice amount, no additional requests can be made until the original request is validated (integrated into a transfer slip). With this option, the control is applied to the sum of all requests, even if they are not integrated into a SEPA transfer slip. The control verifies that the total sum of the requests never exceeds the invoice total. By default, one or more requests exceeding the invoice amount can be entered; this option prevents this behavior. This behavior is more logical and user-friendly, especially when transfer requests are made by technicians or buyers and the SEPA files are created by the accounting department. * fix * Update commoninvoice.class.php * fichier lang * Cast remaining amounts to float for precision --------- Co-authored-by: Laurent Destailleur --- htdocs/compta/facture/prelevement.php | 183 ++++++++-------- htdocs/core/class/commoninvoice.class.php | 254 ++++++++++++++-------- htdocs/langs/en_US/withdrawals.lang | 2 + htdocs/langs/fr_FR/withdrawals.lang | 2 + 4 files changed, 258 insertions(+), 183 deletions(-) diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index c165adee7a0..742d5e03756 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -797,113 +797,116 @@ if ($object->id > 0) { $buttonlabel = $langs->trans("MakeBankTransferOrder"); $user_perms = $user->hasRight('paymentbybanktransfer', 'create'); } - + // Calculate the remaining amount available for new transfer requests + // This takes into account pending requests (traite=0) and requests in non-credited transfer receipts + $remaintopaylesspendingdebit = $resteapayer - $pending; // Add a transfer request - if ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $numopen == 0) { - if ($resteapayer > 0) { - if ($user_perms) { - $remaintopaylesspendingdebit = $resteapayer - $pending; - - $title = $langs->trans("NewStandingOrder"); - if ($type == 'bank-transfer') { - $title = $langs->trans("NewPaymentByBankTransfer"); + // If WITHDRAW_STRICT_CHECK_AMOUNT is enabled, allow multiple partial requests as long as the total requested amount doesn't exceed the invoice total + // Otherwise, use original behavior: block if any request is pending + if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) { + // New behavior: check remaining amount + $canCreateRequest = ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $remaintopaylesspendingdebit > 0); + } else { + // Original behavior: check if no open requests + $canCreateRequest = ($object->status > $object::STATUS_DRAFT && $object->paid == 0 && $numopen == 0 && $resteapayer > 0); + } + if ($canCreateRequest) { + if ($user_perms) { + $title = $langs->trans("NewStandingOrder"); + if ($type == 'bank-transfer') { + $title = $langs->trans("NewPaymentByBankTransfer"); + } + print ''; + print '
'; + print ''; + print ''; + print ''; + print ''; + print '
'; + //print $langs->trans('CustomerIBAN').' '; + // if societe rib in model invoice, we preselect it + $selectedRib = ''; + if ($object->element == 'invoice' && $object->fk_fac_rec_source) { + $facturerec = new FactureRec($db); + $facturerec->fetch($object->fk_fac_rec_source); + if ($facturerec->fk_societe_rib) { + $companyBankAccount = new CompanyBankAccount($db); + $res = $companyBankAccount->fetch($facturerec->fk_societe_rib); + $selectedRib = $companyBankAccount->id; } - - print ''; - print ''; + } + $selectedRib = $form->selectRib($selectedRib, 'accountcustomerid', 'fk_soc='.$object->socid, $langs->trans("CustomerIBAN"), '', 1, 'maxwidth500 maxwidth250onsmartphone'); + $defaultRibId = $object->thirdparty->getDefaultRib(); + if ($defaultRibId) { + $companyBankAccount = new CompanyBankAccount($db); + $res = $companyBankAccount->fetch($defaultRibId); + if ($res > 0 && !$companyBankAccount->verif()) { + print img_warning('Error on default bank number for IBAN : '.$langs->trans($companyBankAccount->error)); + } + } elseif (($type != 'bank-transfer' && $object->mode_reglement_code == 'PRE') || ($type == 'bank-transfer' && $object->mode_reglement_code == 'VIR')) { + print img_warning($langs->trans("NoDefaultIBANFound")); + } + // Bank Transfer Amount + if (getDolOptimizeSmallScreen()) { + print '
'; + } else { + print '     '; + } + print ' '; + print ''; + // Button + print '

'; + print ''; + print '

'; + print '
'; + print '
'; + if (getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT_SHOW_OLD_BUTTON')) { // This is hidden, prefer to use mode enabled with STRIPE_SEPA_DIRECT_DEBIT + // TODO Replace this with a checkbox for each payment mode: "Send request to XXX immediately..." + print "
"; + // Add stripe sepa button + $buttonlabel = $langs->trans("MakeWithdrawRequestStripe"); + print '
'; print ''; print ''; print ''; print ''; - - print '
'; - - //print $langs->trans('CustomerIBAN').' '; - - // if societe rib in model invoice, we preselect it - $selectedRib = ''; - if ($object->element == 'invoice' && $object->fk_fac_rec_source) { - $facturerec = new FactureRec($db); - $facturerec->fetch($object->fk_fac_rec_source); - if ($facturerec->fk_societe_rib) { - $companyBankAccount = new CompanyBankAccount($db); - $res = $companyBankAccount->fetch($facturerec->fk_societe_rib); - $selectedRib = $companyBankAccount->id; - } - } - - $selectedRib = $form->selectRib($selectedRib, 'accountcustomerid', 'fk_soc='.$object->socid, $langs->trans("CustomerIBAN"), '', 1, 'maxwidth500 maxwidth250onsmartphone'); - - $defaultRibId = $object->thirdparty->getDefaultRib(); - if ($defaultRibId) { - $companyBankAccount = new CompanyBankAccount($db); - $res = $companyBankAccount->fetch($defaultRibId); - if ($res > 0 && !$companyBankAccount->verif()) { - print img_warning('Error on default bank number for IBAN : '.$langs->trans($companyBankAccount->error)); - } - } elseif (($type != 'bank-transfer' && $object->mode_reglement_code == 'PRE') || ($type == 'bank-transfer' && $object->mode_reglement_code == 'VIR')) { - print img_warning($langs->trans("NoDefaultIBANFound")); - } - - - // Bank Transfer Amount - if (getDolOptimizeSmallScreen()) { - print '
'; - } else { - print '     '; - } - print ' '; - print ''; - - // Button - print '

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

'; - - print '
'; - print '
'; - - if (getDolGlobalString('STRIPE_SEPA_DIRECT_DEBIT_SHOW_OLD_BUTTON')) { // This is hidden, prefer to use mode enabled with STRIPE_SEPA_DIRECT_DEBIT - // TODO Replace this with a checkbox for each payment mode: "Send request to XXX immediately..." - print "
"; - // Add stripe sepa button - $buttonlabel = $langs->trans("MakeWithdrawRequestStripe"); - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'; - } - } else { - print ''.$buttonlabel.''; } } else { - print ''.$buttonlabel.''; + print ''.$buttonlabel.''; } } else { - if ($numopen == 0) { - if ($object->status > $object::STATUS_DRAFT) { - print ''.$buttonlabel.''; + // Different error messages based on the mode + if ($object->status > $object::STATUS_DRAFT) { + if ($object->paid == 0) { + if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) { + // Total amount has already been requested (pending + in transfer receipts) + print ''.$buttonlabel.''; + } else { + // Original behavior: request already done or amount must be positive + if ($numopen > 0) { + print ''.$buttonlabel.''; + } else { + print ''.$buttonlabel.''; + } + } } else { - print ''.$buttonlabel.''; + print ''.$buttonlabel.''; } } else { - print ''.$buttonlabel.''; + print ''.$buttonlabel.''; } } - print "\n"; diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index b0717809528..8438da1e5ba 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -1331,102 +1331,170 @@ abstract class CommonInvoice extends CommonObject $bac = new CompanyBankAccount($this->db); $bac->fetch($ribId, '', $this->socid); - $sql = "SELECT count(rowid) as nb"; - $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; - if ($type == 'bank-transfer') { - $sql .= " WHERE fk_facture_fourn = ".((int) $this->id); - } else { - $sql .= " WHERE fk_facture = ".((int) $this->id); - } - $sql .= " AND type = 'ban'"; // To exclude record done for some online payments - if (empty($checkduplicateamongall)) { - $sql .= " AND traite = 0"; - } - - dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); - - $resql = $this->db->query($sql); - if ($resql) { - $obj = $this->db->fetch_object($resql); - if ($obj && $obj->nb == 0) { // If no request found yet - $now = dol_now(); - - $totalpaid = $this->getSommePaiement(); - $totalcreditnotes = $this->getSumCreditNotesUsed(); - $totaldeposits = $this->getSumDepositsUsed(); - //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits; - - // We can also use bcadd to avoid pb with floating points - // For example print 239.2 - 229.3 - 9.9; does not return 0. - //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT); - //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); - if (empty($amount)) { - $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT'); - } - - if (is_numeric($amount) && $amount != 0) { - $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande('; - if ($type == 'bank-transfer') { - $sql .= 'fk_facture_fourn, '; - } else { - $sql .= 'fk_facture, '; - } - $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity'; - if (empty($bac->id)) { - $sql .= ')'; - } else { - $sql .= ', fk_societe_rib)'; - } - $sql .= " VALUES (".((int) $this->id); - $sql .= ", ".((float) price2num($amount)); - $sql .= ", '".$this->db->idate($now)."'"; - $sql .= ", ".((int) $fuser->id); - $sql .= ", '".$this->db->escape($bac->code_banque)."'"; - $sql .= ", '".$this->db->escape($bac->code_guichet)."'"; - $sql .= ", '".$this->db->escape($bac->number)."'"; - $sql .= ", '".$this->db->escape($bac->cle_rib)."'"; - $sql .= ", '".$this->db->escape($sourcetype)."'"; - $sql .= ", 'ban'"; - $sql .= ", ".((int) $conf->entity); - if (!empty($bac->id)) { - $sql .= ", '".$this->db->escape((string) $bac->id)."'"; - } - $sql .= ")"; - - dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) { - $this->error = $this->db->lasterror(); - dol_syslog(get_class($this).'::demandeprelevement Erreur'); - $error++; - } - } else { - $this->error = 'WithdrawRequestErrorNilAmount'; - dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount'); - $error++; - } - - if (!$error) { - // Force payment mode of invoice to withdraw - $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1); - if ($payment_mode_id > 0) { - $result = $this->setPaymentMethods($payment_mode_id); - } - } - - if ($error) { - return -1; - } - return 1; + // Option to allow multiple partial requests + // If WITHDRAW_STRICT_CHECK_AMOUNT is enabled, we check the sum of amounts instead of just counting requests + if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) { + // Calculate sum of amounts already requested instead of just counting requests + // This allows multiple partial requests as long as the total doesn't exceed the remain to pay + $total_already_requested = 0; + // Step 1: Get pending requests with no transfer receipt yet (traite = 0) + $sql = "SELECT COALESCE(SUM(amount), 0) as total_requested"; + $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; + if ($type == 'bank-transfer') { + $sql .= " WHERE fk_facture_fourn = ".((int) $this->id); } else { - $this->error = "A request already exists"; - dol_syslog(get_class($this).'::demandeprelevement Can t create a request to generate a direct debit, a request already exists.'); - return 0; + $sql .= " WHERE fk_facture = ".((int) $this->id); + } + $sql .= " AND type = 'ban'"; // To exclude record done for some online payments + $sql .= " AND traite = 0"; // Not yet in a transfer receipt + dol_syslog(get_class($this)."::demande_prelevement - get pending requests not yet in receipt", LOG_DEBUG); + $resql= $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + $total_already_requested += $obj ? (float) $obj->total_requested : 0; + } else { + $this->error = $this->db->error(); + dol_syslog(get_class($this).'::demandeprelevement Error -2a'); + return -2; + } + // Step 2: Get pending requests in transfer receipt but not yet credited + $sql = "SELECT COALESCE(SUM(pl.amount), 0) as total_requested"; + $sql .= " FROM ".$this->db->prefix()."prelevement_lignes as pl"; + $sql .= " INNER JOIN ".$this->db->prefix()."prelevement as p ON p.fk_prelevement_lignes = pl.rowid"; + if ($type == 'bank-transfer') { + $sql .= " WHERE p.fk_facture_fourn = ".((int) $this->id); + } else { + $sql .= " WHERE p.fk_facture = ".((int) $this->id); + } + $sql .= " AND (pl.statut IS NULL OR pl.statut = 0)"; // Not yet processed (statut 2 = credited) + dol_syslog(get_class($this)."::demande_prelevement - get requests in non-credited receipts", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + $total_already_requested += $obj ? (float) $obj->total_requested : 0; + // Calculate remain to pay + $totalpaid = $this->getSommePaiement(); + $totalcreditnotes = $this->getSumCreditNotesUsed(); + $totaldeposits = $this->getSumDepositsUsed(); + $resteapayer = (float) price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT'); + // Calculate remaining amount available for new requests + $remaining_for_request = (float) price2num($resteapayer - $total_already_requested, 'MT'); + // If no amount specified, use the remaining available + if (empty($amount)) { + $amount = $remaining_for_request; + } + // Check if there's still room for new requests + $can_create_request = ($remaining_for_request > 0 && $amount <= $remaining_for_request); + } else { + $this->error = $this->db->error(); + dol_syslog(get_class($this).'::demandeprelevement Error -2b'); + return -2; } } else { - $this->error = $this->db->error(); - dol_syslog(get_class($this).'::demandeprelevement Error -2'); - return -2; + // Original behavior: only check if a request already exists (count) + $sql = "SELECT count(rowid) as nb"; + $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; + if ($type == 'bank-transfer') { + $sql .= " WHERE fk_facture_fourn = ".((int) $this->id); + } else { + $sql .= " WHERE fk_facture = ".((int) $this->id); + } + $sql .= " AND type = 'ban'"; // To exclude record done for some online payments + if (empty($checkduplicateamongall)) { + $sql .= " AND traite = 0"; + } + + dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); + + $resql = $this->db->query($sql); + if ($resql) { + $obj = $this->db->fetch_object($resql); + $can_create_request = ($obj && $obj->nb == 0); + // Calculate amount if not specified + if (empty($amount)) { + $totalpaid = $this->getSommePaiement(); + $totalcreditnotes = $this->getSumCreditNotesUsed(); + $totaldeposits = $this->getSumDepositsUsed(); + //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits; + // We can also use bcadd to avoid pb with floating points + // For example print 239.2 - 229.3 - 9.9; does not return 0. + //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT); + //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); + $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT'); + } + $remaining_for_request = $amount; // For error message compatibility + } else { + $this->error = $this->db->error(); + dol_syslog(get_class($this).'::demandeprelevement Error -2'); + return -2; + } + } + // Common code for both modes + if ($can_create_request) { + $now = dol_now(); + if (is_numeric($amount) && $amount != 0) { + $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande('; + if ($type == 'bank-transfer') { + $sql .= 'fk_facture_fourn, '; + } else { + $sql .= 'fk_facture, '; + } + $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, type, entity'; + if (empty($bac->id)) { + $sql .= ')'; + } else { + $sql .= ', fk_societe_rib)'; + } + $sql .= " VALUES (".((int) $this->id); + $sql .= ", ".((float) price2num($amount)); + $sql .= ", '".$this->db->idate($now)."'"; + $sql .= ", ".((int) $fuser->id); + $sql .= ", '".$this->db->escape($bac->code_banque)."'"; + $sql .= ", '".$this->db->escape($bac->code_guichet)."'"; + $sql .= ", '".$this->db->escape($bac->number)."'"; + $sql .= ", '".$this->db->escape($bac->cle_rib)."'"; + $sql .= ", '".$this->db->escape($sourcetype)."'"; + $sql .= ", 'ban'"; + $sql .= ", ".((int) $conf->entity); + if (!empty($bac->id)) { + $sql .= ", '".$this->db->escape((string) $bac->id)."'"; + } + $sql .= ")"; + dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = $this->db->lasterror(); + dol_syslog(get_class($this).'::demandeprelevement Erreur'); + $error++; + } + } else { + $this->error = 'WithdrawRequestErrorNilAmount'; + dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount'); + $error++; + } + if (!$error) { + // Force payment mode of invoice to withdraw + $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1); + if ($payment_mode_id > 0) { + $result = $this->setPaymentMethods($payment_mode_id); + } + } + if ($error) { + return -1; + } + return 1; + } else { + // Updated error message for when amount exceeds remaining or request already exists + if (getDolGlobalString('WITHDRAW_STRICT_CHECK_AMOUNT')) { + if ($remaining_for_request <= 0) { + $this->error = "AmountRequestedAlreadyReachesTotal"; + } else { + $this->error = "AmountExceedsRemainingToRequest"; + } + } else { + $this->error = "A request already exists"; + } + return 0; } } else { $this->error = "Status of invoice does not allow this"; diff --git a/htdocs/langs/en_US/withdrawals.lang b/htdocs/langs/en_US/withdrawals.lang index 03d9e1dced8..2391a75d6dd 100644 --- a/htdocs/langs/en_US/withdrawals.lang +++ b/htdocs/langs/en_US/withdrawals.lang @@ -173,3 +173,5 @@ RefSalary=Salary NoSalaryInvoiceToWithdraw=No salary waiting for a '%s'. Go on tab '%s' on salary card to make a request. SalaryInvoiceWaitingWithdraw=Salaries waiting for payment by credit transfer ErrorBankTransferNoPaymentRequestSelected=No payment request selected. +AmountRequestedAlreadyReachesTotal=The total invoice amount has already been requested for payment +AmountExceedsRemainingToRequest=The requested amount exceeds the remaining amount available for payment requests diff --git a/htdocs/langs/fr_FR/withdrawals.lang b/htdocs/langs/fr_FR/withdrawals.lang index 6c11ebd6aa7..8e1bcba9ff4 100644 --- a/htdocs/langs/fr_FR/withdrawals.lang +++ b/htdocs/langs/fr_FR/withdrawals.lang @@ -173,3 +173,5 @@ RefSalary=Salaire NoSalaryInvoiceToWithdraw=Aucun salaire n'attend un '%s'. Allez sur l'onglet '%s' sur la fiche salaire pour faire une demande. SalaryInvoiceWaitingWithdraw=Salaires en attente de paiement par virement bancaire ErrorBankTransferNoPaymentRequestSelected=Aucune demande de paiement sélectionnée. +AmountRequestedAlreadyReachesTotal=Le montant total de la facture a déjà été demandé +AmountExceedsRemainingToRequest=Le montant demandé dépasse le montant restant disponible pour les demandes de paiement