dolibarr 20.0.0
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-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
5 * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27include_once DOL_DOCUMENT_ROOT."/accountancy/class/bookkeeping.class.php";
28include_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
29include_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
30
35{
36 public static $doc_type_infos = array(
37 'customer_invoice' => array(
38 'payment_table' => 'paiement',
39 'payment_table_fk_bank' => 'fk_bank',
40 'doc_payment_table' => 'paiement_facture',
41 'doc_payment_table_fk_payment' => 'fk_paiement',
42 'doc_payment_table_fk_doc' => 'fk_facture',
43 'linked_info' => array(
44 array(
45 'table' => 'paiement_facture',
46 'fk_doc' => 'fk_facture',
47 'fk_link' => 'fk_paiement',
48 'prefix' => 'p',
49 ),
50 array(
51 'table' => 'societe_remise_except',
52 'fk_doc' => 'fk_facture_source',
53 'fk_link' => 'fk_facture',
54 'fk_line_link' => 'fk_facture_line',
55 'table_link_line' => 'facturedet',
56 'fk_table_link_line' => 'rowid',
57 'fk_table_link_line_parent' => 'fk_facture',
58 'prefix' => 'a',
59 'is_fk_link_is_also_fk_doc' => true,
60 ),
61 ),
62 ),
63 'supplier_invoice' => array(
64 'payment_table' => 'paiementfourn',
65 'payment_table_fk_bank' => 'fk_bank',
66 'doc_payment_table' => 'paiementfourn_facturefourn',
67 'doc_payment_table_fk_payment' => 'fk_paiementfourn',
68 'doc_payment_table_fk_doc' => 'fk_facturefourn',
69 'linked_info' => array(
70 array(
71 'table' => 'paiementfourn_facturefourn',
72 'fk_doc' => 'fk_facturefourn',
73 'fk_link' => 'fk_paiementfourn',
74 'prefix' => 'p',
75 ),
76 array(
77 'table' => 'societe_remise_except',
78 'fk_doc' => 'fk_invoice_supplier_source',
79 'fk_link' => 'fk_invoice_supplier',
80 'fk_line_link' => 'fk_invoice_supplier_line',
81 'table_link_line' => 'facture_fourn_det',
82 'fk_table_link_line' => 'rowid',
83 'fk_table_link_line_parent' => 'fk_facture_fourn',
84 'prefix' => 'a',
85 'is_fk_link_is_also_fk_doc' => true,
86 ),
87 ),
88 ),
89 );
90
97 public function letteringThirdparty($socid)
98 {
99 global $conf;
100
101 $error = 0;
102
103 $object = new Societe($this->db);
104 $object->id = $socid;
105 $object->fetch($socid);
106
107
108 if ($object->code_compta_client == '411CUSTCODE') {
109 $object->code_compta_client = '';
110 }
111
112 if ($object->code_compta_fournisseur == '401SUPPCODE') {
113 $object->code_compta_fournisseur = '';
114 }
115
119 $sql = "SELECT DISTINCT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.subledger_account, ";
120 $sql .= " bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant ";
121 $sql .= " , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type ";
122 $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk";
123 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) ";
124 $sql .= " WHERE ( ";
125 if ($object->code_compta_client != "") {
126 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
127 }
128 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
129 $sql .= " OR ";
130 }
131 if ($object->code_compta_fournisseur != "") {
132 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
133 }
134
135 $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) ";
136 $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) ";
137 $sql .= ' AND bk.date_validated IS NULL ';
138 $sql .= $this->db->order('bk.doc_date', 'DESC');
139
140 // echo $sql;
141 //
142 $resql = $this->db->query($sql);
143 if ($resql) {
144 $num = $this->db->num_rows($resql);
145
146 while ($obj = $this->db->fetch_object($resql)) {
147 $ids = array();
148 $ids_fact = array();
149
150 if ($obj->type == 'payment_supplier') {
151 $sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id';
152 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
153 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid";
154 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid";
155 $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)."')";
156 $sql .= " WHERE payfacf.fk_paiementfourn = '".$this->db->escape($obj->url_id)."' ";
157 $sql .= " AND facf.entity = ".$conf->entity;
158 $sql .= " AND code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") ";
159 $sql .= " AND ( ";
160 if ($object->code_compta_client != "") {
161 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
162 }
163 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
164 $sql .= " OR ";
165 }
166 if ($object->code_compta_fournisseur != "") {
167 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
168 }
169 $sql .= " ) ";
170
171 $resql2 = $this->db->query($sql);
172 if ($resql2) {
173 while ($obj2 = $this->db->fetch_object($resql2)) {
174 $ids[$obj2->rowid] = $obj2->rowid;
175 $ids_fact[] = $obj2->fact_id;
176 }
177 $this->db->free($resql2);
178 } else {
179 $this->errors[] = $this->db->lasterror;
180 return -1;
181 }
182 if (count($ids_fact)) {
183 $sql = 'SELECT bk.rowid, facf.ref, facf.ref_supplier ';
184 $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
185 $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))."))";
186 $sql .= " WHERE bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=3 AND entity=".$conf->entity.") ";
187 $sql .= " AND facf.entity = ".$conf->entity;
188 $sql .= " AND ( ";
189 if ($object->code_compta_client != "") {
190 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
191 }
192 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
193 $sql .= " OR ";
194 }
195 if ($object->code_compta_fournisseur != "") {
196 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
197 }
198 $sql .= ") ";
199
200 $resql2 = $this->db->query($sql);
201 if ($resql2) {
202 while ($obj2 = $this->db->fetch_object($resql2)) {
203 $ids[$obj2->rowid] = $obj2->rowid;
204 }
205 $this->db->free($resql2);
206 } else {
207 $this->errors[] = $this->db->lasterror;
208 return -1;
209 }
210 }
211 } elseif ($obj->type == 'payment') {
212 $sql = 'SELECT DISTINCT bk.rowid, fac.ref, fac.ref, pay.fk_bank, fac.rowid as fact_id';
213 $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
214 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement_facture as payfac ON payfac.fk_facture=fac.rowid";
215 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement as pay ON payfac.fk_paiement=pay.rowid";
216 $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)."')";
217 $sql .= " WHERE payfac.fk_paiement = '".$this->db->escape($obj->url_id)."' ";
218 $sql .= " AND bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") ";
219 $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
220 $sql .= " AND ( ";
221 if ($object->code_compta_client != "") {
222 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
223 }
224 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
225 $sql .= " OR ";
226 }
227 if ($object->code_compta_fournisseur != "") {
228 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
229 }
230 $sql .= " )";
231
232 $resql2 = $this->db->query($sql);
233 if ($resql2) {
234 while ($obj2 = $this->db->fetch_object($resql2)) {
235 $ids[$obj2->rowid] = $obj2->rowid;
236 $ids_fact[] = $obj2->fact_id;
237 }
238 } else {
239 $this->errors[] = $this->db->lasterror;
240 return -1;
241 }
242 if (count($ids_fact)) {
243 $sql = 'SELECT bk.rowid, fac.ref, fac.ref_supplier ';
244 $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
245 $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))."))";
246 $sql .= " WHERE code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=2 AND entity=".$conf->entity.") ";
247 $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
248 $sql .= " AND ( ";
249 if ($object->code_compta_client != "") {
250 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_client)."' ";
251 }
252 if ($object->code_compta_client != "" && $object->code_compta_fournisseur != "") {
253 $sql .= " OR ";
254 }
255 if ($object->code_compta_fournisseur != "") {
256 $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
257 }
258 $sql .= " ) ";
259
260 $resql2 = $this->db->query($sql);
261 if ($resql2) {
262 while ($obj2 = $this->db->fetch_object($resql2)) {
263 $ids[$obj2->rowid] = $obj2->rowid;
264 }
265 $this->db->free($resql2);
266 } else {
267 $this->errors[] = $this->db->lasterror;
268 return -1;
269 }
270 }
271 }
272
273 if (count($ids) > 1) {
274 $result = $this->updateLettering($ids);
275 }
276 }
277 $this->db->free($resql);
278 }
279 if ($error) {
280 foreach ($this->errors as $errmsg) {
281 dol_syslog(__METHOD__.' '.$errmsg, LOG_ERR);
282 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
283 }
284 return -1 * $error;
285 } else {
286 return 1;
287 }
288 }
289
296 public function updateLettering($ids = array(), $notrigger = 0)
297 {
298 $error = 0;
299
300 // Generate a string with n char A where n is ACCOUNTING_LETTERING_NBLETTERS (So 'AA', 'AAA', ...) @phan-suppress-next-line PhanParamSuspiciousOrder
301 $lettre = str_pad("", getDolGlobalInt('ACCOUNTING_LETTERING_NBLETTERS', 3), "A");
302
303 $sql = "SELECT DISTINCT ab2.lettering_code";
304 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
305 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab2 ON ab2.subledger_account = ab.subledger_account";
306 $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ")";
307 $sql .= " AND ab2.lettering_code != ''";
308 $sql .= " ORDER BY ab2.lettering_code DESC";
309 $sql .= " LIMIT 1 ";
310
311 $resqla = $this->db->query($sql);
312 if ($resqla) {
313 $obj = $this->db->fetch_object($resqla);
314 $lettre = (empty($obj->lettering_code) ? $lettre : $obj->lettering_code);
315 if (!empty($obj->lettering_code)) {
316 $lettre++;
317 }
318 $this->db->free($resqla);
319 } else {
320 $this->errors[] = 'Error'.$this->db->lasterror();
321 $error++;
322 }
323
324 $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE ";
325 $sql .= " rowid IN (".$this->db->sanitize(implode(',', $ids)).") AND lettering_code IS NULL AND subledger_account != ''";
326 $resqlb = $this->db->query($sql);
327 if ($resqlb) {
328 $obj = $this->db->fetch_object($resqlb);
329 if (!(round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) {
330 $this->errors[] = 'Total not exacts '.round(abs($obj->deb), 2).' vs '.round(abs($obj->cred), 2);
331 $error++;
332 }
333 $this->db->free($resqlb);
334 } else {
335 $this->errors[] = 'Erreur sql'.$this->db->lasterror();
336 $error++;
337 }
338
339 // Update request
340 $now = dol_now();
341 $affected_rows = 0;
342
343 if (!$error) {
344 $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
345 $sql .= " lettering_code='".$this->db->escape($lettre)."'";
346 $sql .= ", date_lettering = '".$this->db->idate($now)."'"; // todo correct date it's false
347 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $ids)).") AND lettering_code IS NULL AND subledger_account != ''";
348
349 dol_syslog(get_class($this)."::update", LOG_DEBUG);
350 $resql = $this->db->query($sql);
351 if (!$resql) {
352 $error++;
353 $this->errors[] = "Error ".$this->db->lasterror();
354 } else {
355 $affected_rows = $this->db->affected_rows($resql);
356 }
357 }
358
359 // Commit or rollback
360 if ($error) {
361 foreach ($this->errors as $errmsg) {
362 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
363 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
364 }
365 return -1 * $error;
366 } else {
367 return $affected_rows;
368 }
369 }
370
377 public function deleteLettering($ids, $notrigger = 0)
378 {
379 $error = 0;
380
381 $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
382 $sql .= " lettering_code = NULL";
383 $sql .= ", date_lettering = NULL";
384 $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $ids)).")";
385 $sql .= " AND subledger_account != ''";
386
387 dol_syslog(get_class($this)."::update", LOG_DEBUG);
388 $resql = $this->db->query($sql);
389 if (!$resql) {
390 $error++;
391 $this->errors[] = "Error ".$this->db->lasterror();
392 }
393
394 // Commit or rollback
395 if ($error) {
396 foreach ($this->errors as $errmsg) {
397 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
398 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
399 }
400 return -1 * $error;
401 } else {
402 return $this->db->affected_rows($resql);
403 }
404 }
405
413 public function bookkeepingLetteringAll($bookkeeping_ids, $unlettering = false)
414 {
415 dol_syslog(__METHOD__ . " - ", LOG_DEBUG);
416
417 $error = 0;
418 $errors = array();
419 $nb_lettering = 0;
420
421 $result = $this->bookkeepingLettering($bookkeeping_ids, $unlettering);
422 if ($result < 0) {
423 $error++;
424 $errors = array_merge($errors, $this->errors);
425 $nb_lettering += abs($result) - 2;
426 } else {
427 $nb_lettering += $result;
428 }
429
430 if ($error) {
431 $this->errors = $errors;
432 return -2 - $nb_lettering;
433 } else {
434 return $nb_lettering;
435 }
436 }
437
445 public function bookkeepingLettering($bookkeeping_ids, $unlettering = false)
446 {
447 global $langs;
448
449 $this->errors = array();
450
451 // Clean parameters
452 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
453
454 $error = 0;
455 $nb_lettering = 0;
456 $grouped_lines = $this->getLinkedLines($bookkeeping_ids);
457 if (!is_array($grouped_lines)) {
458 return -2;
459 }
460
461 foreach ($grouped_lines as $lines) {
462 $group_error = 0;
463 $total = 0;
464 $do_it = !$unlettering;
465 $lettering_code = null;
466 $piece_num_lines = array();
467 $bookkeeping_lines = array();
468 foreach ($lines as $line_infos) {
469 $bookkeeping_lines[$line_infos['id']] = $line_infos['id'];
470 $piece_num_lines[$line_infos['piece_num']] = $line_infos['piece_num'];
471 $total += ($line_infos['credit'] > 0 ? $line_infos['credit'] : -$line_infos['debit']);
472
473 // Check lettering code
474 if ($unlettering) {
475 if (isset($lettering_code) && $lettering_code != $line_infos['lettering_code']) {
476 $this->errors[] = $langs->trans('AccountancyErrorMismatchLetteringCode');
477 $group_error++;
478 break;
479 }
480 if (!isset($lettering_code)) {
481 $lettering_code = (string) $line_infos['lettering_code'];
482 }
483 if (!empty($line_infos['lettering_code'])) {
484 $do_it = true;
485 }
486 } elseif (!empty($line_infos['lettering_code'])) {
487 $do_it = false;
488 }
489 }
490
491 // Check balance amount
492 if (!$group_error && !$unlettering && price2num($total) != 0) {
493 $this->errors[] = $langs->trans('AccountancyErrorMismatchBalanceAmount', $total);
494 $group_error++;
495 }
496
497 // Lettering/Unlettering the group of bookkeeping lines
498 if (!$group_error && $do_it) {
499 if ($unlettering) {
500 $result = $this->deleteLettering($bookkeeping_lines);
501 } else {
502 $result = $this->updateLettering($bookkeeping_lines);
503 }
504 if ($result < 0) {
505 $group_error++;
506 } elseif ($result > 0) {
507 $nb_lettering++;
508 }
509 }
510
511 if ($group_error) {
512 $this->errors[] = $langs->trans('AccountancyErrorLetteringBookkeeping', implode(', ', $piece_num_lines));
513 $error++;
514 }
515 }
516
517 if ($error) {
518 return -2 - $nb_lettering;
519 } else {
520 return $nb_lettering;
521 }
522 }
523
531 public function getLinkedLines($bookkeeping_ids, $only_has_subledger_account = true)
532 {
533 global $conf, $langs;
534 $this->errors = array();
535
536 // Clean parameters
537 $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
538
539 // Get all bookkeeping lines
540 $sql = "SELECT DISTINCT ab.doc_type, ab.fk_doc";
541 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
542 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
543 $sql .= " AND ab.fk_doc > 0";
544 if (!empty($bookkeeping_ids)) {
545 // Get all bookkeeping lines of piece number
546 $sql .= " AND EXISTS (";
547 $sql .= " SELECT rowid";
548 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS pn";
549 $sql .= " WHERE pn.entity IN (" . getEntity('accountancy') . ")";
550 $sql .= " AND pn.rowid IN (" . $this->db->sanitize(implode(',', $bookkeeping_ids)) . ")";
551 $sql .= " AND pn.piece_num = ab.piece_num";
552 $sql .= " )";
553 }
554 if ($only_has_subledger_account) {
555 $sql .= " AND ab.subledger_account != ''";
556 }
557
558 dol_syslog(__METHOD__ . " - Get all bookkeeping lines", LOG_DEBUG);
559 $resql = $this->db->query($sql);
560 if (!$resql) {
561 $this->errors[] = "Error " . $this->db->lasterror();
562 return -1;
563 }
564
565 $bookkeeping_lines_by_type = array();
566 while ($obj = $this->db->fetch_object($resql)) {
567 $bookkeeping_lines_by_type[$obj->doc_type][$obj->fk_doc] = $obj->fk_doc;
568 }
569 $this->db->free($resql);
570
571 if (empty($bookkeeping_lines_by_type)) {
572 return array();
573 }
574
575 if (!empty($bookkeeping_lines_by_type['bank'])) {
576 $new_bookkeeping_lines_by_type = $this->getDocTypeAndFkDocFromBankLines($bookkeeping_lines_by_type['bank']);
577 if (!is_array($new_bookkeeping_lines_by_type)) {
578 return -1;
579 }
580 foreach ($new_bookkeeping_lines_by_type as $doc_type => $fk_docs) {
581 foreach ($fk_docs as $fk_doc) {
582 $bookkeeping_lines_by_type[$doc_type][$fk_doc] = $fk_doc;
583 }
584 }
585 }
586
587 $grouped_lines = array();
588 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
589 if (!is_array($bookkeeping_lines_by_type[$doc_type])) {
590 continue;
591 }
592
593 // Get all document ids grouped
594 $doc_grouped = $this->getLinkedDocumentByGroup($bookkeeping_lines_by_type[$doc_type], $doc_type);
595 if (!is_array($doc_grouped)) {
596 return -1;
597 }
598
599 // Group all lines by document/piece number
600 foreach ($doc_grouped as $doc_ids) {
601 $bank_ids = $this->getBankLinesFromFkDocAndDocType($doc_ids, $doc_type);
602 if (!is_array($bank_ids)) {
603 return -1;
604 }
605
606 // Get all bookkeeping lines linked
607 $sql = "SELECT DISTINCT ab.rowid, ab.piece_num, ab.debit, ab.credit, ab.lettering_code";
608 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
609 $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
610 $sql .= " AND (";
611 if (!empty($bank_ids)) {
612 $sql .= " EXISTS (";
613 $sql .= " SELECT bpn.rowid";
614 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS bpn";
615 $sql .= " WHERE bpn.entity IN (" . getEntity('accountancy') . ")";
616 $sql .= " AND bpn.doc_type = 'bank'";
617 $sql .= " AND bpn.fk_doc IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
618 $sql .= " AND bpn.piece_num = ab.piece_num";
619 $sql .= " ) OR ";
620 }
621 $sql .= " EXISTS (";
622 $sql .= " SELECT dpn.rowid";
623 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS dpn";
624 $sql .= " WHERE dpn.entity IN (" . getEntity('accountancy') . ")";
625 $sql .= " AND dpn.doc_type = '" . $this->db->escape($doc_type) . "'";
626 $sql .= " AND dpn.fk_doc IN (" . $this->db->sanitize(implode(',', $doc_ids)) . ")";
627 $sql .= " AND dpn.piece_num = ab.piece_num";
628 $sql .= " )";
629 $sql .= ")";
630 if ($only_has_subledger_account) {
631 $sql .= " AND ab.subledger_account != ''";
632 }
633
634 dol_syslog(__METHOD__ . " - Get all bookkeeping lines linked", LOG_DEBUG);
635 $resql = $this->db->query($sql);
636 if (!$resql) {
637 $this->errors[] = "Error " . $this->db->lasterror();
638 return -1;
639 }
640
641 $group = array();
642 while ($obj = $this->db->fetch_object($resql)) {
643 $group[$obj->rowid] = array(
644 'id' => $obj->rowid,
645 'piece_num' => $obj->piece_num,
646 'debit' => $obj->debit,
647 'credit' => $obj->credit,
648 'lettering_code' => $obj->lettering_code,
649 );
650 }
651 $this->db->free($resql);
652
653 if (!empty($group)) {
654 $grouped_lines[] = $group;
655 }
656 }
657 }
658
659 return $grouped_lines;
660 }
661
668 public function getDocTypeAndFkDocFromBankLines($bank_ids)
669 {
670 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($bank_ids), LOG_DEBUG);
671
672 // Clean parameters
673 $bank_ids = is_array($bank_ids) ? $bank_ids : array();
674
675 if (empty($bank_ids)) {
676 return array();
677 }
678
679 $bookkeeping_lines_by_type = array();
680 foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
681 // Get all fk_doc by doc_type from bank ids
682 $sql = "SELECT DISTINCT dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " AS fk_doc";
683 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
684 $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";
685 $sql .= " WHERE p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
686 $sql .= " AND dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " > 0";
687
688 dol_syslog(__METHOD__ . " - Get all fk_doc by doc_type from list of bank ids for '" . $doc_type . "'", LOG_DEBUG);
689 $resql = $this->db->query($sql);
690 if (!$resql) {
691 $this->errors[] = "Error " . $this->db->lasterror();
692 return -1;
693 }
694
695 while ($obj = $this->db->fetch_object($resql)) {
696 $bookkeeping_lines_by_type[$doc_type][$obj->fk_doc] = $obj->fk_doc;
697 }
698 $this->db->free($resql);
699 }
700
701 return $bookkeeping_lines_by_type;
702 }
703
711 public function getBankLinesFromFkDocAndDocType($document_ids, $doc_type)
712 {
713 global $langs;
714
715 dol_syslog(__METHOD__ . " - bank_ids=".json_encode($document_ids) . ", doc_type=$doc_type", LOG_DEBUG);
716
717 // Clean parameters
718 $document_ids = is_array($document_ids) ? $document_ids : array();
719 //remove empty entries
720 $document_ids = array_filter($document_ids);
721
722 $doc_type = trim($doc_type);
723
724 if (empty($document_ids)) {
725 return array();
726 }
727 if (!is_array(self::$doc_type_infos[$doc_type])) {
728 $langs->load('errors');
729 $this->errors[] = $langs->trans('ErrorBadParameters');
730 return -1;
731 }
732
733 $doc_type_info = self::$doc_type_infos[$doc_type];
734 $bank_ids = array();
735
736 // Get all fk_doc by doc_type from bank ids
737 $sql = "SELECT DISTINCT p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " AS fk_doc";
738 $sql .= " FROM " . MAIN_DB_PREFIX . $this->db->sanitize($doc_type_info['payment_table']) . " AS p";
739 $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";
740 $sql .= " WHERE dp." . $this->db->sanitize($doc_type_info['doc_payment_table_fk_doc']) . " IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
741 $sql .= " AND p." . $this->db->sanitize($doc_type_info['payment_table_fk_bank']) . " > 0";
742
743 dol_syslog(__METHOD__ . " - Get all bank ids from list of document ids of a type '" . $doc_type . "'", LOG_DEBUG);
744 $resql = $this->db->query($sql);
745 if (!$resql) {
746 $this->errors[] = "Error " . $this->db->lasterror();
747 return -1;
748 }
749
750 while ($obj = $this->db->fetch_object($resql)) {
751 $bank_ids[$obj->fk_doc] = $obj->fk_doc;
752 }
753 $this->db->free($resql);
754
755 return $bank_ids;
756 }
757
765 public function getLinkedDocumentByGroup($document_ids, $doc_type)
766 {
767 global $langs;
768
769 // Clean parameters
770 $document_ids = is_array($document_ids) ? $document_ids : array();
771 $doc_type = trim($doc_type);
772 //remove empty entries
773 $document_ids = array_filter($document_ids);
774
775 if (empty($document_ids)) {
776 return array();
777 }
778
779 if (!is_array(self::$doc_type_infos[$doc_type])) {
780 $langs->load('errors');
781 $this->errors[] = $langs->trans('ErrorBadParameters');
782 return -1;
783 }
784
785 $doc_type_info = self::$doc_type_infos[$doc_type];
786
787 // Get document lines
788 $current_document_ids = array();
789 $link_by_element = array();
790 $element_by_link = array();
791 foreach ($doc_type_info['linked_info'] as $linked_info) {
792 if (empty($linked_info['fk_line_link'])) {
793 $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";
794 $sql .= " FROM ".MAIN_DB_PREFIX.$this->db->sanitize($linked_info['table'])." AS tl";
795 $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']);
796 $sql .= " WHERE tl.".$this->db->sanitize($linked_info['fk_doc'])." IN (".$this->db->sanitize(implode(',', $document_ids)).")";
797 } else {
798 $sql = "SELECT DISTINCT tl2.fk_link, tl2.fk_doc";
799 $sql .= " FROM (";
800 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
801 $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";
802 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
803 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
804 $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']);
805 $sql .= ") AS tl";
806 $sql .= " LEFT JOIN (";
807 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
808 $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";
809 $sql .= " FROM " . MAIN_DB_PREFIX .$this->db->sanitize($linked_info['table'])." AS tl";
810 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset
811 $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']);
812 $sql .= ") AS tl2 ON tl2.fk_link = tl.fk_link";
813 $sql .= " WHERE tl.fk_doc IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
814 $sql .= " AND tl2.fk_doc IS NOT NULL";
815 }
816
817 dol_syslog(__METHOD__ . " - Get document lines", LOG_DEBUG);
818 $resql = $this->db->query($sql);
819 if (!$resql) {
820 $this->errors[] = "Error " . $this->db->lasterror();
821 return -1;
822 }
823
824 $is_fk_link_is_also_fk_doc = !empty($linked_info['is_fk_link_is_also_fk_doc']);
825 while ($obj = $this->db->fetch_object($resql)) {
826 $current_document_ids[$obj->fk_doc] = $obj->fk_doc;
827
828 $link_key = $linked_info['prefix'] . $obj->fk_link;
829 $element_by_link[$link_key][$obj->fk_doc] = $obj->fk_doc;
830 $link_by_element[$obj->fk_doc][$link_key] = $link_key;
831 if ($is_fk_link_is_also_fk_doc) {
832 $element_by_link[$link_key][$obj->fk_link] = $obj->fk_link;
833 $link_by_element[$obj->fk_link][$link_key] = $link_key;
834 }
835 }
836 $this->db->free($resql);
837 }
838
839 if (count(array_diff($document_ids, $current_document_ids))) {
840 return $this->getLinkedDocumentByGroup($current_document_ids, $doc_type);
841 }
842
843 return $this->getGroupElements($link_by_element, $element_by_link);
844 }
845
855 public function getGroupElements(&$link_by_element, &$element_by_link, $link_key = '', &$current_group = array())
856 {
857 $grouped_elements = array();
858 if (!empty($link_key) && !isset($element_by_link[$link_key])) {
859 // Return if specific link key not found
860 return $grouped_elements;
861 }
862
863 if (empty($link_key)) {
864 // Save list when is the begin of recursive function
865 $save_link_by_element = $link_by_element;
866 $save_element_by_link = $element_by_link;
867 }
868
869 do {
870 // Get current element id, get this payment id list and delete the entry
871 $current_link_key = !empty($link_key) ? $link_key : array_keys($element_by_link)[0];
872 $element_ids = $element_by_link[$current_link_key];
873 unset($element_by_link[$current_link_key]);
874
875 foreach ($element_ids as $element_id) {
876 // Continue if element id in not found
877 if (!isset($link_by_element[$element_id])) {
878 continue;
879 }
880
881 // Set the element in the current group
882 $current_group[$element_id] = $element_id;
883
884 // Get current link keys, get this element id list and delete the entry
885 $link_keys = $link_by_element[$element_id];
886 unset($link_by_element[$element_id]);
887
888 // Set element id on the current group for each link key of the element
889 foreach ($link_keys as $key) {
890 $this->getGroupElements($link_by_element, $element_by_link, $key, $current_group);
891 }
892 }
893
894 if (empty($link_key)) {
895 // Save current group and reset the current group when is the begin of recursive function
896 $grouped_elements[] = $current_group;
897 $current_group = array();
898 }
899 } while (!empty($element_by_link) && empty($link_key));
900
901 if (empty($link_key)) {
902 // Restore list when is the begin of recursive function
903 $link_by_element = $save_link_by_element;
904 $element_by_link = $save_element_by_link;
905 }
906
907 return $grouped_elements;
908 }
909}
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.
updateLettering($ids=array(), $notrigger=0)
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.
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.