dolibarr 22.0.5
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-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
5 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2025 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 = ".$conf->entity;
162 $sql .= " AND code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$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=".$conf->entity.") ";
191 $sql .= " AND facf.entity = ".$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=".$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=".$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 $now = dol_now();
303 $error = 0;
304 $affected_rows = 0;
305
306 // 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
307 $letter = str_pad("", getDolGlobalInt('ACCOUNTING_LETTERING_NBLETTERS', 3), $partial ? 'a' : 'A');
308
309 $this->db->begin();
310
311 // Check partial / normal lettering case
312 $sql = "SELECT ab.lettering_code, GROUP_CONCAT(DISTINCT ab.rowid SEPARATOR ',') AS bookkeeping_ids";
313 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
314 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ")";
315 $sql .= " GROUP BY ab.lettering_code";
316 $sql .= " ORDER BY ab.lettering_code DESC";
317
318 dol_syslog(__METHOD__ . " - Check partial / normal lettering case", LOG_DEBUG);
319 $resql = $this->db->query($sql);
320 if ($resql) {
321 while ($obj = $this->db->fetch_object($resql)) {
322 if (empty($obj->lettering_code)) {
323 continue;
324 }
325
326 // Remove normal lettering code if set partial lettering
327 if ($partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)) {
328 if (!empty($obj->bookkeeping_ids)) {
329 $ids = array_diff($ids, explode(',', $obj->bookkeeping_ids));
330 }
331 } elseif (!$partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) {
332 // Delete partial lettering code if set normal lettering
333 $sql2 = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET";
334 $sql2 .= " lettering_code = NULL";
335 $sql2 .= ", date_lettering = NULL";
336 $sql2 .= " WHERE entity IN (" . getEntity('accountancy') . ")";
337 $sql2 .= " AND lettering_code = '" . $this->db->escape($obj->lettering_code) . "'";
338
339 dol_syslog(__METHOD__ . " - Remove partial lettering", LOG_DEBUG);
340 $resql2 = $this->db->query($sql2);
341 if (!$resql2) {
342 $this->errors[] = 'Error' . $this->db->lasterror();
343 $error++;
344 break;
345 }
346 }
347 }
348 $this->db->free($resql);
349 } else {
350 $this->errors[] = 'Error' . $this->db->lasterror();
351 $error++;
352 }
353
354 if (!$error && !empty($ids)) {
355 // Get next code
356 $sql = "SELECT DISTINCT ab2.lettering_code";
357 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
358 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab2 ON ab2.subledger_account = ab.subledger_account";
359 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ")";
360 $sql .= " AND ab2.lettering_code != ''";
361 $sql .= " ORDER BY ab2.lettering_code DESC";
362
363 dol_syslog(__METHOD__ . " - Get next code", LOG_DEBUG);
364 $resql = $this->db->query($sql);
365 if ($resql) {
366 while ($obj = $this->db->fetch_object($resql)) {
367 if (!empty($obj->lettering_code) &&
368 (($partial && preg_match('/^[a-z]+$/', $obj->lettering_code)) ||
369 (!$partial && preg_match('/^[A-Z]+$/', $obj->lettering_code)))
370 ) {
371 $letter = $obj->lettering_code;
372 $letter++;
373 break;
374 }
375 }
376 $this->db->free($resql);
377 } else {
378 $this->errors[] = 'Error' . $this->db->lasterror();
379 $error++;
380 }
381
382 // Test amount integrity
383 if (!$error && !$partial) {
384 $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE ";
385 $sql .= " rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ") AND lettering_code IS NULL AND subledger_account != ''";
386
387 dol_syslog(__METHOD__ . " - Test amount integrity", LOG_DEBUG);
388 $resql = $this->db->query($sql);
389 if ($resql) {
390 if ($obj = $this->db->fetch_object($resql)) {
391 if (!(round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) {
392 $this->errors[] = 'Total not exacts ' . round(abs($obj->deb), 2) . ' vs ' . round(abs($obj->cred), 2);
393 $error++;
394 }
395 }
396 $this->db->free($resql);
397 } else {
398 $this->errors[] = 'Erreur sql' . $this->db->lasterror();
399 $error++;
400 }
401 }
402
403 // Update lettering code
404 if (!$error) {
405 $sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping SET";
406 $sql .= " lettering_code='" . $this->db->escape($letter) . "'";
407 $sql .= ", date_lettering = '" . $this->db->idate($now) . "'"; // todo correct date it's false
408 $sql .= " WHERE rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ") AND lettering_code IS NULL AND subledger_account != ''";
409
410 dol_syslog(__METHOD__ . " - Update lettering code", LOG_DEBUG);
411 $resql = $this->db->query($sql);
412 if (!$resql) {
413 $error++;
414 $this->errors[] = "Error " . $this->db->lasterror();
415 } else {
416 $affected_rows = $this->db->affected_rows($resql);
417 }
418 }
419 }
420
421 // Commit or rollback
422 if ($error) {
423 $this->db->rollback();
424 foreach ($this->errors as $errmsg) {
425 dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
426 $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
427 }
428 return -1 * $error;
429 } else {
430 $this->db->commit();
431 return $affected_rows;
432 }
433 }
434
440 public function deleteLettering($ids, $notrigger = 0)
441 {
442 $error = 0;
443
444 $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
445 $sql .= " lettering_code = NULL";
446 $sql .= ", date_lettering = NULL";
447 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $ids)).")";
448 $sql .= " AND subledger_account != ''";
449
450 dol_syslog(get_class($this)."::update", LOG_DEBUG);
451 $resql = $this->db->query($sql);
452 if (!$resql) {
453 $error++;
454 $this->errors[] = "Error ".$this->db->lasterror();
455 }
456
457 // Commit or rollback
458 if ($error) {
459 foreach ($this->errors as $errmsg) {
460 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
461 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
462 }
463 return -1 * $error;
464 } else {
465 return $this->db->affected_rows($resql);
466 }
467 }
468
476 public function bookkeepingLetteringAll($bookkeeping_ids, $unlettering = false)
477 {
478 dol_syslog(__METHOD__ . " - ", LOG_DEBUG);
479
480 $error = 0;
481 $errors = array();
482 $nb_lettering = 0;
483
484 $result = $this->bookkeepingLettering($bookkeeping_ids, $unlettering);
485 if ($result < 0) {
486 $error++;
487 $errors = array_merge($errors, $this->errors);
488 $nb_lettering += abs($result) - 2;
489 } else {
490 $nb_lettering += $result;
491 }
492
493 if ($error) {
494 $this->errors = $errors;
495 return -2 - $nb_lettering;
496 } else {
497 return $nb_lettering;
498 }
499 }
500
508 public function bookkeepingLettering($bookkeeping_ids, $unlettering = false)
509 {
510 global $langs;
511
512 $this->errors = array();
513
514 // Clean parameters
515 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
516
517 $error = 0;
518 $nb_lettering = 0;
519 $grouped_lines = $this->getLinkedLines($bookkeeping_ids);
520 if (!is_array($grouped_lines)) {
521 return -2;
522 }
523
524 foreach ($grouped_lines as $lines) {
525 $group_error = 0;
526 $total = 0;
527 $do_it = !$unlettering;
528 $lettering_code = null;
529 $piece_num_lines = array();
530 $bookkeeping_lines = array();
531 foreach ($lines as $line_infos) {
532 $bookkeeping_lines[$line_infos['id']] = $line_infos['id'];
533 $piece_num_lines[$line_infos['piece_num']] = $line_infos['piece_num'];
534 $total += ($line_infos['credit'] > 0 ? $line_infos['credit'] : -$line_infos['debit']);
535
536 // Check lettering code
537 if ($unlettering) {
538 if (isset($lettering_code) && $lettering_code != $line_infos['lettering_code']) {
539 $this->errors[] = $langs->trans('AccountancyErrorMismatchLetteringCode');
540 $group_error++;
541 break;
542 }
543 if (!isset($lettering_code)) {
544 $lettering_code = (string) $line_infos['lettering_code'];
545 }
546 if (!empty($line_infos['lettering_code'])) {
547 $do_it = true;
548 }
549 } elseif (!empty($line_infos['lettering_code'])) {
550 $do_it = false;
551 }
552 }
553
554 // Check balance amount
555 if (!$group_error && !$unlettering && price2num($total) != 0) {
556 $this->errors[] = $langs->trans('AccountancyErrorMismatchBalanceAmount', $total);
557 $group_error++;
558 }
559
560 // Lettering/Unlettering the group of bookkeeping lines
561 if (!$group_error && $do_it) {
562 if ($unlettering) {
563 $result = $this->deleteLettering($bookkeeping_lines);
564 } else {
565 $result = $this->updateLettering($bookkeeping_lines);
566 }
567 if ($result < 0) {
568 $group_error++;
569 } elseif ($result > 0) {
570 $nb_lettering++;
571 }
572 }
573
574 if ($group_error) {
575 $this->errors[] = $langs->trans('AccountancyErrorLetteringBookkeeping', implode(', ', $piece_num_lines));
576 $error++;
577 }
578 }
579
580 if ($error) {
581 return -2 - $nb_lettering;
582 } else {
583 return $nb_lettering;
584 }
585 }
586
594 public function getLinkedLines($bookkeeping_ids, $only_has_subledger_account = true)
595 {
596 global $conf, $langs;
597 $this->errors = array();
598
599 // Clean parameters
600 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
601
602 // Get all bookkeeping lines
603 $sql = "SELECT DISTINCT ab.doc_type, ab.fk_doc";
604 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
605 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
606 $sql .= " AND ab.fk_doc > 0";
607 if (!empty($bookkeeping_ids)) {
608 // Get all bookkeeping lines of piece number
609 $sql .= " AND EXISTS (";
610 $sql .= " SELECT rowid";
611 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS pn";
612 $sql .= " WHERE pn.entity IN (" . getEntity('accountancy') . ")";
613 $sql .= " AND pn.rowid IN (" . $this->db->sanitize(implode(',', $bookkeeping_ids)) . ")";
614 $sql .= " AND pn.piece_num = ab.piece_num";
615 $sql .= " )";
616 }
617 if ($only_has_subledger_account) {
618 $sql .= " AND ab.subledger_account != ''";
619 }
620
621 dol_syslog(__METHOD__ . " - Get all bookkeeping lines", LOG_DEBUG);
622 $resql = $this->db->query($sql);
623 if (!$resql) {
624 $this->errors[] = "Error " . $this->db->lasterror();
625 return -1;
626 }
627
628 $bookkeeping_lines_by_type = array();
629 while ($obj = $this->db->fetch_object($resql)) {
630 $bookkeeping_lines_by_type[$obj->doc_type][$obj->fk_doc] = $obj->fk_doc;
631 }
632 $this->db->free($resql);
633
634 if (empty($bookkeeping_lines_by_type)) {
635 return array();
636 }
637
638 if (!empty($bookkeeping_lines_by_type['bank'])) {
639 $new_bookkeeping_lines_by_type = $this->getDocTypeAndFkDocFromBankLines($bookkeeping_lines_by_type['bank']);
640 if (!is_array($new_bookkeeping_lines_by_type)) {
641 return -1;
642 }
643 foreach ($new_bookkeeping_lines_by_type as $doc_type => $fk_docs) {
644 foreach ($fk_docs as $fk_doc) {
645 $bookkeeping_lines_by_type[$doc_type][$fk_doc] = $fk_doc;
646 }
647 }
648 }
649
650 $grouped_lines = array();
651 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
652 if (empty($bookkeeping_lines_by_type[$doc_type]) || !is_array($bookkeeping_lines_by_type[$doc_type])) {
653 continue;
654 }
655
656 // Get all document ids grouped
657 $doc_grouped = $this->getLinkedDocumentByGroup($bookkeeping_lines_by_type[$doc_type], $doc_type);
658 if (!is_array($doc_grouped)) {
659 return -1;
660 }
661
662 // Group all lines by document/piece number
663 foreach ($doc_grouped as $doc_ids) {
664 $bank_ids = $this->getBankLinesFromFkDocAndDocType($doc_ids, $doc_type);
665 if (!is_array($bank_ids)) {
666 return -1;
667 }
668
669 // Get all bookkeeping lines linked
670 $sql = "SELECT DISTINCT ab.rowid, ab.piece_num, ab.debit, ab.credit, ab.lettering_code";
671 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
672 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
673 $sql .= " AND (";
674 if (!empty($bank_ids)) {
675 $sql .= " EXISTS (";
676 $sql .= " SELECT bpn.rowid";
677 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS bpn";
678 $sql .= " WHERE bpn.entity IN (" . getEntity('accountancy') . ")";
679 $sql .= " AND bpn.doc_type = 'bank'";
680 $sql .= " AND bpn.fk_doc IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
681 $sql .= " AND bpn.piece_num = ab.piece_num";
682 $sql .= " ) OR ";
683 }
684 $sql .= " EXISTS (";
685 $sql .= " SELECT dpn.rowid";
686 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS dpn";
687 $sql .= " WHERE dpn.entity IN (" . getEntity('accountancy') . ")";
688 $sql .= " AND dpn.doc_type = '" . $this->db->escape($doc_type) . "'";
689 $sql .= " AND dpn.fk_doc IN (" . $this->db->sanitize(implode(',', $doc_ids)) . ")";
690 $sql .= " AND dpn.piece_num = ab.piece_num";
691 $sql .= " )";
692 $sql .= ")";
693 if ($only_has_subledger_account) {
694 $sql .= " AND ab.subledger_account != ''";
695 }
696
697 dol_syslog(__METHOD__ . " - Get all bookkeeping lines linked", LOG_DEBUG);
698 $resql = $this->db->query($sql);
699 if (!$resql) {
700 $this->errors[] = "Error " . $this->db->lasterror();
701 return -1;
702 }
703
704 $group = array();
705 while ($obj = $this->db->fetch_object($resql)) {
706 $group[$obj->rowid] = array(
707 'id' => $obj->rowid,
708 'piece_num' => $obj->piece_num,
709 'debit' => $obj->debit,
710 'credit' => $obj->credit,
711 'lettering_code' => $obj->lettering_code,
712 );
713 }
714 $this->db->free($resql);
715
716 if (!empty($group)) {
717 $grouped_lines[] = $group;
718 }
719 }
720 }
721
722 return $grouped_lines;
723 }
724
731 public function getDocTypeAndFkDocFromBankLines($bank_ids)
732 {
733 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($bank_ids), LOG_DEBUG);
734
735 // Clean parameters
736 $bank_ids = is_array($bank_ids) ? $bank_ids : array();
737
738 if (empty($bank_ids)) {
739 return array();
740 }
741
742 $bookkeeping_lines_by_type = array();
743 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
744 // Get all fk_doc by doc_type from bank ids
745 $sql = "SELECT DISTINCT dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " AS fk_doc";
746 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
747 $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";
748 $sql .= " WHERE p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
749 $sql .= " AND dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " > 0";
750
751 dol_syslog(__METHOD__ . " - Get all fk_doc by doc_type from list of bank ids for '" . $doc_type . "'", LOG_DEBUG);
752 $resql = $this->db->query($sql);
753 if (!$resql) {
754 $this->errors[] = "Error " . $this->db->lasterror();
755 return -1;
756 }
757
758 while ($obj = $this->db->fetch_object($resql)) {
759 $bookkeeping_lines_by_type[$doc_type][$obj->fk_doc] = $obj->fk_doc;
760 }
761 $this->db->free($resql);
762 }
763
764 return $bookkeeping_lines_by_type;
765 }
766
774 public function getBankLinesFromFkDocAndDocType($document_ids, $doc_type)
775 {
776 global $langs;
777
778 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($document_ids) . ", doc_type=$doc_type", LOG_DEBUG);
779
780 // Clean parameters
781 $document_ids = is_array($document_ids) ? $document_ids : array();
782 //remove empty entries
783 $document_ids = array_filter($document_ids);
784
785 $doc_type = trim($doc_type);
786
787 if (empty($document_ids)) {
788 return array();
789 }
790 if (!is_array(self::$doc_type_infos[$doc_type])) {
791 $langs->load('errors');
792 $this->errors[] = $langs->trans('ErrorBadParameters');
793 return -1;
794 }
795
796 $doc_type_info = self::$doc_type_infos[$doc_type];
797 $bank_ids = array();
798
799 // Get all fk_doc by doc_type from bank ids
800 $sql = "SELECT DISTINCT p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " AS fk_doc";
801 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
802 $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";
803 // Implode used on array of int @phan-suppress-next-line PhanTypeMismatchArgumentInternal
804 $sql .= " WHERE dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
805 $sql .= " AND p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " > 0";
806
807 dol_syslog(__METHOD__ . " - Get all bank ids from list of document ids of a type '" . $doc_type . "'", LOG_DEBUG);
808 $resql = $this->db->query($sql);
809 if (!$resql) {
810 $this->errors[] = "Error " . $this->db->lasterror();
811 return -1;
812 }
813
814 while ($obj = $this->db->fetch_object($resql)) {
815 $bank_ids[$obj->fk_doc] = $obj->fk_doc;
816 }
817 $this->db->free($resql);
818
819 return $bank_ids;
820 }
821
829 public function getLinkedDocumentByGroup($document_ids, $doc_type)
830 {
831 global $langs;
832
833 // Clean parameters
834 $document_ids = is_array($document_ids) ? $document_ids : array();
835 $doc_type = trim($doc_type);
836 //remove empty entries
837 $document_ids = array_filter($document_ids);
838
839 if (empty($document_ids)) {
840 return array();
841 }
842
843 if (!is_array(self::$doc_type_infos[$doc_type])) {
844 $langs->load('errors');
845 $this->errors[] = $langs->trans('ErrorBadParameters');
846 return -1;
847 }
848
849 $doc_type_info = self::$doc_type_infos[$doc_type];
850
851 // Get document lines
852 $current_document_ids = array();
853 $link_by_element = array();
854 $element_by_link = array();
855 foreach ($doc_type_info['linked_info'] as $linked_info) {
856 if (empty($linked_info['fk_line_link'])) {
857 $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";
858 $sql .= " FROM ".MAIN_DB_PREFIX.$this->db->sanitize($linked_info['table'])." AS tl";
859 $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']);
860 $sql .= " WHERE tl.".$this->db->sanitize($linked_info['fk_doc'])." IN (".$this->db->sanitize(implode(',', $document_ids)).")";
861 } else {
862 $sql = "SELECT DISTINCT tl2.fk_link, tl2.fk_doc";
863 $sql .= " FROM (";
864 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
865 $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";
866 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
867 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
868 $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']);
869 $sql .= ") AS tl";
870 $sql .= " LEFT JOIN (";
871 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
872 $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";
873 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
874 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
875 $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']);
876 $sql .= ") AS tl2 ON tl2.fk_link = tl.fk_link";
877 $sql .= " WHERE tl.fk_doc IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
878 $sql .= " AND tl2.fk_doc IS NOT NULL";
879 }
880
881 dol_syslog(__METHOD__ . " - Get document lines", LOG_DEBUG);
882 $resql = $this->db->query($sql);
883 if (!$resql) {
884 $this->errors[] = "Error " . $this->db->lasterror();
885 return -1;
886 }
887
888 $is_fk_link_is_also_fk_doc = !empty($linked_info['is_fk_link_is_also_fk_doc']);
889 while ($obj = $this->db->fetch_object($resql)) {
890 $current_document_ids[$obj->fk_doc] = $obj->fk_doc;
891
892 $link_key = $linked_info['prefix'] . $obj->fk_link;
893 $element_by_link[$link_key][$obj->fk_doc] = $obj->fk_doc;
894 $link_by_element[$obj->fk_doc][$link_key] = $link_key;
895 if ($is_fk_link_is_also_fk_doc) {
896 $element_by_link[$link_key][$obj->fk_link] = $obj->fk_link;
897 $link_by_element[$obj->fk_link][$link_key] = $link_key;
898 }
899 }
900 $this->db->free($resql);
901 }
902
903 if (count(array_diff($document_ids, $current_document_ids))) {
904 return $this->getLinkedDocumentByGroup($current_document_ids, $doc_type);
905 }
906
907 return $this->getGroupElements($link_by_element, $element_by_link);
908 }
909
919 public function getGroupElements(&$link_by_element, &$element_by_link, $link_key = '', &$current_group = array())
920 {
921 $grouped_elements = array();
922 if (!empty($link_key) && !isset($element_by_link[$link_key])) {
923 // Return if specific link key not found
924 return $grouped_elements;
925 }
926
927
928 if (empty($link_key)) {
929 // Save list when is the first step of the recursive recursive function
930 $save_link_by_element = $link_by_element;
931 $save_element_by_link = $element_by_link;
932 }
933
934 do {
935 // Get current element id, get this payment id list and delete the entry
936 $current_link_key = !empty($link_key) ? $link_key : array_keys($element_by_link)[0];
937 $element_ids = $element_by_link[$current_link_key];
938 unset($element_by_link[$current_link_key]);
939
940 foreach ($element_ids as $element_id) {
941 // Continue if element id in not found
942 if (!isset($link_by_element[$element_id])) {
943 continue;
944 }
945
946 // Set the element in the current group
947 $current_group[$element_id] = $element_id;
948
949 // Get current link keys, get this element id list and delete the entry
950 $link_keys = $link_by_element[$element_id];
951 unset($link_by_element[$element_id]);
952
953 // Set element id on the current group for each link key of the element
954 foreach ($link_keys as $key) {
955 $this->getGroupElements($link_by_element, $element_by_link, (string) $key, $current_group);
956 }
957 }
958
959 if (empty($link_key)) {
960 // Save current group and reset the current group when is the begin of recursive function
961 $grouped_elements[] = $current_group;
962 $current_group = array();
963 }
964 } while (!empty($element_by_link) && empty($link_key));
965
966 if (empty($link_key)) {
967 // Restore list when is the begin of recursive function
968 $link_by_element = $save_link_by_element; // @phan-suppress-current-line PhanPossiblyUndeclaredVariable
969 $element_by_link = $save_element_by_link; // @phan-suppress-current-line PhanPossiblyUndeclaredVariable
970 }
971
972 return $grouped_elements;
973 }
974}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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.
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.
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...)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79