lettering.class.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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-2019 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. /**
  21. * \file htdocs/accountancy/class/lettering.class.php
  22. * \ingroup Accountancy (Double entries)
  23. * \brief File of class for lettering
  24. */
  25. include_once DOL_DOCUMENT_ROOT."/accountancy/class/bookkeeping.class.php";
  26. include_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
  27. include_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php";
  28. /**
  29. * Class Lettering
  30. */
  31. class Lettering extends BookKeeping
  32. {
  33. public static $doc_type_infos = array(
  34. 'customer_invoice' => array(
  35. 'payment_table' => 'paiement',
  36. 'payment_table_fk_bank' => 'fk_bank',
  37. 'doc_payment_table' => 'paiement_facture',
  38. 'doc_payment_table_fk_payment' => 'fk_paiement',
  39. 'doc_payment_table_fk_doc' => 'fk_facture',
  40. 'linked_info' => array(
  41. array(
  42. 'table' => 'paiement_facture',
  43. 'fk_doc' => 'fk_facture',
  44. 'fk_link' => 'fk_paiement',
  45. 'prefix' => 'p',
  46. ),
  47. array(
  48. 'table' => 'societe_remise_except',
  49. 'fk_doc' => 'fk_facture_source',
  50. 'fk_link' => 'fk_facture',
  51. 'prefix' => 'a',
  52. 'is_fk_link_is_also_fk_doc' => true,
  53. ),
  54. ),
  55. ),
  56. 'supplier_invoice' => array(
  57. 'payment_table' => 'paiementfourn',
  58. 'payment_table_fk_bank' => 'fk_bank',
  59. 'doc_payment_table' => 'paiementfourn_facturefourn',
  60. 'doc_payment_table_fk_payment' => 'fk_paiementfourn',
  61. 'doc_payment_table_fk_doc' => 'fk_facturefourn',
  62. 'linked_info' => array(
  63. array(
  64. 'table' => 'paiementfourn_facturefourn',
  65. 'fk_doc' => 'fk_facturefourn',
  66. 'fk_link' => 'fk_paiementfourn',
  67. 'prefix' => 'p',
  68. ),
  69. array(
  70. 'table' => 'societe_remise_except',
  71. 'fk_doc' => 'fk_invoice_supplier_source',
  72. 'fk_link' => 'fk_invoice_supplier',
  73. 'prefix' => 'a',
  74. 'is_fk_link_is_also_fk_doc' => true,
  75. ),
  76. ),
  77. ),
  78. );
  79. /**
  80. * letteringThirdparty
  81. *
  82. * @param int $socid Thirdparty id
  83. * @return int 1 OK, <0 error
  84. */
  85. public function letteringThirdparty($socid)
  86. {
  87. global $conf;
  88. $error = 0;
  89. $object = new Societe($this->db);
  90. $object->id = $socid;
  91. $object->fetch($socid);
  92. if ($object->code_compta == '411CUSTCODE') {
  93. $object->code_compta = '';
  94. }
  95. if ($object->code_compta_fournisseur == '401SUPPCODE') {
  96. $object->code_compta_fournisseur = '';
  97. }
  98. /**
  99. * Prise en charge des lettering complexe avec prelevment , virement
  100. */
  101. $sql = "SELECT DISTINCT bk.rowid, bk.doc_date, bk.doc_type, bk.doc_ref, bk.subledger_account, ";
  102. $sql .= " bk.numero_compte , bk.label_compte, bk.debit , bk.credit, bk.montant ";
  103. $sql .= " , bk.sens , bk.code_journal , bk.piece_num, bk.date_lettering, bu.url_id , bu.type ";
  104. $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as bk";
  105. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_url as bu ON(bk.fk_doc = bu.fk_bank AND bu.type IN ('payment', 'payment_supplier') ) ";
  106. $sql .= " WHERE ( ";
  107. if ($object->code_compta != "") {
  108. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' ";
  109. }
  110. if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
  111. $sql .= " OR ";
  112. }
  113. if ($object->code_compta_fournisseur != "") {
  114. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
  115. }
  116. $sql .= " ) AND (bk.date_lettering ='' OR bk.date_lettering IS NULL) ";
  117. $sql .= " AND (bk.lettering_code != '' OR bk.lettering_code IS NULL) ";
  118. $sql .= ' AND bk.date_validated IS NULL ';
  119. $sql .= $this->db->order('bk.doc_date', 'DESC');
  120. // echo $sql;
  121. //
  122. $resql = $this->db->query($sql);
  123. if ($resql) {
  124. $num = $this->db->num_rows($resql);
  125. while ($obj = $this->db->fetch_object($resql)) {
  126. $ids = array();
  127. $ids_fact = array();
  128. if ($obj->type == 'payment_supplier') {
  129. $sql = 'SELECT DISTINCT bk.rowid, facf.ref, facf.ref_supplier, payf.fk_bank, facf.rowid as fact_id';
  130. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
  131. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as payfacf ON payfacf.fk_facturefourn=facf.rowid";
  132. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiementfourn as payf ON payfacf.fk_paiementfourn=payf.rowid";
  133. $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)."')";
  134. $sql .= " WHERE payfacf.fk_paiementfourn = '".$this->db->escape($obj->url_id)."' ";
  135. $sql .= " AND facf.entity = ".$conf->entity;
  136. $sql .= " AND code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") ";
  137. $sql .= " AND ( ";
  138. if ($object->code_compta != "") {
  139. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' ";
  140. }
  141. if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
  142. $sql .= " OR ";
  143. }
  144. if ($object->code_compta_fournisseur != "") {
  145. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
  146. }
  147. $sql .= " ) ";
  148. $resql2 = $this->db->query($sql);
  149. if ($resql2) {
  150. while ($obj2 = $this->db->fetch_object($resql2)) {
  151. $ids[$obj2->rowid] = $obj2->rowid;
  152. $ids_fact[] = $obj2->fact_id;
  153. }
  154. $this->db->free($resql2);
  155. } else {
  156. $this->errors[] = $this->db->lasterror;
  157. return -1;
  158. }
  159. if (count($ids_fact)) {
  160. $sql = 'SELECT bk.rowid, facf.ref, facf.ref_supplier ';
  161. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn facf ";
  162. $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))."))";
  163. $sql .= " WHERE bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=3 AND entity=".$conf->entity.") ";
  164. $sql .= " AND facf.entity = ".$conf->entity;
  165. $sql .= " AND ( ";
  166. if ($object->code_compta != "") {
  167. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' ";
  168. }
  169. if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
  170. $sql .= " OR ";
  171. }
  172. if ($object->code_compta_fournisseur != "") {
  173. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
  174. }
  175. $sql .= ") ";
  176. $resql2 = $this->db->query($sql);
  177. if ($resql2) {
  178. while ($obj2 = $this->db->fetch_object($resql2)) {
  179. $ids[$obj2->rowid] = $obj2->rowid;
  180. }
  181. $this->db->free($resql2);
  182. } else {
  183. $this->errors[] = $this->db->lasterror;
  184. return -1;
  185. }
  186. }
  187. } elseif ($obj->type == 'payment') {
  188. $sql = 'SELECT DISTINCT bk.rowid, fac.ref, fac.ref, pay.fk_bank, fac.rowid as fact_id';
  189. $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
  190. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement_facture as payfac ON payfac.fk_facture=fac.rowid";
  191. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."paiement as pay ON payfac.fk_paiement=pay.rowid";
  192. $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)."')";
  193. $sql .= " WHERE payfac.fk_paiement = '".$this->db->escape($obj->url_id)."' ";
  194. $sql .= " AND bk.code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=4 AND entity=".$conf->entity.") ";
  195. $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
  196. $sql .= " AND ( ";
  197. if ($object->code_compta != "") {
  198. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' ";
  199. }
  200. if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
  201. $sql .= " OR ";
  202. }
  203. if ($object->code_compta_fournisseur != "") {
  204. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
  205. }
  206. $sql .= " )";
  207. $resql2 = $this->db->query($sql);
  208. if ($resql2) {
  209. while ($obj2 = $this->db->fetch_object($resql2)) {
  210. $ids[$obj2->rowid] = $obj2->rowid;
  211. $ids_fact[] = $obj2->fact_id;
  212. }
  213. } else {
  214. $this->errors[] = $this->db->lasterror;
  215. return -1;
  216. }
  217. if (count($ids_fact)) {
  218. $sql = 'SELECT bk.rowid, fac.ref, fac.ref_supplier ';
  219. $sql .= " FROM ".MAIN_DB_PREFIX."facture fac ";
  220. $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))."))";
  221. $sql .= " WHERE code_journal IN (SELECT code FROM ".MAIN_DB_PREFIX."accounting_journal WHERE nature=2 AND entity=".$conf->entity.") ";
  222. $sql .= " AND fac.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
  223. $sql .= " AND ( ";
  224. if ($object->code_compta != "") {
  225. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta)."' ";
  226. }
  227. if ($object->code_compta != "" && $object->code_compta_fournisseur != "") {
  228. $sql .= " OR ";
  229. }
  230. if ($object->code_compta_fournisseur != "") {
  231. $sql .= " bk.subledger_account = '".$this->db->escape($object->code_compta_fournisseur)."' ";
  232. }
  233. $sql .= " ) ";
  234. $resql2 = $this->db->query($sql);
  235. if ($resql2) {
  236. while ($obj2 = $this->db->fetch_object($resql2)) {
  237. $ids[$obj2->rowid] = $obj2->rowid;
  238. }
  239. $this->db->free($resql2);
  240. } else {
  241. $this->errors[] = $this->db->lasterror;
  242. return -1;
  243. }
  244. }
  245. }
  246. if (count($ids) > 1) {
  247. $result = $this->updateLettering($ids);
  248. }
  249. }
  250. $this->db->free($resql);
  251. }
  252. if ($error) {
  253. foreach ($this->errors as $errmsg) {
  254. dol_syslog(__METHOD__.' '.$errmsg, LOG_ERR);
  255. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  256. }
  257. return -1 * $error;
  258. } else {
  259. return 1;
  260. }
  261. }
  262. /**
  263. *
  264. * @param array $ids ids array
  265. * @param boolean $notrigger no trigger
  266. * @return int
  267. */
  268. public function updateLettering($ids = array(), $notrigger = false)
  269. {
  270. $error = 0;
  271. $lettre = 'AAA';
  272. $sql = "SELECT DISTINCT ab2.lettering_code";
  273. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
  274. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab2 ON ab2.subledger_account = ab.subledger_account";
  275. $sql .= " WHERE ab.rowid IN (" . $this->db->sanitize(implode(',', $ids)) . ")";
  276. $sql .= " AND ab2.lettering_code != ''";
  277. $sql .= " ORDER BY ab2.lettering_code DESC";
  278. $sql .= " LIMIT 1 ";
  279. $resqla = $this->db->query($sql);
  280. if ($resqla) {
  281. $obj = $this->db->fetch_object($resqla);
  282. $lettre = (empty($obj->lettering_code) ? $lettre : $obj->lettering_code);
  283. if (!empty($obj->lettering_code)) {
  284. $lettre++;
  285. }
  286. $this->db->free($resqla);
  287. } else {
  288. $this->errors[] = 'Error'.$this->db->lasterror();
  289. $error++;
  290. }
  291. $sql = "SELECT SUM(ABS(debit)) as deb, SUM(ABS(credit)) as cred FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE ";
  292. $sql .= " rowid IN (".$this->db->sanitize(implode(',', $ids)).") AND lettering_code IS NULL AND subledger_account != ''";
  293. $resqlb = $this->db->query($sql);
  294. if ($resqlb) {
  295. $obj = $this->db->fetch_object($resqlb);
  296. if (!(round(abs($obj->deb), 2) === round(abs($obj->cred), 2))) {
  297. $this->errors[] = 'Total not exacts '.round(abs($obj->deb), 2).' vs '.round(abs($obj->cred), 2);
  298. $error++;
  299. }
  300. $this->db->free($resqlb);
  301. } else {
  302. $this->errors[] = 'Erreur sql'.$this->db->lasterror();
  303. $error++;
  304. }
  305. // Update request
  306. $now = dol_now();
  307. $affected_rows = 0;
  308. if (!$error) {
  309. $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
  310. $sql .= " lettering_code='".$this->db->escape($lettre)."'";
  311. $sql .= ", date_lettering = '".$this->db->idate($now)."'"; // todo correct date it's false
  312. $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $ids)).") AND lettering_code IS NULL AND subledger_account != ''";
  313. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  314. $resql = $this->db->query($sql);
  315. if (!$resql) {
  316. $error++;
  317. $this->errors[] = "Error ".$this->db->lasterror();
  318. } else {
  319. $affected_rows = $this->db->affected_rows($resql);
  320. }
  321. }
  322. // Commit or rollback
  323. if ($error) {
  324. foreach ($this->errors as $errmsg) {
  325. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  326. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  327. }
  328. return -1 * $error;
  329. } else {
  330. return $affected_rows;
  331. }
  332. }
  333. /**
  334. *
  335. * @param array $ids ids array
  336. * @param boolean $notrigger no trigger
  337. * @return int
  338. */
  339. public function deleteLettering($ids, $notrigger = false)
  340. {
  341. $error = 0;
  342. $sql = "UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping SET";
  343. $sql .= " lettering_code = NULL";
  344. $sql .= ", date_lettering = NULL";
  345. $sql .= " WHERE rowid IN (".$this->db->sanitize(implode(',', $ids)).")";
  346. $sql .= " AND subledger_account != ''";
  347. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  348. $resql = $this->db->query($sql);
  349. if (!$resql) {
  350. $error++;
  351. $this->errors[] = "Error ".$this->db->lasterror();
  352. }
  353. // Commit or rollback
  354. if ($error) {
  355. foreach ($this->errors as $errmsg) {
  356. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  357. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  358. }
  359. return -1 * $error;
  360. } else {
  361. return $this->db->affected_rows($resql);
  362. }
  363. }
  364. /**
  365. * Lettering bookkeeping lines all types
  366. *
  367. * @param array $bookkeeping_ids Lettering specific list of bookkeeping id
  368. * @param bool $unlettering Do unlettering
  369. * @return int <0 if error (nb lettered = result -1), 0 if noting to lettering, >0 if OK (nb lettered)
  370. */
  371. public function bookkeepingLetteringAll($bookkeeping_ids, $unlettering = false)
  372. {
  373. dol_syslog(__METHOD__ . " - ", LOG_DEBUG);
  374. $error = 0;
  375. $errors = array();
  376. $nb_lettering = 0;
  377. $result = $this->bookkeepingLettering($bookkeeping_ids, $unlettering);
  378. if ($result < 0) {
  379. $error++;
  380. $errors = array_merge($errors, $this->errors);
  381. $nb_lettering += abs($result) - 2;
  382. } else {
  383. $nb_lettering += $result;
  384. }
  385. if ($error) {
  386. $this->errors = $errors;
  387. return -2 - $nb_lettering;
  388. } else {
  389. return $nb_lettering;
  390. }
  391. }
  392. /**
  393. * Lettering bookkeeping lines
  394. *
  395. * @param array $bookkeeping_ids Lettering specific list of bookkeeping id
  396. * @param bool $unlettering Do unlettering
  397. * @return int <0 if error (nb lettered = result -1), 0 if noting to lettering, >0 if OK (nb lettered)
  398. */
  399. public function bookkeepingLettering($bookkeeping_ids, $unlettering = false)
  400. {
  401. global $langs;
  402. $this->errors = array();
  403. // Clean parameters
  404. $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
  405. $error = 0;
  406. $nb_lettering = 0;
  407. $grouped_lines = $this->getLinkedLines($bookkeeping_ids);
  408. if (!is_array($grouped_lines)) {
  409. return -2;
  410. }
  411. foreach ($grouped_lines as $lines) {
  412. $group_error = 0;
  413. $total = 0;
  414. $do_it = !$unlettering;
  415. $lettering_code = null;
  416. $piece_num_lines = array();
  417. $bookkeeping_lines = array();
  418. foreach ($lines as $line_infos) {
  419. $bookkeeping_lines[$line_infos['id']] = $line_infos['id'];
  420. $piece_num_lines[$line_infos['piece_num']] = $line_infos['piece_num'];
  421. $total += ($line_infos['credit'] > 0 ? $line_infos['credit'] : -$line_infos['debit']);
  422. // Check lettering code
  423. if ($unlettering) {
  424. if (isset($lettering_code) && $lettering_code != $line_infos['lettering_code']) {
  425. $this->errors[] = $langs->trans('AccountancyErrorMismatchLetteringCode');
  426. $group_error++;
  427. break;
  428. }
  429. if (!isset($lettering_code)) $lettering_code = (string) $line_infos['lettering_code'];
  430. if (!empty($line_infos['lettering_code'])) $do_it = true;
  431. } elseif (!empty($line_infos['lettering_code'])) $do_it = false;
  432. }
  433. // Check balance amount
  434. if (!$group_error && !$unlettering && price2num($total) != 0) {
  435. $this->errors[] = $langs->trans('AccountancyErrorMismatchBalanceAmount', $total);
  436. $group_error++;
  437. }
  438. // Lettering/Unlettering the group of bookkeeping lines
  439. if (!$group_error && $do_it) {
  440. if ($unlettering) $result = $this->deleteLettering($bookkeeping_lines);
  441. else $result = $this->updateLettering($bookkeeping_lines);
  442. if ($result < 0) {
  443. $group_error++;
  444. } elseif ($result > 0) {
  445. $nb_lettering++;
  446. }
  447. }
  448. if ($group_error) {
  449. $this->errors[] = $langs->trans('AccountancyErrorLetteringBookkeeping', implode(', ', $piece_num_lines));
  450. $error++;
  451. }
  452. }
  453. if ($error) {
  454. return -2 - $nb_lettering;
  455. } else {
  456. return $nb_lettering;
  457. }
  458. }
  459. /**
  460. * Lettering bookkeeping lines
  461. *
  462. * @param array $bookkeeping_ids Lettering specific list of bookkeeping id
  463. * @param bool $only_has_subledger_account Get only lines who have subledger account
  464. * @return array|int <0 if error otherwise all linked lines by block
  465. */
  466. public function getLinkedLines($bookkeeping_ids, $only_has_subledger_account = true)
  467. {
  468. global $conf, $langs;
  469. $this->errors = array();
  470. // Clean parameters
  471. $bookkeeping_ids = is_array($bookkeeping_ids) ? $bookkeeping_ids : array();
  472. // Get all bookkeeping lines
  473. $sql = "SELECT DISTINCT ab.doc_type, ab.fk_doc";
  474. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
  475. $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
  476. $sql .= " AND ab.fk_doc > 0";
  477. if (!empty($bookkeeping_ids)) {
  478. // Get all bookkeeping lines of piece number
  479. $sql .= " AND EXISTS (";
  480. $sql .= " SELECT rowid";
  481. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS pn";
  482. $sql .= " WHERE pn.entity IN (" . getEntity('accountancy') . ")";
  483. $sql .= " AND pn.rowid IN (" . $this->db->sanitize(implode(',', $bookkeeping_ids)) . ")";
  484. $sql .= " AND pn.piece_num = ab.piece_num";
  485. $sql .= " )";
  486. }
  487. if ($only_has_subledger_account) $sql .= " AND ab.subledger_account != ''";
  488. dol_syslog(__METHOD__ . " - Get all bookkeeping lines", LOG_DEBUG);
  489. $resql = $this->db->query($sql);
  490. if (!$resql) {
  491. $this->errors[] = "Error " . $this->db->lasterror();
  492. return -1;
  493. }
  494. $bookkeeping_lines_by_type = array();
  495. while ($obj = $this->db->fetch_object($resql)) {
  496. $bookkeeping_lines_by_type[$obj->doc_type][$obj->fk_doc] = $obj->fk_doc;
  497. }
  498. $this->db->free($resql);
  499. if (empty($bookkeeping_lines_by_type)) {
  500. return array();
  501. }
  502. if (!empty($bookkeeping_lines_by_type['bank'])) {
  503. $new_bookkeeping_lines_by_type = $this->getDocTypeAndFkDocFromBankLines($bookkeeping_lines_by_type['bank']);
  504. if (!is_array($new_bookkeeping_lines_by_type)) {
  505. return -1;
  506. }
  507. foreach ($new_bookkeeping_lines_by_type as $doc_type => $fk_docs) {
  508. foreach ($fk_docs as $fk_doc) {
  509. $bookkeeping_lines_by_type[$doc_type][$fk_doc] = $fk_doc;
  510. }
  511. }
  512. }
  513. $grouped_lines = array();
  514. foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
  515. if (!is_array($bookkeeping_lines_by_type[$doc_type])) {
  516. continue;
  517. }
  518. // Get all document ids grouped
  519. $doc_grouped = $this->getLinkedDocumentByGroup($bookkeeping_lines_by_type[$doc_type], $doc_type);
  520. if (!is_array($doc_grouped)) {
  521. return -1;
  522. }
  523. // Group all lines by document/piece number
  524. foreach ($doc_grouped as $doc_ids) {
  525. $bank_ids = $this->getBankLinesFromFkDocAndDocType($doc_ids, $doc_type);
  526. if (!is_array($bank_ids)) {
  527. return -1;
  528. }
  529. // Get all bookkeeping lines linked
  530. $sql = "SELECT DISTINCT ab.rowid, ab.piece_num, ab.debit, ab.credit, ab.lettering_code";
  531. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS ab";
  532. $sql .= " WHERE ab.entity IN (" . getEntity('accountancy') . ")";
  533. $sql .= " AND (";
  534. if (!empty($bank_ids)) {
  535. $sql .= " EXISTS (";
  536. $sql .= " SELECT bpn.rowid";
  537. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS bpn";
  538. $sql .= " WHERE bpn.entity IN (" . getEntity('accountancy') . ")";
  539. $sql .= " AND bpn.doc_type = 'bank'";
  540. $sql .= " AND bpn.fk_doc IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
  541. $sql .= " AND bpn.piece_num = ab.piece_num";
  542. $sql .= " ) OR ";
  543. }
  544. $sql .= " EXISTS (";
  545. $sql .= " SELECT dpn.rowid";
  546. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping AS dpn";
  547. $sql .= " WHERE dpn.entity IN (" . getEntity('accountancy') . ")";
  548. $sql .= " AND dpn.doc_type = '" . $this->db->escape($doc_type) . "'";
  549. $sql .= " AND dpn.fk_doc IN (" . $this->db->sanitize(implode(',', $doc_ids)) . ")";
  550. $sql .= " AND dpn.piece_num = ab.piece_num";
  551. $sql .= " )";
  552. $sql .= ")";
  553. if ($only_has_subledger_account) $sql .= " AND ab.subledger_account != ''";
  554. dol_syslog(__METHOD__ . " - Get all bookkeeping lines linked", LOG_DEBUG);
  555. $resql = $this->db->query($sql);
  556. if (!$resql) {
  557. $this->errors[] = "Error " . $this->db->lasterror();
  558. return -1;
  559. }
  560. $group = array();
  561. while ($obj = $this->db->fetch_object($resql)) {
  562. $group[$obj->rowid] = array(
  563. 'id' => $obj->rowid,
  564. 'piece_num' => $obj->piece_num,
  565. 'debit' => $obj->debit,
  566. 'credit' => $obj->credit,
  567. 'lettering_code' => $obj->lettering_code,
  568. );
  569. }
  570. $this->db->free($resql);
  571. if (!empty($group)) $grouped_lines[] = $group;
  572. }
  573. }
  574. return $grouped_lines;
  575. }
  576. /**
  577. * Get all fk_doc by doc_type from list of bank ids
  578. *
  579. * @param array $bank_ids List of bank ids
  580. * @return array|int <0 if error otherwise all fk_doc by doc_type
  581. */
  582. public function getDocTypeAndFkDocFromBankLines($bank_ids)
  583. {
  584. dol_syslog(__METHOD__ . " - bank_ids=".json_encode($bank_ids), LOG_DEBUG);
  585. // Clean parameters
  586. $bank_ids = is_array($bank_ids) ? $bank_ids : array();
  587. if (empty($bank_ids)) {
  588. return array();
  589. }
  590. $bookkeeping_lines_by_type = array();
  591. foreach (self::$doc_type_infos as $doc_type => $doc_type_info) {
  592. // Get all fk_doc by doc_type from bank ids
  593. $sql = "SELECT DISTINCT dp." . $doc_type_info['doc_payment_table_fk_doc'] . " AS fk_doc";
  594. $sql .= " FROM " . MAIN_DB_PREFIX . $doc_type_info['payment_table'] . " AS p";
  595. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $doc_type_info['doc_payment_table'] . " AS dp ON dp." . $doc_type_info['doc_payment_table_fk_payment'] . " = p.rowid";
  596. $sql .= " WHERE p." . $doc_type_info['payment_table_fk_bank'] . " IN (" . $this->db->sanitize(implode(',', $bank_ids)) . ")";
  597. $sql .= " AND dp." . $doc_type_info['doc_payment_table_fk_doc'] . " > 0";
  598. dol_syslog(__METHOD__ . " - Get all fk_doc by doc_type from list of bank ids for '" . $doc_type . "'", LOG_DEBUG);
  599. $resql = $this->db->query($sql);
  600. if (!$resql) {
  601. $this->errors[] = "Error " . $this->db->lasterror();
  602. return -1;
  603. }
  604. while ($obj = $this->db->fetch_object($resql)) {
  605. $bookkeeping_lines_by_type[$doc_type][$obj->fk_doc] = $obj->fk_doc;
  606. }
  607. $this->db->free($resql);
  608. }
  609. return $bookkeeping_lines_by_type;
  610. }
  611. /**
  612. * Get all bank ids from list of document ids of a type
  613. *
  614. * @param array $document_ids List of document id
  615. * @param string $doc_type Type of document ('customer_invoice' or 'supplier_invoice', ...)
  616. * @return array|int <0 if error otherwise all all bank ids from list of document ids of a type
  617. */
  618. public function getBankLinesFromFkDocAndDocType($document_ids, $doc_type)
  619. {
  620. global $langs;
  621. dol_syslog(__METHOD__ . " - bank_ids=".json_encode($document_ids) . ", doc_type=$doc_type", LOG_DEBUG);
  622. // Clean parameters
  623. $document_ids = is_array($document_ids) ? $document_ids : array();
  624. $doc_type = trim($doc_type);
  625. if (empty($document_ids)) {
  626. return array();
  627. }
  628. if (!is_array(self::$doc_type_infos[$doc_type])) {
  629. $langs->load('errors');
  630. $this->errors[] = $langs->trans('ErrorBadParameters');
  631. return -1;
  632. }
  633. $doc_type_info = self::$doc_type_infos[$doc_type];
  634. $bank_ids = array();
  635. // Get all fk_doc by doc_type from bank ids
  636. $sql = "SELECT DISTINCT p." . $doc_type_info['payment_table_fk_bank'] . " AS fk_doc";
  637. $sql .= " FROM " . MAIN_DB_PREFIX . $doc_type_info['payment_table'] . " AS p";
  638. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $doc_type_info['doc_payment_table'] . " AS dp ON dp." . $doc_type_info['doc_payment_table_fk_payment'] . " = p.rowid";
  639. $sql .= " WHERE dp." . $doc_type_info['doc_payment_table_fk_doc'] . " IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
  640. $sql .= " AND p." . $doc_type_info['payment_table_fk_bank'] . " > 0";
  641. dol_syslog(__METHOD__ . " - Get all bank ids from list of document ids of a type '" . $doc_type . "'", LOG_DEBUG);
  642. $resql = $this->db->query($sql);
  643. if (!$resql) {
  644. $this->errors[] = "Error " . $this->db->lasterror();
  645. return -1;
  646. }
  647. while ($obj = $this->db->fetch_object($resql)) {
  648. $bank_ids[$obj->fk_doc] = $obj->fk_doc;
  649. }
  650. $this->db->free($resql);
  651. return $bank_ids;
  652. }
  653. /**
  654. * Get all linked document ids by group and type
  655. *
  656. * @param array $document_ids List of document id
  657. * @param string $doc_type Type of document ('customer_invoice' or 'supplier_invoice', ...)
  658. * @return array|int <0 if error otherwise all linked document ids by group and type [ [ 'doc_type' => [ doc_id, ... ], ... ], ... ]
  659. */
  660. public function getLinkedDocumentByGroup($document_ids, $doc_type)
  661. {
  662. global $langs;
  663. // Clean parameters
  664. $document_ids = is_array($document_ids) ? $document_ids : array();
  665. $doc_type = trim($doc_type);
  666. if (empty($document_ids)) {
  667. return array();
  668. }
  669. if (!is_array(self::$doc_type_infos[$doc_type])) {
  670. $langs->load('errors');
  671. $this->errors[] = $langs->trans('ErrorBadParameters');
  672. return -1;
  673. }
  674. $doc_type_info = self::$doc_type_infos[$doc_type];
  675. // Get document lines
  676. $current_document_ids = array();
  677. $link_by_element = array();
  678. $element_by_link = array();
  679. foreach ($doc_type_info['linked_info'] as $linked_info) {
  680. $sql = "SELECT DISTINCT tl2." . $linked_info['fk_link'] . " AS fk_link, tl2." . $linked_info['fk_doc'] . " AS fk_doc";
  681. $sql .= " FROM " . MAIN_DB_PREFIX . $linked_info['table'] . " AS tl";
  682. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $linked_info['table'] . " AS tl2 ON tl2." . $linked_info['fk_link'] . " = tl." . $linked_info['fk_link'];
  683. $sql .= " WHERE tl." . $linked_info['fk_doc'] . " IN (" . $this->db->sanitize(implode(',', $document_ids)) . ")";
  684. dol_syslog(__METHOD__ . " - Get document lines", LOG_DEBUG);
  685. $resql = $this->db->query($sql);
  686. if (!$resql) {
  687. $this->errors[] = "Error " . $this->db->lasterror();
  688. return -1;
  689. }
  690. $is_fk_link_is_also_fk_doc = !empty($linked_info['is_fk_link_is_also_fk_doc']);
  691. while ($obj = $this->db->fetch_object($resql)) {
  692. $current_document_ids[$obj->fk_doc] = $obj->fk_doc;
  693. $link_key = $linked_info['prefix'] . $obj->fk_link;
  694. $element_by_link[$link_key][$obj->fk_doc] = $obj->fk_doc;
  695. $link_by_element[$obj->fk_doc][$link_key] = $link_key;
  696. if ($is_fk_link_is_also_fk_doc) {
  697. $element_by_link[$link_key][$obj->fk_link] = $obj->fk_link;
  698. $link_by_element[$obj->fk_link][$link_key] = $link_key;
  699. }
  700. }
  701. $this->db->free($resql);
  702. }
  703. if (count(array_diff($document_ids, $current_document_ids))) {
  704. return $this->getLinkedDocumentByGroup($current_document_ids, $doc_type);
  705. }
  706. return $this->getGroupElements($link_by_element, $element_by_link);
  707. }
  708. /**
  709. * Get element ids grouped by link or element in common
  710. *
  711. * @param array $link_by_element List of payment ids by link key
  712. * @param array $element_by_link List of element ids by link key
  713. * @param string $link_key Link key (used for recursive function)
  714. * @param array $current_group Current group (used for recursive function)
  715. * @return array List of element ids grouped by link or element in common
  716. */
  717. public function getGroupElements(&$link_by_element, &$element_by_link, $link_key = '', &$current_group = array())
  718. {
  719. $grouped_elements = array();
  720. if (!empty($link_key) && !isset($element_by_link[$link_key])) {
  721. // Return if specific link key not found
  722. return $grouped_elements;
  723. }
  724. if (empty($link_key)) {
  725. // Save list when is the begin of recursive function
  726. $save_link_by_element = $link_by_element;
  727. $save_element_by_link = $element_by_link;
  728. }
  729. do {
  730. // Get current element id, get this payment id list and delete the entry
  731. $current_link_key = !empty($link_key) ? $link_key : array_keys($element_by_link)[0];
  732. $element_ids = $element_by_link[$current_link_key];
  733. unset($element_by_link[$current_link_key]);
  734. foreach ($element_ids as $element_id) {
  735. // Continue if element id in not found
  736. if (!isset($link_by_element[$element_id])) continue;
  737. // Set the element in the current group
  738. $current_group[$element_id] = $element_id;
  739. // Get current link keys, get this element id list and delete the entry
  740. $link_keys = $link_by_element[$element_id];
  741. unset($link_by_element[$element_id]);
  742. // Set element id on the current group for each link key of the element
  743. foreach ($link_keys as $key) {
  744. $this->getGroupElements($link_by_element, $element_by_link, $key, $current_group);
  745. }
  746. }
  747. if (empty($link_key)) {
  748. // Save current group and reset the current group when is the begin of recursive function
  749. $grouped_elements[] = $current_group;
  750. $current_group = array();
  751. }
  752. } while (!empty($element_by_link) && empty($link_key));
  753. if (empty($link_key)) {
  754. // Restore list when is the begin of recursive function
  755. $link_by_element = $save_link_by_element;
  756. $element_by_link = $save_element_by_link;
  757. }
  758. return $grouped_elements;
  759. }
  760. }