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