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