dolibarr 24.0.0-beta
lettering.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2004-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2013 Olivier Geffroy <jeff@jeffinfo.com>
4 * Copyright (C) 2013-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
5 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28include_once DOL_DOCUMENT_ROOT."/accountancy/class/bookkeeping.class.php";
29include_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
30include_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
31
36{
40 public static $doc_type_infos = array(
41 'customer_invoice' => array(
42 'payment_table' => 'paiement',
43 'payment_table_fk_bank' => 'fk_bank',
44 'doc_payment_table' => 'paiement_facture',
45 'doc_payment_table_fk_payment' => 'fk_paiement',
46 'doc_payment_table_fk_doc' => 'fk_facture',
47 'linked_info' => array(
48 array(
49 'table' => 'paiement_facture',
50 'fk_doc' => 'fk_facture',
51 'fk_link' => 'fk_paiement',
52 'prefix' => 'p',
53 ),
54 array(
55 'table' => 'societe_remise_except',
56 'fk_doc' => 'fk_facture_source',
57 'fk_link' => 'fk_facture',
58 'fk_line_link' => 'fk_facture_line',
59 'table_link_line' => 'facturedet',
60 'fk_table_link_line' => 'rowid',
61 'fk_table_link_line_parent' => 'fk_facture',
62 'prefix' => 'a',
63 'is_fk_link_is_also_fk_doc' => true,
64 ),
65 ),
66 ),
67 'supplier_invoice' => array(
68 'payment_table' => 'paiementfourn',
69 'payment_table_fk_bank' => 'fk_bank',
70 'doc_payment_table' => 'paiementfourn_facturefourn',
71 'doc_payment_table_fk_payment' => 'fk_paiementfourn',
72 'doc_payment_table_fk_doc' => 'fk_facturefourn',
73 'linked_info' => array(
74 array(
75 'table' => 'paiementfourn_facturefourn',
76 'fk_doc' => 'fk_facturefourn',
77 'fk_link' => 'fk_paiementfourn',
78 'prefix' => 'p',
79 ),
80 array(
81 'table' => 'societe_remise_except',
82 'fk_doc' => 'fk_invoice_supplier_source',
83 'fk_link' => 'fk_invoice_supplier',
84 'fk_line_link' => 'fk_invoice_supplier_line',
85 'table_link_line' => 'facture_fourn_det',
86 'fk_table_link_line' => 'rowid',
87 'fk_table_link_line_parent' => 'fk_facture_fourn',
88 'prefix' => 'a',
89 'is_fk_link_is_also_fk_doc' => true,
90 ),
91 ),
92 ),
93 );
94
101 public function letteringThirdparty($socid)
102 {
103 global $conf;
104
105 $error = 0;
106
107 $object = new Societe($this->db);
108 $object->id = $socid;
109 $object->fetch($socid);
110
111
112 if ($object->code_compta_client == '411CUSTCODE') {
113 $object->code_compta_client = '';
114 }
115
116 if ($object->code_compta_fournisseur == '401SUPPCODE') {
117 $object->code_compta_fournisseur = '';
118 }
119
123 $sql = "SELECT DISTINCT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.subledger_account, ";
124 $sql .= " bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant ";
125 $sql .= " , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type ";
126 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk";
127 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) ";
128 $sql .= " WHERE ( ";
129 if ($object->code_compta_client != "") {
130 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
131 }
132 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
133 $sql .= " OR ";
134 }
135 if ($object->code_compta_fournisseur != "") {
136 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
137 }
138
139 $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) ";
140 $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) ";
141 $sql .= ' AND bk.date_validated IS NULL ';
142 $sql .= $this->db->order('bk.doc_date', 'DESC');
143
144 // echo $sql;
145 //
146 $resql = $this->db->query($sql);
147 if ($resql) {
148 $num = $this->db->num_rows($resql);
149
150 while ($obj = $this->db->fetch_object($resql)) {
151 $ids = array();
152 $ids_fact = array();
153
154 if ($obj->type == 'payment_supplier') {
155 $sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id';
156 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
157 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid";
158 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid";
159 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = payf.fk_bank AND bk.code_journal='".$this->db->escape($obj->code_journal)."')";
160 $sql .= " WHERE payfacf.fk_paiementfourn = '".$this->db->escape($obj->url_id)."' ";
161 $sql .= " AND facf.entity = " . (int) $conf->entity;
162 $sql .= " AND code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=" . (int) $conf->entity . ") ";
163 $sql .= " AND ( ";
164 if ($object->code_compta_client != "") {
165 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
166 }
167 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
168 $sql .= " OR ";
169 }
170 if ($object->code_compta_fournisseur != "") {
171 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
172 }
173 $sql .= " ) ";
174
175 $resql2 = $this->db->query($sql);
176 if ($resql2) {
177 while ($obj2 = $this->db->fetch_object($resql2)) {
178 $ids[$obj2->rowid] = $obj2->rowid;
179 $ids_fact[] = $obj2->fact_id;
180 }
181 $this->db->free($resql2);
182 } else {
183 $this->errors[] = $this->db->lasterror;
184 return -1;
185 }
186 if (count($ids_fact)) {
187 $sql = 'SELECT bk.rowid, facf.ref, facf.ref_supplier ';
188 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
189 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON( bk.fk_doc = facf.rowid AND facf.rowid IN (".$this->db->sanitize(implode(',', $ids_fact))."))";
190 $sql .= " WHERE bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=3 AND entity=". (int) $conf->entity.") ";
191 $sql .= " AND facf.entity = " . (int) $conf->entity;
192 $sql .= " AND ( ";
193 if ($object->code_compta_client != "") {
194 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
195 }
196 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
197 $sql .= " OR ";
198 }
199 if ($object->code_compta_fournisseur != "") {
200 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
201 }
202 $sql .= ") ";
203
204 $resql2 = $this->db->query($sql);
205 if ($resql2) {
206 while ($obj2 = $this->db->fetch_object($resql2)) {
207 $ids[$obj2->rowid] = $obj2->rowid;
208 }
209 $this->db->free($resql2);
210 } else {
211 $this->errors[] = $this->db->lasterror;
212 return -1;
213 }
214 }
215 } elseif ($obj->type == 'payment') {
216 $sql = 'SELECT DISTINCT bk.rowid, fac.ref, fac.ref, pay.fk_bank, fac.rowid as fact_id';
217 $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
218 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement_facture as payfac ON payfac.fk_facture=fac.rowid";
219 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement as pay ON payfac.fk_paiement=pay.rowid";
220 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON (bk.fk_doc = pay.fk_bank AND bk.code_journal='".$this->db->escape($obj->code_journal)."')";
221 $sql .= " WHERE payfac.fk_paiement = '".$this->db->escape($obj->url_id)."' ";
222 $sql .= " AND bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=". (int) $conf->entity.") ";
223 $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
224 $sql .= " AND ( ";
225 if ($object->code_compta_client != "") {
226 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
227 }
228 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
229 $sql .= " OR ";
230 }
231 if ($object->code_compta_fournisseur != "") {
232 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
233 }
234 $sql .= " )";
235
236 $resql2 = $this->db->query($sql);
237 if ($resql2) {
238 while ($obj2 = $this->db->fetch_object($resql2)) {
239 $ids[$obj2->rowid] = $obj2->rowid;
240 $ids_fact[] = $obj2->fact_id;
241 }
242 } else {
243 $this->errors[] = $this->db->lasterror;
244 return -1;
245 }
246 if (count($ids_fact)) {
247 $sql = 'SELECT bk.rowid, fac.ref, fac.ref_supplier ';
248 $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
249 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_bookkeeping as bk ON( bk.fk_doc = fac.rowid AND fac.rowid IN (".$this->db->sanitize(implode(',', $ids_fact))."))";
250 $sql .= " WHERE code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=2 AND entity=". (int) $conf->entity.") ";
251 $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
252 $sql .= " AND ( ";
253 if ($object->code_compta_client != "") {
254 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
255 }
256 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
257 $sql .= " OR ";
258 }
259 if ($object->code_compta_fournisseur != "") {
260 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
261 }
262 $sql .= " ) ";
263
264 $resql2 = $this->db->query($sql);
265 if ($resql2) {
266 while ($obj2 = $this->db->fetch_object($resql2)) {
267 $ids[$obj2->rowid] = $obj2->rowid;
268 }
269 $this->db->free($resql2);
270 } else {
271 $this->errors[] = $this->db->lasterror;
272 return -1;
273 }
274 }
275 }
276
277 if (count($ids) > 1) {
278 $result = $this->updateLettering($ids);
279 }
280 }
281 $this->db->free($resql);
282 }
283 if ($error) {
284 foreach ($this->errors as $errmsg) {
285 dol_syslog(__METHOD__.' '.$errmsg, LOG_ERR);
286 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
287 }
288 return -1 * $error;
289 } else {
290 return 1;
291 }
292 }
293
300 public function updateLettering($ids = array(), $notrigger = 0, $partial = false)
301 {
302 global $langs;
303
304 $now = dol_now();
305 $error = 0;
306 $affected_rows = 0;
307
308 // Generate a string with n char 'A' (for manual/auto reconcile) or 'a' (for partial reconcile) where n is ACCOUNTING_LETTERING_NBLETTERS (So 'AA'/'aa', 'AAA'/'aaa', ...) @phan-suppress-next-line PhanParamSuspiciousOrder
309 $letter = str_pad("", getDolGlobalInt('ACCOUNTING_LETTERING_NBLETTERS', 3), $partial ? 'a' : 'A');
310
311 $this->db->begin();
312
313 // Check partial / normal lettering case
314 $idlist = implode(',', array_map('intval', $ids));
315 $sql = "SELECT ab.lettering_code, GROUP_CONCAT(DISTINCT ab.rowid SEPARATOR ',') AS bookkeeping_ids";
316 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
317 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
318 $sql .= " GROUP BY ab.lettering_code";
319 $sql .= " ORDER BY ab.lettering_code DESC";
320
321 dol_syslog(__METHOD__ . " - Check partial / normal lettering case", LOG_DEBUG);
322 $resql = $this->db->query($sql);
323 if ($resql) {
324 while ($obj = $this->db->fetch_object($resql)) {
325 if (empty($obj->lettering_code)) {
326 continue;
327 }
328
329 // Remove normal lettering code if set partial lettering
330 if ($partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)) {
331 if (!empty($obj->bookkeeping_ids)) {
332 $ids = array_diff($ids, explode(',', $obj->bookkeeping_ids));
333 }
334 } elseif (!$partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) {
335 // Delete partial lettering code if set normal lettering
336 $sql2 = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET";
337 $sql2 .= " matching_general = 0";
338 $sql2 .= ", lettering_code = NULL";
339 $sql2 .= ", date_lettering = NULL";
340 $sql2 .= " WHERE entity IN (" . getEntity('accountancy') . ")";
341 $sql2 .= " AND lettering_code = '" . $this->db->escape($obj->lettering_code) . "'";
342
343 dol_syslog(__METHOD__ . " - Remove partial lettering", LOG_DEBUG);
344 $resql2 = $this->db->query($sql2);
345 if (!$resql2) {
346 $this->errors[] = 'Error' . $this->db->lasterror();
347 $error++;
348 break;
349 }
350 }
351 }
352 $this->db->free($resql);
353 } else {
354 $this->errors[] = 'Error' . $this->db->lasterror();
355 $error++;
356 }
357
358 if (!$error && !empty($ids)) {
359 // Get next code
360 $idlist = implode(',', array_map('intval', $ids));
361 $sql = "SELECT DISTINCT ab2.lettering_code";
362 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
363 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab2 ON ab2.subledger_account = ab.subledger_account";
364 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
365 $sql .= " AND ab2.lettering_code != ''";
366 $sql .= " AND ab2.matching_general = 0";
367 $sql .= " ORDER BY ab2.lettering_code DESC";
368
369 dol_syslog(__METHOD__ . " - Get next code", LOG_DEBUG);
370 $resql = $this->db->query($sql);
371 if ($resql) {
372 while ($obj = $this->db->fetch_object($resql)) {
373 if (!empty($obj->lettering_code) &&
374 (($partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) ||
375 (!$partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)))
376 ) {
377 $letter = $obj->lettering_code;
378 $letter++;
379 break;
380 }
381 }
382 $this->db->free($resql);
383 } else {
384 $this->errors[] = 'Error' . $this->db->lasterror();
385 $error++;
386 }
387
388 // Test amount integrity
389 if (!$error && !$partial) {
390 $idlist = implode(',', array_map('intval', $ids));
391 $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred";
392 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
393 $sql .= " WHERE rowid IN (" . $this->db->sanitize($idlist) . ")";
394 $sql .= " AND lettering_code IS NULL";
395 $sql .= " AND subledger_account != ''";
396
397 dol_syslog(__METHOD__ . " - Test amount integrity", LOG_DEBUG);
398 $resql = $this->db->query($sql);
399 if ($resql) {
400 if ($obj = $this->db->fetch_object($resql)) {
401 if (!(round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) {
402 $this->errors[] = $langs->trans('ErrorMatchingUnbalanced', price(price2num(abs($obj->deb), 'MT')), price(price2num(abs($obj->cred), 'MT')));
403 $error++;
404 }
405 }
406 $this->db->free($resql);
407 } else {
408 $this->errors[] = 'SQL Error message: ' . $this->db->lasterror();
409 $error++;
410 }
411 }
412
413 // Update lettering code
414 if (!$error) {
415 $idlist = implode(',', array_map('intval', $ids));
416 $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET";
417 $sql .= " lettering_code='" . $this->db->escape($letter) . "'";
418 $sql .= ", date_lettering = '" . $this->db->idate($now) . "'"; // todo correct date it's false
419 $sql .= ", matching_general = 0";
420 $sql .= " WHERE rowid IN (" . $this->db->sanitize($idlist) . ")";
421 $sql .= " AND lettering_code IS NULL";
422 $sql .= " AND subledger_account != ''";
423
424 dol_syslog(__METHOD__ . " - Update lettering code", LOG_DEBUG);
425 $resql = $this->db->query($sql);
426 if (!$resql) {
427 $error++;
428 $this->errors[] = "Error " . $this->db->lasterror();
429 } else {
430 $affected_rows = $this->db->affected_rows($resql);
431 }
432 }
433 }
434
435 // Commit or rollback
436 if ($error) {
437 $this->db->rollback();
438 foreach ($this->errors as $errmsg) {
439 dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
440 $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
441 }
442 return -1 * $error;
443 } else {
444 $this->db->commit();
445 return $affected_rows;
446 }
447 }
448
454 public function deleteLettering($ids, $notrigger = 0)
455 {
456 $error = 0;
457
458 $idlist = implode(',', array_map('intval', $ids));
459 $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
460 $sql .= " matching_general = 0";
461 $sql .= ", lettering_code = NULL";
462 $sql .= ", date_lettering = NULL";
463 $sql .= " WHERE rowid IN (" . $this->db->sanitize($idlist) . ")";
464 $sql .= " AND subledger_account != ''";
465
466 dol_syslog(get_class($this)."::update", LOG_DEBUG);
467 $resql = $this->db->query($sql);
468 if (!$resql) {
469 $error++;
470 $this->errors[] = "Error ".$this->db->lasterror();
471 }
472
473 // Commit or rollback
474 if ($error) {
475 foreach ($this->errors as $errmsg) {
476 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
477 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
478 }
479 return -1 * $error;
480 } else {
481 return $this->db->affected_rows($resql);
482 }
483 }
484
492 public function bookkeepingLetteringAll($bookkeeping_ids, $unlettering = false)
493 {
494 dol_syslog(__METHOD__ . " - ", LOG_DEBUG);
495
496 $error = 0;
497 $errors = array();
498 $nb_lettering = 0;
499
500 $result = $this->bookkeepingLettering($bookkeeping_ids, $unlettering);
501 if ($result < 0) {
502 $error++;
503 $errors = array_merge($errors, $this->errors);
504 $nb_lettering += abs($result) - 2;
505 } else {
506 $nb_lettering += $result;
507 }
508
509 if ($error) {
510 $this->errors = $errors;
511 return -2 - $nb_lettering;
512 } else {
513 return $nb_lettering;
514 }
515 }
516
524 public function updateGeneralMatching(array $ids = [], $partial = false)
525 {
526 global $conf, $langs;
527
528 $now = dol_now();
529 $error = 0;
530 $affected_rows = 0;
531
532 // Generate a string with n char 'A' (for manual/auto reconcile) or 'a' (for partial reconcile) where n is ACCOUNTING_LETTERING_NBLETTERS (So 'AA'/'aa', 'AAA'/'aaa', ...) @phan-suppress-next-line PhanParamSuspiciousOrder
533 $letter = str_pad("", getDolGlobalInt('ACCOUNTING_LETTERING_NBLETTERS', 3), $partial ? 'a' : 'A');
534
535 // Check for unreconcilable accounts
536 $pcgId = getDolGlobalInt('CHARTOFACCOUNTS');
537 $idlist = implode(',', array_map('intval', $ids));
538 $sql = "SELECT DISTINCT numero_compte";
539 $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping AS ab";
540 $sql .= " LEFT JOIN (";
541 $sql .= " SELECT aa.rowid, aa.account_number";
542 $sql .= " FROM " . $this->db->prefix() . "accounting_account AS aa";
543 $sql .= " INNER JOIN " . $this->db->prefix() . "accounting_system AS asys ON asys.pcg_version = aa.fk_pcg_version";
544 $sql .= " WHERE asys.rowid = ".(int) $pcgId." AND aa.reconcilable";
545 $sql .= " ) AS reconciliable_accounts ON reconciliable_accounts.account_number = ab.numero_compte";
546 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
547 $sql .= " AND reconciliable_accounts.rowid IS NULL";
548
549 $resql = $this->db->query($sql);
550 if ($resql) {
551 while ($obj = $this->db->fetch_object($resql)) {
552 $this->errors[] = $langs->trans(
553 'ErrorAccountNotReconcilable',
554 $obj->numero_compte,
555 dol_buildpath('accountancy/admin/account.php', 1) . '?search_account=' . $obj->numero_compte,
556 $langs->transnoentitiesnoconv('Chartofaccounts')
557 );
558 return -1;
559 }
560 $this->db->free($resql);
561 } else {
562 $this->errors[] = 'Error' . $this->db->lasterror();
563 return -1;
564 }
565
566 // Get fiscal year & verify all selected rows belong to the same fiscal year
567 $idlist = implode(',', array_map('intval', $ids));
568 $sql = "SELECT fy.rowid, fy.date_start, fy.date_end, COUNT(DISTINCT fy.rowid) AS nb_fiscalyears";
569 $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping AS ab";
570 $sql .= " INNER JOIN " . $this->db->prefix() . "accounting_fiscalyear AS fy";
571 $sql .= " ON ab.doc_date BETWEEN fy.date_start AND fy.date_end";
572 $sql .= " AND fy.entity = " . (int) $conf->entity;
573 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
574 $sql .= " GROUP BY fy.rowid, fy.date_start, fy.date_end";
575
576 dol_syslog(__METHOD__ . " - Get fiscal year", LOG_DEBUG);
577 $resql = $this->db->query($sql);
578 if (!$resql) {
579 $this->errors[] = 'Error ' . $this->db->lasterror();
580 return -1;
581 }
582
583 $fiscalYearRows = [];
584 while ($obj = $this->db->fetch_object($resql)) {
585 $fiscalYearRows[] = $obj;
586 }
587 $this->db->free($resql);
588
589 // No fiscal year found for any of the selected rows
590 if (empty($fiscalYearRows)) {
591 $this->errors[] = $langs->trans('ErrorFiscalYearNotFound');
592 return -1;
593 }
594
595 // Cross-fiscal-year matching is forbidden
596 if (count($fiscalYearRows) > 1) {
597 $periods = array_map(
602 function ($row) {
603 return dol_print_date($this->db->jdate($row->date_start), 'day') . ' – ' . dol_print_date($this->db->jdate($row->date_end), 'day');
604 },
605 $fiscalYearRows
606 );
607 $this->errors[] = $langs->transnoentitiesnoconv('ErrorMatchingCrossFiscalYear', implode(', ', $periods));
608 return -1;
609 }
610
611 $fiscalYear = $fiscalYearRows[0];
612 $fiscalYearStart = $this->db->jdate($fiscalYear->date_start);
613 $fiscalYearEnd = $this->db->jdate($fiscalYear->date_end);
614
615 $this->db->begin();
616
617 // Check partial / normal lettering case
618 $idlist = implode(',', array_map('intval', $ids));
619 $sql = "SELECT ab.lettering_code, GROUP_CONCAT(DISTINCT ab.rowid SEPARATOR ',') AS bookkeeping_ids";
620 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
621 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
622 $sql .= " GROUP BY ab.lettering_code";
623 $sql .= " ORDER BY ab.lettering_code DESC";
624
625 dol_syslog(__METHOD__ . " - Check partial / normal lettering case", LOG_DEBUG);
626 $resql = $this->db->query($sql);
627 if ($resql) {
628 while ($obj = $this->db->fetch_object($resql)) {
629 if (empty($obj->lettering_code)) {
630 continue;
631 }
632
633 // Remove normal lettering code if set partial lettering
634 if ($partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)) {
635 if (!empty($obj->bookkeeping_ids)) {
636 $ids = array_diff($ids, explode(',', $obj->bookkeeping_ids));
637 }
638 } elseif (!$partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) {
639 // Delete partial lettering code if set normal lettering
640 $sql2 = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET";
641 $sql2 .= " matching_general = 1";
642 $sql2 .= ", lettering_code = NULL";
643 $sql2 .= ", date_lettering = NULL";
644 $sql2 .= " WHERE entity IN (" . getEntity('accountancy') . ")";
645 $sql2 .= " AND lettering_code = '" . $this->db->escape($obj->lettering_code) . "'";
646
647 dol_syslog(__METHOD__ . " - Remove partial lettering", LOG_DEBUG);
648 $resql2 = $this->db->query($sql2);
649 if (!$resql2) {
650 $this->errors[] = 'Error' . $this->db->lasterror();
651 $error++;
652 break;
653 }
654 }
655 }
656 $this->db->free($resql);
657 } else {
658 $this->errors[] = 'Error' . $this->db->lasterror();
659 $error++;
660 }
661
662 if (!$error && !empty($ids)) {
663 // Get next code
664 $idlist = implode(',', array_map('intval', $ids));
665 $sql = "SELECT DISTINCT ab2.lettering_code";
666 $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping AS ab";
667 $sql .= " LEFT JOIN " . $this->db->prefix() . "accounting_bookkeeping AS ab2 ON ab2.numero_compte = ab.numero_compte";
668 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
669 $sql .= " AND ab2.lettering_code != ''";
670 $sql .= " AND ab2.matching_general = 1";
671 $sql .= " AND ab2.doc_date BETWEEN '" . $this->db->idate($fiscalYearStart) . "' AND '" . $this->db->idate($fiscalYearEnd) . "'";
672 $sql .= " ORDER BY ab2.lettering_code DESC";
673
674 dol_syslog(__METHOD__ . " - Get next code", LOG_DEBUG);
675 $resql = $this->db->query($sql);
676 if ($resql) {
677 while ($obj = $this->db->fetch_object($resql)) {
678 if (!empty($obj->lettering_code) &&
679 (($partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) ||
680 (!$partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)))
681 ) {
682 $letter = $obj->lettering_code;
683 $letter++;
684 break;
685 }
686 }
687 $this->db->free($resql);
688 } else {
689 $this->errors[] = 'Error' . $this->db->lasterror();
690 $error++;
691 }
692
693 // Test amount integrity
694 if (!$error && !$partial) {
695 $idlist = implode(',', array_map('intval', $ids));
696 $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred";
697 $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping";
698 $sql .= " WHERE rowid IN (" . $this->db->sanitize($idlist) . ")";
699 $sql .= " AND lettering_code IS NULL";
700
701 dol_syslog(__METHOD__ . " - Test amount integrity", LOG_DEBUG);
702 $resql = $this->db->query($sql);
703 if ($resql) {
704 if ($obj = $this->db->fetch_object($resql)) {
705 if (!(round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) {
706 $this->errors[] = $langs->trans('ErrorMatchingUnbalanced', price(price2num(abs($obj->deb), 'MT')), price(price2num(abs($obj->cred), 'MT')));
707 $error++;
708 }
709 }
710 $this->db->free($resql);
711 } else {
712 $this->errors[] = 'SQL Error message: ' . $this->db->lasterror();
713 $error++;
714 }
715 }
716
717 // Update matching code
718 if (!$error) {
719 $idlist = implode(',', array_map('intval', $ids));
720 $sql = "UPDATE " . $this->db->prefix() . "accounting_bookkeeping SET";
721 $sql .= " lettering_code='" . $this->db->escape($letter) . "'";
722 $sql .= ", date_lettering = '" . $this->db->idate($now) . "'";
723 $sql .= ", matching_general = 1";
724 $sql .= " WHERE rowid IN (" . $this->db->sanitize($idlist) . ")";
725 $sql .= " AND lettering_code IS NULL";
726
727 dol_syslog(__METHOD__ . " - Update general lettering code", LOG_DEBUG);
728 $resql = $this->db->query($sql);
729 if (!$resql) {
730 $error++;
731 $this->errors[] = "Error " . $this->db->lasterror();
732 } else {
733 $affected_rows = $this->db->affected_rows($resql);
734 }
735 }
736 }
737
738 // Commit or rollback
739 if ($error) {
740 $this->db->rollback();
741 foreach ($this->errors as $errmsg) {
742 dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
743 $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
744 }
745 return -1 * $error;
746 } else {
747 $this->db->commit();
748 return $affected_rows;
749 }
750 }
751
759 public function deleteGeneralMatching(array $ids = [])
760 {
761 global $conf;
762
763 $error = 0;
764
765 // Step 1: collect all (lettering_code, numero_compte, fiscal year) from selected ids
766 $idlist = implode(',', array_map('intval', $ids));
767 $sql = "SELECT DISTINCT ab.lettering_code, ab.numero_compte, fy.date_start, fy.date_end";
768 $sql .= " FROM " . $this->db->prefix() . "accounting_bookkeeping AS ab";
769 $sql .= " INNER JOIN " . $this->db->prefix() . "accounting_fiscalyear AS fy";
770 $sql .= " ON ab.doc_date BETWEEN fy.date_start AND fy.date_end";
771 $sql .= " AND fy.entity = " . (int) $conf->entity;
772 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize($idlist) . ")";
773 $sql .= " AND ab.matching_general = 1";
774 $sql .= " AND ab.lettering_code IS NOT NULL AND ab.lettering_code != ''";
775
776 dol_syslog(__METHOD__ . " - Collect lettering groups to delete", LOG_DEBUG);
777 $resql = $this->db->query($sql);
778 if (!$resql) {
779 $this->errors[] = 'Error ' . $this->db->lasterror();
780 return -1;
781 }
782
783 $groups = [];
784 while ($obj = $this->db->fetch_object($resql)) {
785 $groups[] = [
786 'code' => $obj->lettering_code,
787 'compte' => $obj->numero_compte,
788 'date_start' => $obj->date_start,
789 'date_end' => $obj->date_end,
790 ];
791 }
792 $this->db->free($resql);
793
794 if (empty($groups)) {
795 return 0; // Nothing to delete (lines not matched or already unmatched)
796 }
797
798 // Step 2: for each group, delete all lines sharing the same code+account+fiscal year
799 $affected = 0;
800 foreach ($groups as $group) {
801 $sql = "UPDATE " . $this->db->prefix() . "accounting_bookkeeping SET";
802 $sql .= " lettering_code = NULL";
803 $sql .= ", date_lettering = NULL";
804 $sql .= ", matching_general = 0";
805 $sql .= " WHERE numero_compte = '" . $this->db->escape($group['compte']) . "'";
806 $sql .= " AND lettering_code = '" . $this->db->escape($group['code']) . "'";
807 $sql .= " AND matching_general = 1";
808 $sql .= " AND doc_date BETWEEN '" . $this->db->escape($group['date_start']) . "' AND '" . $this->db->escape($group['date_end']) . "'";
809
810 dol_syslog(__METHOD__ . " - Delete gl matching group " . $group['code'] . "/" . $group['compte'], LOG_DEBUG);
811 $resql = $this->db->query($sql);
812 if (!$resql) {
813 $error++;
814 $this->errors[] = 'Error ' . $this->db->lasterror();
815 break;
816 }
817 $affected += $this->db->affected_rows($resql);
818 }
819
820 if ($error) {
821 foreach ($this->errors as $errmsg) {
822 dol_syslog(get_class($this) . "::deleteGeneralMatching " . $errmsg, LOG_ERR);
823 $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
824 }
825 return -1 * $error;
826 }
827
828 return $affected;
829 }
830
838 public function bookkeepingLettering($bookkeeping_ids, $unlettering = false)
839 {
840 global $langs;
841
842 $this->errors = array();
843
844 // Clean parameters
845 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
846
847 $error = 0;
848 $nb_lettering = 0;
849 $grouped_lines = $this->getLinkedLines($bookkeeping_ids);
850 if (!is_array($grouped_lines)) {
851 return -2;
852 }
853
854 foreach ($grouped_lines as $lines) {
855 $group_error = 0;
856 $total = 0;
857 $do_it = !$unlettering;
858 $lettering_code = null;
859 $piece_num_lines = array();
860 $bookkeeping_lines = array();
861 foreach ($lines as $line_infos) {
862 $bookkeeping_lines[$line_infos['id']] = $line_infos['id'];
863 $piece_num_lines[$line_infos['piece_num']] = $line_infos['piece_num'];
864 $total += ($line_infos['credit'] > 0 ? $line_infos['credit'] : -$line_infos['debit']);
865
866 // Check lettering code
867 if ($unlettering) {
868 if (isset($lettering_code) && $lettering_code != $line_infos['lettering_code']) {
869 $this->errors[] = $langs->trans('AccountancyErrorMismatchLetteringCode');
870 $group_error++;
871 break;
872 }
873 if (!isset($lettering_code)) {
874 $lettering_code = (string) $line_infos['lettering_code'];
875 }
876 if (!empty($line_infos['lettering_code'])) {
877 $do_it = true;
878 }
879 } elseif (!empty($line_infos['lettering_code'])) {
880 $do_it = false;
881 }
882 }
883
884 // Check balance amount
885 if (!$group_error && !$unlettering && price2num($total) != 0) {
886 $this->errors[] = $langs->trans('AccountancyErrorMismatchBalanceAmount', $total);
887 $group_error++;
888 }
889
890 // Matching/Unmatching the group of bookkeeping lines
891 if (!$group_error && $do_it) {
892 if ($unlettering) {
893 $result = $this->deleteLettering($bookkeeping_lines);
894 } else {
895 $result = $this->updateLettering($bookkeeping_lines);
896 }
897 if ($result < 0) {
898 $group_error++;
899 } elseif ($result > 0) {
900 $nb_lettering++;
901 }
902 }
903
904 if ($group_error) {
905 $this->errors[] = $langs->trans('AccountancyErrorLetteringBookkeeping', implode(', ', $piece_num_lines));
906 $error++;
907 }
908 }
909
910 if ($error) {
911 return -2 - $nb_lettering;
912 } else {
913 return $nb_lettering;
914 }
915 }
916
924 public function getLinkedLines($bookkeeping_ids, $only_has_subledger_account = true)
925 {
926 global $conf, $langs;
927 $this->errors = array();
928
929 // Clean parameters
930 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
931
932 // Get all bookkeeping lines
933 $sql = "SELECT DISTINCT ab.doc_type, ab.fk_doc";
934 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
935 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
936 $sql .= " AND ab.fk_doc > 0";
937 if (!empty($bookkeeping_ids)) {
938 // Get all bookkeeping lines of piece number
939 $sql .= " AND EXISTS (";
940 $sql .= " SELECT rowid";
941 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS pn";
942 $sql .= " WHERE pn.entity IN (" . getEntity('accountancy') . ")";
943 $sql .= " AND pn.rowid IN (" . $this->db->sanitize(implode(',', $bookkeeping_ids)) . ")";
944 $sql .= " AND pn.piece_num = ab.piece_num";
945 $sql .= " )";
946 }
947 if ($only_has_subledger_account) {
948 $sql .= " AND ab.subledger_account != ''";
949 }
950
951 dol_syslog(__METHOD__ . " - Get all bookkeeping lines", LOG_DEBUG);
952 $resql = $this->db->query($sql);
953 if (!$resql) {
954 $this->errors[] = "Error " . $this->db->lasterror();
955 return -1;
956 }
957
958 $bookkeeping_lines_by_type = array();
959 while ($obj = $this->db->fetch_object($resql)) {
960 $bookkeeping_lines_by_type[$obj->doc_type][$obj->fk_doc] = $obj->fk_doc;
961 }
962 $this->db->free($resql);
963
964 if (empty($bookkeeping_lines_by_type)) {
965 return array();
966 }
967
968 if (!empty($bookkeeping_lines_by_type['bank'])) {
969 $new_bookkeeping_lines_by_type = $this->getDocTypeAndFkDocFromBankLines($bookkeeping_lines_by_type['bank']);
970 if (!is_array($new_bookkeeping_lines_by_type)) {
971 return -1;
972 }
973 foreach ($new_bookkeeping_lines_by_type as $doc_type => $fk_docs) {
974 foreach ($fk_docs as $fk_doc) {
975 $bookkeeping_lines_by_type[$doc_type][$fk_doc] = $fk_doc;
976 }
977 }
978 }
979
980 $grouped_lines = array();
981 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
982 if (empty($bookkeeping_lines_by_type[$doc_type]) || !is_array($bookkeeping_lines_by_type[$doc_type])) {
983 continue;
984 }
985
986 // Get all document ids grouped
987 $doc_grouped = $this->getLinkedDocumentByGroup($bookkeeping_lines_by_type[$doc_type], $doc_type);
988 if (!is_array($doc_grouped)) {
989 return -1;
990 }
991
992 // Group all lines by document/piece number
993 foreach ($doc_grouped as $doc_ids) {
994 $bank_ids = $this->getBankLinesFromFkDocAndDocType($doc_ids, $doc_type);
995 if (!is_array($bank_ids)) {
996 return -1;
997 }
998
999 // Get all bookkeeping lines linked
1000 $sql = "SELECT DISTINCT ab.rowid, ab.piece_num, ab.debit, ab.credit, ab.lettering_code";
1001 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
1002 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
1003 $sql .= " AND (";
1004 if (!empty($bank_ids)) {
1005 $sql .= " EXISTS (";
1006 $sql .= " SELECT bpn.rowid";
1007 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS bpn";
1008 $sql .= " WHERE bpn.entity IN (" . getEntity('accountancy') . ")";
1009 $sql .= " AND bpn.doc_type = 'bank'";
1010 $sql .= " AND bpn.fk_doc IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
1011 $sql .= " AND bpn.piece_num = ab.piece_num";
1012 $sql .= " ) OR ";
1013 }
1014 $sql .= " EXISTS (";
1015 $sql .= " SELECT dpn.rowid";
1016 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS dpn";
1017 $sql .= " WHERE dpn.entity IN (" . getEntity('accountancy') . ")";
1018 $sql .= " AND dpn.doc_type = '" . $this->db->escape($doc_type) . "'";
1019 $sql .= " AND dpn.fk_doc IN (" . $this->db->sanitize(implode(',', $doc_ids)) . ")";
1020 $sql .= " AND dpn.piece_num = ab.piece_num";
1021 $sql .= " )";
1022 $sql .= ")";
1023 if ($only_has_subledger_account) {
1024 $sql .= " AND ab.subledger_account != ''";
1025 }
1026
1027 dol_syslog(__METHOD__ . " - Get all bookkeeping lines linked", LOG_DEBUG);
1028 $resql = $this->db->query($sql);
1029 if (!$resql) {
1030 $this->errors[] = "Error " . $this->db->lasterror();
1031 return -1;
1032 }
1033
1034 $group = array();
1035 while ($obj = $this->db->fetch_object($resql)) {
1036 $group[$obj->rowid] = array(
1037 'id' => $obj->rowid,
1038 'piece_num' => $obj->piece_num,
1039 'debit' => $obj->debit,
1040 'credit' => $obj->credit,
1041 'lettering_code' => $obj->lettering_code,
1042 );
1043 }
1044 $this->db->free($resql);
1045
1046 if (!empty($group)) {
1047 $grouped_lines[] = $group;
1048 }
1049 }
1050 }
1051
1052 return $grouped_lines;
1053 }
1054
1061 public function getDocTypeAndFkDocFromBankLines($bank_ids)
1062 {
1063 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($bank_ids), LOG_DEBUG);
1064
1065 // Clean parameters
1066 $bank_ids = is_array($bank_ids) ? $bank_ids : array();
1067
1068 if (empty($bank_ids)) {
1069 return array();
1070 }
1071
1072 $bookkeeping_lines_by_type = array();
1073 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
1074 // Get all fk_doc by doc_type from bank ids
1075 $sql = "SELECT DISTINCT dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " AS fk_doc";
1076 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
1077 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['doc_payment_table']) . " AS dp ON dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_payment']) . " = p.rowid";
1078 $sql .= " WHERE p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
1079 $sql .= " AND dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " > 0";
1080
1081 dol_syslog(__METHOD__ . " - Get all fk_doc by doc_type from list of bank ids for '" . $doc_type . "'", LOG_DEBUG);
1082 $resql = $this->db->query($sql);
1083 if (!$resql) {
1084 $this->errors[] = "Error " . $this->db->lasterror();
1085 return -1;
1086 }
1087
1088 while ($obj = $this->db->fetch_object($resql)) {
1089 $bookkeeping_lines_by_type[$doc_type][$obj->fk_doc] = $obj->fk_doc;
1090 }
1091 $this->db->free($resql);
1092 }
1093
1094 return $bookkeeping_lines_by_type;
1095 }
1096
1104 public function getBankLinesFromFkDocAndDocType($document_ids, $doc_type)
1105 {
1106 global $langs;
1107
1108 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($document_ids) . ", doc_type=$doc_type", LOG_DEBUG);
1109
1110 // Clean parameters
1111 $document_ids = is_array($document_ids) ? $document_ids : array();
1112 //remove empty entries
1113 $document_ids = array_filter($document_ids);
1114
1115 $doc_type = trim($doc_type);
1116
1117 if (empty($document_ids)) {
1118 return array();
1119 }
1120 if (!is_array(self::$doc_type_infos[$doc_type])) {
1121 $langs->load('errors');
1122 $this->errors[] = $langs->trans('ErrorBadParameters');
1123 return -1;
1124 }
1125
1126 $doc_type_info = self::$doc_type_infos[$doc_type];
1127 $bank_ids = array();
1128
1129 // Get all fk_doc by doc_type from bank ids
1130 $sql = "SELECT DISTINCT p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " AS fk_doc";
1131 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
1132 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['doc_payment_table']) . " AS dp ON dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_payment']) . " = p.rowid";
1133 // Implode used on array of int @phan-suppress-next-line PhanTypeMismatchArgumentInternal
1134 $sql .= " WHERE dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
1135 $sql .= " AND p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " > 0";
1136
1137 dol_syslog(__METHOD__ . " - Get all bank ids from list of document ids of a type '" . $doc_type . "'", LOG_DEBUG);
1138 $resql = $this->db->query($sql);
1139 if (!$resql) {
1140 $this->errors[] = "Error " . $this->db->lasterror();
1141 return -1;
1142 }
1143
1144 while ($obj = $this->db->fetch_object($resql)) {
1145 $bank_ids[$obj->fk_doc] = $obj->fk_doc;
1146 }
1147 $this->db->free($resql);
1148
1149 return $bank_ids;
1150 }
1151
1159 public function getLinkedDocumentByGroup($document_ids, $doc_type)
1160 {
1161 global $langs;
1162
1163 // Clean parameters
1164 $document_ids = is_array($document_ids) ? $document_ids : array();
1165 $doc_type = trim($doc_type);
1166 //remove empty entries
1167 $document_ids = array_filter($document_ids);
1168
1169 if (empty($document_ids)) {
1170 return array();
1171 }
1172
1173 if (!is_array(self::$doc_type_infos[$doc_type])) {
1174 $langs->load('errors');
1175 $this->errors[] = $langs->trans('ErrorBadParameters');
1176 return -1;
1177 }
1178
1179 $doc_type_info = self::$doc_type_infos[$doc_type];
1180
1181 // Get document lines
1182 $current_document_ids = array();
1183 $link_by_element = array();
1184 $element_by_link = array();
1185 foreach ($doc_type_info['linked_info'] as $linked_info) {
1186 if (empty($linked_info['fk_line_link'])) {
1187 $sql = "SELECT DISTINCT tl2.".$this->db->sanitize($linked_info['fk_link'])." AS fk_link, tl2.".$this->db->sanitize($linked_info['fk_doc'])." AS fk_doc";
1188 $sql .= " FROM ".MAIN_DB_PREFIX.$this->db->sanitize($linked_info['table'])." AS tl";
1189 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$this->db->sanitize($linked_info['table'])." AS tl2 ON tl2.".$this->db->sanitize($linked_info['fk_link'])." = tl.".$this->db->sanitize($linked_info['fk_link']);
1190 $sql .= " WHERE tl.".$this->db->sanitize($linked_info['fk_doc'])." IN (".$this->db->sanitize(implode(',', $document_ids)).")";
1191 } else {
1192 $sql = "SELECT DISTINCT tl2.fk_link, tl2.fk_doc";
1193 $sql .= " FROM (";
1194 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1195 $sql .= " SELECT DISTINCT " . $this->db->ifsql("tll.".$this->db->sanitize($linked_info['fk_table_link_line_parent'])." IS NOT NULL", "tll.".$this->db->sanitize($linked_info['fk_table_link_line_parent']), "tl.".$this->db->sanitize($linked_info['fk_link']))." AS fk_link, tl.".$this->db->sanitize($linked_info['fk_doc'])." AS fk_doc";
1196 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
1197 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1198 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->db->sanitize($linked_info['table_link_line']) . " AS tll ON tll.".$this->db->sanitize($linked_info['fk_table_link_line']) . " = tl.".$this->db->sanitize($linked_info['fk_line_link']);
1199 $sql .= ") AS tl";
1200 $sql .= " LEFT JOIN (";
1201 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1202 $sql .= " SELECT DISTINCT " . $this->db->ifsql("tll.".$this->db->sanitize($linked_info['fk_table_link_line_parent'])." IS NOT NULL", "tll.".$this->db->sanitize($linked_info['fk_table_link_line_parent']), "tl.".$this->db->sanitize($linked_info['fk_link']))." AS fk_link, tl.".$this->db->sanitize($linked_info['fk_doc'])." AS fk_doc";
1203 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
1204 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
1205 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->db->sanitize($linked_info['table_link_line']) . " AS tll ON tll.".$this->db->sanitize($linked_info['fk_table_link_line']) . " = tl.".$this->db->sanitize($linked_info['fk_line_link']);
1206 $sql .= ") AS tl2 ON tl2.fk_link = tl.fk_link";
1207 $sql .= " WHERE tl.fk_doc IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
1208 $sql .= " AND tl2.fk_doc IS NOT NULL";
1209 }
1210
1211 dol_syslog(__METHOD__ . " - Get document lines", LOG_DEBUG);
1212 $resql = $this->db->query($sql);
1213 if (!$resql) {
1214 $this->errors[] = "Error " . $this->db->lasterror();
1215 return -1;
1216 }
1217
1218 $is_fk_link_is_also_fk_doc = !empty($linked_info['is_fk_link_is_also_fk_doc']);
1219 while ($obj = $this->db->fetch_object($resql)) {
1220 $current_document_ids[$obj->fk_doc] = $obj->fk_doc;
1221
1222 $link_key = (string) $linked_info['prefix'] . (string) $obj->fk_link;
1223 $element_by_link[$link_key][$obj->fk_doc] = $obj->fk_doc;
1224 $link_by_element[(int) $obj->fk_doc][$link_key] = $link_key;
1225 if ($is_fk_link_is_also_fk_doc) {
1226 $element_by_link[$link_key][$obj->fk_link] = $obj->fk_link;
1227 $link_by_element[(int) $obj->fk_link][$link_key] = $link_key;
1228 }
1229 }
1230 $this->db->free($resql);
1231 }
1232
1233 if (count(array_diff($document_ids, $current_document_ids))) {
1234 return $this->getLinkedDocumentByGroup($current_document_ids, $doc_type);
1235 }
1236
1237 return $this->getGroupElements($link_by_element, $element_by_link);
1238 }
1239
1249 public function getGroupElements(&$link_by_element, &$element_by_link, $link_key = '', &$current_group = array())
1250 {
1251 $grouped_elements = array();
1252 if (!empty($link_key) && !isset($element_by_link[$link_key])) {
1253 // Return if specific link key not found
1254 return $grouped_elements;
1255 }
1256
1257
1258 if (empty($link_key)) {
1259 // Save list when is the first step of the recursive recursive function
1260 $save_link_by_element = $link_by_element;
1261 $save_element_by_link = $element_by_link;
1262 } else {
1263 // To satisfy static analysis (phpstan)
1264 $save_link_by_element = null;
1265 $save_element_by_link = null;
1266 }
1267
1268 do {
1269 // Get current element id, get this payment id list and delete the entry
1270 $current_link_key = !empty($link_key) ? $link_key : array_keys($element_by_link)[0];
1271 $element_ids = $element_by_link[$current_link_key];
1272 unset($element_by_link[$current_link_key]);
1273
1274 foreach ($element_ids as $element_id) {
1275 // Continue if element id in not found
1276 if (!isset($link_by_element[$element_id])) {
1277 continue;
1278 }
1279
1280 // Set the element in the current group
1281 $current_group[$element_id] = $element_id;
1282
1283 // Get current link keys, get this element id list and delete the entry
1284 $link_keys = $link_by_element[$element_id];
1285 unset($link_by_element[$element_id]);
1286
1287 // Set element id on the current group for each link key of the element
1288 foreach ($link_keys as $key) {
1289 $this->getGroupElements($link_by_element, $element_by_link, (string) $key, $current_group);
1290 }
1291 }
1292
1293 if (empty($link_key)) {
1294 // Save current group and reset the current group when is the begin of recursive function
1295 $grouped_elements[] = $current_group;
1296 $current_group = array();
1297 }
1298 } while (!empty($element_by_link) && empty($link_key));
1299
1300 if (empty($link_key)) {
1301 // Restore list when is the begin of recursive function
1302 $link_by_element = $save_link_by_element; // @phan-suppress-current-line PhanPossiblyUndeclaredVariable
1303 $element_by_link = $save_element_by_link; // @phan-suppress-current-line PhanPossiblyUndeclaredVariable
1304 }
1305
1306 return $grouped_elements;
1307 }
1308}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage Ledger (General Ledger and Subledger)
Class Lettering.
getDocTypeAndFkDocFromBankLines($bank_ids)
Get all fk_doc by doc_type from list of bank ids.
letteringThirdparty($socid)
letteringThirdparty
bookkeepingLetteringAll($bookkeeping_ids, $unlettering=false)
Lettering bookkeeping lines all types.
getGroupElements(&$link_by_element, &$element_by_link, $link_key='', &$current_group=array())
Get element ids grouped by link or element in common.
deleteGeneralMatching(array $ids=[])
Delete matching code on general account Deletes all lines sharing the same lettering_code+numero_comp...
bookkeepingLettering($bookkeeping_ids, $unlettering=false)
Lettering bookkeeping lines.
deleteLettering($ids, $notrigger=0)
getLinkedDocumentByGroup($document_ids, $doc_type)
Get all linked document ids by group and type.
updateGeneralMatching(array $ids=[], $partial=false)
Update the matching on general account.
getBankLinesFromFkDocAndDocType($document_ids, $doc_type)
Get all bank ids from list of document ids of a type.
getLinkedLines($bookkeeping_ids, $only_has_subledger_account=true)
Lettering bookkeeping lines.
updateLettering($ids=array(), $notrigger=0, $partial=false)
Class to manage third parties objects (customers, suppliers, prospects...)
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php