dolibarr 25.0.0-alpha
paymentref.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Nick Fragoulis
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
34function dolPayRefGetSchemeForCountry($country_code)
35{
36 switch (dol_strtoupper((string) $country_code)) {
37 case 'BE':
38 // Belgian OGM-VCS structured communication, see functions_be.lib.php
39 return 'BE';
40 case 'FI':
41 // Finnish national reference or finnish RF, see functions_fi.lib.php
42 return 'FI';
43 case 'GR':
44 // DIAS RF with an embedded 5 digit merchant code, see functions_gr.lib.php
45 return 'GR';
46 default:
47 // DE, CH, AT, NL, FR, IT, ES, SE and other SEPA countries use plain
48 // ISO 11649 with no national deviation, see functions_creditorref.lib.php
49 return 'RF';
50 }
51}
52
67function dolPayRefFormatForDisplay($ref, $country_code = '')
68{
69 $ref = (string) $ref;
70 if ($ref === '') {
71 return '';
72 }
73
74 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
75
76 if (dolPayRefDetectScheme($ref) == 'BBA') {
77 return $ref;
78 }
79 if (dolPayRefGetSchemeForCountry($country_code) == 'GR') {
80 return dolPayRefStrip($ref);
81 }
82
83 return dolPayRefFormat(dolPayRefStrip($ref));
84}
85
98function dolPayRefGetSetupWarning($country_code, $mode = '')
99{
100 if ($mode == '') {
101 $mode = getDolGlobalString('INVOICE_PAYMENT_REF_MODE');
102 }
103 if (!$mode) {
104 return '';
105 }
106
107 if (dolPayRefGetSchemeForCountry($country_code) == 'GR') {
108 // A company that already has a complete reference issues it as it is, so
109 // nothing is generated and the DIAS code is not needed.
110 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
111 $alreadycomplete = ($mode == 'company'
112 && dolCreditorRefIsValid(getDolGlobalString('MAIN_INFO_SOCIETE_PAYMENT_ID')));
113
114 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_gr.lib.php';
115 $diascode = preg_replace('/[^0-9]/', '', getDolGlobalString('MAIN_INFO_SOCIETE_DIAS_CODE'));
116 if (!$alreadycomplete && !dolGRIsValidDiasCode($diascode)) {
117 // References already written on a third party keep working without the
118 // code, only a third party that has none yet needs one generated.
119 if ($mode == 'thirdparty') {
120 return 'WarningPaymentRefDIASCodeMissingThirdparty';
121 }
122 return 'WarningPaymentRefDIASCodeMissing';
123 }
124 }
125
126 if ($mode == 'company' && !getDolGlobalString('MAIN_INFO_SOCIETE_PAYMENT_ID')) {
127 return 'WarningPaymentRefPaymentIdMissing';
128 }
129
130 // The company reference is printed on every invoice, so it must not ask the bank
131 // to check one fixed amount.
132 if ($mode == 'company' && dolPayRefGetSchemeForCountry($country_code) == 'GR') {
133 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_gr.lib.php';
134 if (dolGRIsAmountCheckedReference(getDolGlobalString('MAIN_INFO_SOCIETE_PAYMENT_ID'))) {
135 return 'ErrorDIASReferenceAmountChecked';
136 }
137 }
138
139 return '';
140}
141
154function dolPayRefBuild($payment_id, $statut, $country_code, $invoice_type = 0)
155{
156 if ($statut < 1) {
157 return '';
158 }
159
160 // A value that is already a complete reference is kept as it is. A company that
161 // used a reference before this feature existed can therefore keep issuing the
162 // one its customers already pay against.
163 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
164 if (dolCreditorRefIsValid((string) $payment_id) || strpos((string) $payment_id, '+++') === 0) {
165 // A greek reference that checks one fixed amount would be refused by the bank
166 // for any other amount, so it is never reused on several invoices.
167 if (dolPayRefGetSchemeForCountry($country_code) == 'GR') {
168 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_gr.lib.php';
169 if (dolGRIsAmountCheckedReference((string) $payment_id)) {
170 dol_syslog('dolPayRefBuild: greek reference '.$payment_id.' checks a fixed amount, not used', LOG_WARNING);
171 return '';
172 }
173 }
174 return dolPayRefStrip((string) $payment_id);
175 }
176
177 // A finnish national reference carries its own check digit, so one that is
178 // already complete is kept too, instead of being used as a base for a new one.
179 if (dolPayRefGetSchemeForCountry($country_code) == 'FI') {
180 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_fi.lib.php';
181 if (dolFIIsValidReference((string) $payment_id)) {
182 return dolPayRefStrip((string) $payment_id);
183 }
184 }
185
186 switch (dolPayRefGetSchemeForCountry($country_code)) {
187 case 'BE':
188 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_be.lib.php';
189 return dolBECalculateStructuredCommunication((string) $payment_id, $invoice_type);
190
191 case 'FI':
192 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_fi.lib.php';
193 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
194 // Finnish RF is accepted for both domestic and cross border payments.
195 // Since 18 november 2024 a plain ISO 11649 reference is also valid in
196 // Finland, but the RF form built on the national reference stays the
197 // most widely supported, so it is the default here.
198 return dolPayRefStrip(dolFICalculatePaymentReference((string) $payment_id, $statut, 1));
199
200 case 'GR':
201 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_gr.lib.php';
202 return dolGRCalculateCreditorReference((string) $payment_id, $statut);
203
204 default:
205 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
206 return dolCreditorRefGenerate((string) $payment_id, $statut);
207 }
208}
209
233function dolPayRefGenerateForInvoice($object, $user, $store = 1)
234{
235 global $mysoc;
236
237 $mode = getDolGlobalString('INVOICE_PAYMENT_REF_MODE');
238
239 if (empty($mode) || $mode === 'disabled' || !is_object($object)) {
240 return '';
241 }
242
243 $statut = isset($object->status) ? (int) $object->status : (int) $object->statut;
244 $country_code = empty($mysoc->country_code) ? '' : $mysoc->country_code;
245 // The invoice type only means something on an invoice, it drives the belgian scheme.
246 // A proposal or an order previewing its future reference has none.
247 $type = ($object instanceof CommonInvoice) ? (int) $object->type : 0;
248
249 if (!is_object($object->thirdparty)) {
250 $object->fetch_thirdparty();
251 }
252
253 $ref = '';
254
255 if ($mode === 'company') {
256 // One fixed reference for the whole company
257 $ref = dolPayRefBuild(getDolGlobalString('MAIN_INFO_SOCIETE_PAYMENT_ID', '0'), $statut, $country_code, $type);
258 } elseif ($mode === 'thirdparty') {
259 // Reuse the reference already stored on the customer when there is one
260 if (!empty($object->thirdparty->tp_payment_reference)) {
261 $ref = $object->thirdparty->tp_payment_reference;
262 } else {
263 $base = '';
264 $base = dolPayRefGetThirdpartyBase($object->thirdparty);
265
266 $ref = dolPayRefBuild($base, $statut, $country_code, $type);
267
268 // Keep it on the customer so every later invoice reuses the same value
269 if ($ref !== '' && $store) {
270 $object->thirdparty->setValueFrom('tp_payment_reference', $ref, '', null, 'text', '', $user, 'COMPANY_MODIFY');
271 $object->thirdparty->tp_payment_reference = $ref;
272 }
273 }
274 } elseif ($mode === 'invoice') {
276 if (empty($parts)) {
277 return '';
278 }
279 if (dolPayRefGetSchemeForCountry($country_code) === 'RF' && count($parts) > 1) {
280 include_once DOL_DOCUMENT_ROOT.'/core/lib/functions_creditorref.lib.php';
281 $ref = dolCreditorRefGenerateFromParts($parts, $statut);
282 } else {
283 $ref = dolPayRefBuild(implode('', $parts), $statut, $country_code, $type);
284 }
285 }
286
287 if ($ref === '') {
288 dol_syslog('dolPayRefGenerateForInvoice: no reference produced for '.$object->ref.' mode '.$mode, LOG_WARNING);
289 return '';
290 }
291
292 // llx_facture.payment_reference is varchar(25)
293 if (dol_strlen($ref) > 25) {
294 dol_syslog('dolPayRefGenerateForInvoice: reference longer than 25 chars, not stored', LOG_WARNING);
295 return '';
296 }
297
298 if ($store && $statut >= 1) {
299 $object->setValueFrom('payment_reference', $ref, '', null, 'text', '', $user, 'BILL_MODIFY');
300 $object->payment_reference = $ref;
301 }
302
303 return $ref;
304}
305
316function dolPayRefGetThirdpartyBase($thirdparty)
317{
318 $field = getDolGlobalString('INVOICE_PAYMENT_REF_TP_BASE', 'code_client');
319
320 if ($field == 'code_fournisseur' && !empty($thirdparty->code_fournisseur)) {
321 return (string) $thirdparty->code_fournisseur;
322 }
323 if ($field == 'code_client' && !empty($thirdparty->code_client)) {
324 return (string) $thirdparty->code_client;
325 }
326 if ($field == 'rowid') {
327 return (string) $thirdparty->id;
328 }
329
330 // The chosen field is empty on this third party, fall back so a reference still exists
331 if (!empty($thirdparty->code_client)) {
332 return (string) $thirdparty->code_client;
333 }
334 if (!empty($thirdparty->code_fournisseur)) {
335 return (string) $thirdparty->code_fournisseur;
336 }
337
338 return (string) $thirdparty->id;
339}
340
351{
352 $wanted = getDolGlobalString('INVOICE_PAYMENT_REF_PARTS', 'invoice_ref');
353 $allowed = array('customer_code', 'contract_ref', 'invoice_ref');
354 $parts = array();
355
356 foreach (explode(',', $wanted) as $part) {
357 $part = trim($part);
358 if (!in_array($part, $allowed)) {
359 continue;
360 }
361
362 $value = '';
363 if ($part === 'customer_code' && is_object($object->thirdparty)) {
364 $value = (string) $object->thirdparty->code_client;
365 } elseif ($part === 'contract_ref') {
367 } elseif ($part === 'invoice_ref') {
368 $value = (string) $object->ref;
369 }
370
371 if ($value !== '') {
372 $parts[] = $value;
373 }
374 }
375
376 return $parts;
377}
378
386{
387 if (empty($object->id) || !is_object($object->db)) {
388 return '';
389 }
390
391 $sql = "SELECT c.ref";
392 $sql .= " FROM ".$object->db->prefix()."contrat as c";
393 $sql .= " INNER JOIN ".$object->db->prefix()."element_element as ee ON ee.fk_source = c.rowid";
394 $sql .= " WHERE ee.sourcetype = 'contrat'";
395 $sql .= " AND ee.targettype = 'facture'";
396 $sql .= " AND ee.fk_target = ".((int) $object->id);
397 $sql .= " AND c.entity IN (".getEntity('contract').")";
398 $sql .= " ORDER BY c.rowid ASC";
399 $sql .= $object->db->plimit(1);
400
401 $resql = $object->db->query($sql);
402 if ($resql) {
403 $obj = $object->db->fetch_object($resql);
404 $object->db->free($resql);
405 if ($obj) {
406 return (string) $obj->ref;
407 }
408 } else {
409 dol_syslog('dolPayRefGetLinkedContractRef: '.$object->db->lasterror(), LOG_ERR);
410 }
411
412 return '';
413}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Superclass for invoice classes.
global $mysoc
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_strtoupper($string, $encoding="UTF-8")
Convert a string to upper.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dolBECalculateStructuredCommunication($invoice_number, $invoice_type)
Calculate Structured Communication / BE Bank payment reference number.
dolCreditorRefIsValid($ref)
Check that a string is a valid ISO 11649 Structured Creditor Reference.
dolCreditorRefGenerateFromParts($parts, $statut)
Generate an ISO 11649 reference from an ordered list of parts.
dolPayRefStrip($ref)
Remove formatting spaces from a payment reference (machine form).
dolPayRefDetectScheme($ref)
Detect which structured payment reference scheme a stored value belongs to.
dolCreditorRefGenerate($payload, $statut)
Generate an ISO 11649 Structured Creditor Reference from a payload.
dolPayRefFormat($ref)
Format a payment reference into groups of 4 characters (human form).
dolFIIsValidReference($reference)
Check that a string is a valid finnish national reference.
dolFICalculatePaymentReference($invoice_number, $statut, $use_rf)
Calculate Creditor Reference RF / FI Bank payment reference number.
dolGRCalculateCreditorReference($payment_id, $statut, $dias_code='', $usage='')
Calculate a greek DIAS RF Structured Creditor Reference.
dolGRIsValidDiasCode($dias_code)
Check a DIAS creditor code.
dolGRIsAmountCheckedReference($ref)
Tell if a greek DIAS reference asks the paying bank for an amount check.
dolPayRefGetLinkedContractRef($object)
Return the reference of the first contract linked to an invoice.
dolPayRefBuild($payment_id, $statut, $country_code, $invoice_type=0)
Build a structured payment reference from a payment id, for a country.
dolPayRefGetThirdpartyBase($thirdparty)
Return the value a third party builds its payment reference from.
dolPayRefCollectParts($object)
Collect the ordered parts used to build a per invoice reference.
dolPayRefGetSetupWarning($country_code, $mode='')
Return the setup that is still missing before references can be generated.
dolPayRefGetSchemeForCountry($country_code)
Return the payment reference scheme to use for a country.
dolPayRefGenerateForInvoice($object, $user, $store=1)
Generate and optionally store the payment reference of an invoice.
dolPayRefFormatForDisplay($ref, $country_code='')
Format a payment reference the way its country prints it.