remisecheque.class.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. <?php
  2. /* Copyright (C) 2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2007-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2009 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2011-2016 Juanjo Menent <jmenent@2byte.es>
  6. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. */
  21. /**
  22. * \file htdocs/compta/paiement/cheque/class/remisecheque.class.php
  23. * \ingroup compta
  24. * \brief File with class to manage cheque delivery receipts
  25. */
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  28. /**
  29. * Class to manage cheque delivery receipts
  30. */
  31. class RemiseCheque extends CommonObject
  32. {
  33. /**
  34. * @var string ID to identify managed object
  35. */
  36. public $element = 'chequereceipt';
  37. /**
  38. * @var string Name of table without prefix where object is stored
  39. */
  40. public $table_element = 'bordereau_cheque';
  41. /**
  42. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  43. */
  44. public $picto = 'payment';
  45. public $num;
  46. public $intitule;
  47. //! Numero d'erreur Plage 1024-1279
  48. public $errno;
  49. public $type = 'CHQ'; // 'CHQ', 'TRA', ...
  50. public $amount;
  51. public $date_bordereau;
  52. public $account_id;
  53. public $account_label;
  54. public $author_id;
  55. public $nbcheque;
  56. /**
  57. * @var string Ref
  58. */
  59. public $ref;
  60. const STATUS_DRAFT = 0;
  61. const STATUS_VALIDATED = 1;
  62. /**
  63. * Constructor
  64. *
  65. * @param DoliDB $db Database handler
  66. */
  67. public function __construct($db)
  68. {
  69. $this->db = $db;
  70. }
  71. /**
  72. * Load record
  73. *
  74. * @param int $id Id record
  75. * @param string $ref Ref record
  76. * @return int Return integer <0 if KO, > 0 if OK
  77. */
  78. public function fetch($id, $ref = '')
  79. {
  80. global $conf;
  81. $sql = "SELECT bc.rowid, bc.datec, bc.fk_user_author, bc.fk_bank_account, bc.amount, bc.ref, bc.statut, bc.nbcheque, bc.ref_ext,";
  82. $sql .= " bc.date_bordereau as date_bordereau, bc.type,";
  83. $sql .= " ba.label as account_label";
  84. $sql .= " FROM ".MAIN_DB_PREFIX."bordereau_cheque as bc";
  85. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON bc.fk_bank_account = ba.rowid";
  86. $sql .= " WHERE bc.entity = ".$conf->entity;
  87. if ($id) {
  88. $sql .= " AND bc.rowid = ".((int) $id);
  89. }
  90. if ($ref) {
  91. $sql .= " AND bc.ref = '".$this->db->escape($ref)."'";
  92. }
  93. dol_syslog("RemiseCheque::fetch", LOG_DEBUG);
  94. $resql = $this->db->query($sql);
  95. if ($resql) {
  96. if ($obj = $this->db->fetch_object($resql)) {
  97. $this->id = $obj->rowid;
  98. $this->amount = $obj->amount;
  99. $this->date_bordereau = $this->db->jdate($obj->date_bordereau);
  100. $this->account_id = $obj->fk_bank_account;
  101. $this->account_label = $obj->account_label;
  102. $this->author_id = $obj->fk_user_author;
  103. $this->nbcheque = $obj->nbcheque;
  104. $this->statut = $obj->statut;
  105. $this->ref_ext = $obj->ref_ext;
  106. $this->type = $obj->type;
  107. if ($this->statut == 0) {
  108. $this->ref = "(PROV".$this->id.")";
  109. } else {
  110. $this->ref = $obj->ref;
  111. }
  112. }
  113. $this->db->free($resql);
  114. return 1;
  115. } else {
  116. $this->error = $this->db->lasterror();
  117. return -1;
  118. }
  119. }
  120. /**
  121. * Create a receipt to send cheques
  122. *
  123. * @param User $user User making creation
  124. * @param int $account_id Bank account for cheque receipt
  125. * @param int $limit Limit ref of cheque to this
  126. * @param array $toRemise array with cheques to remise
  127. * @return int Return integer <0 if KO, >0 if OK
  128. */
  129. public function create($user, $account_id, $limit, $toRemise)
  130. {
  131. global $conf;
  132. $this->errno = 0;
  133. $this->id = 0;
  134. $now = dol_now();
  135. dol_syslog("RemiseCheque::Create start", LOG_DEBUG);
  136. // Clean parameters
  137. if (empty($this->type)) {
  138. $this->type = 'CHQ';
  139. }
  140. $this->db->begin();
  141. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bordereau_cheque (";
  142. $sql .= "datec";
  143. $sql .= ", date_bordereau";
  144. $sql .= ", fk_user_author";
  145. $sql .= ", fk_bank_account";
  146. $sql .= ", statut";
  147. $sql .= ", amount";
  148. $sql .= ", ref";
  149. $sql .= ", entity";
  150. $sql .= ", nbcheque";
  151. $sql .= ", ref_ext";
  152. $sql .= ", type";
  153. $sql .= ") VALUES (";
  154. $sql .= "'".$this->db->idate($now)."'";
  155. $sql .= ", '".$this->db->idate($now)."'";
  156. $sql .= ", ".((int) $user->id);
  157. $sql .= ", ".((int) $account_id);
  158. $sql .= ", 0";
  159. $sql .= ", 0";
  160. $sql .= ", 0";
  161. $sql .= ", ".((int) $conf->entity);
  162. $sql .= ", 0";
  163. $sql .= ", ''";
  164. $sql .= ", '".$this->db->escape($this->type)."'";
  165. $sql .= ")";
  166. $resql = $this->db->query($sql);
  167. if ($resql) {
  168. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bordereau_cheque");
  169. if ($this->id == 0) {
  170. $this->errno = -1024;
  171. dol_syslog("Remisecheque::Create Error read id ".$this->errno, LOG_ERR);
  172. }
  173. if ($this->id > 0 && $this->errno == 0) {
  174. $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque";
  175. $sql .= " SET ref = '(PROV".$this->id.")'";
  176. $sql .= " WHERE rowid=".((int) $this->id);
  177. $resql = $this->db->query($sql);
  178. if (!$resql) {
  179. $this->errno = -1025;
  180. dol_syslog("RemiseCheque::Create Error update ".$this->errno, LOG_ERR);
  181. }
  182. }
  183. $lines = array();
  184. if ($this->id > 0 && $this->errno == 0) {
  185. $sql = "SELECT b.rowid";
  186. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
  187. $sql .= " WHERE b.fk_type = '".$this->db->escape($this->type)."'";
  188. $sql .= " AND b.amount > 0";
  189. $sql .= " AND b.fk_bordereau = 0";
  190. $sql .= " AND b.fk_account = ".((int) $account_id);
  191. if ($limit) {
  192. $sql .= $this->db->plimit($limit);
  193. }
  194. dol_syslog("RemiseCheque::Create", LOG_DEBUG);
  195. $resql = $this->db->query($sql);
  196. if ($resql) {
  197. while ($row = $this->db->fetch_row($resql)) {
  198. array_push($lines, $row[0]);
  199. }
  200. $this->db->free($resql);
  201. } else {
  202. $this->errno = -1026;
  203. dol_syslog("RemiseCheque::Create Error ".$this->errno, LOG_ERR);
  204. }
  205. }
  206. if ($this->id > 0 && $this->errno == 0) {
  207. foreach ($lines as $lineid) {
  208. $checkremise = false;
  209. foreach ($toRemise as $linetoremise) {
  210. if ($linetoremise == $lineid) {
  211. $checkremise = true;
  212. }
  213. }
  214. if ($checkremise) {
  215. $sql = "UPDATE ".MAIN_DB_PREFIX."bank";
  216. $sql .= " SET fk_bordereau = ".((int) $this->id);
  217. $sql .= " WHERE rowid = ".((int) $lineid);
  218. $resql = $this->db->query($sql);
  219. if (!$resql) {
  220. $this->errno = -18;
  221. dol_syslog("RemiseCheque::Create Error update bank ".$this->errno, LOG_ERR);
  222. }
  223. }
  224. }
  225. }
  226. if ($this->id > 0 && $this->errno == 0) {
  227. if ($this->updateAmount() != 0) {
  228. $this->errno = -1027;
  229. dol_syslog("RemiseCheque::Create Error update amount ".$this->errno, LOG_ERR);
  230. }
  231. }
  232. } else {
  233. $this->errno = -1;
  234. $this->error = $this->db->lasterror();
  235. $this->errno = $this->db->lasterrno();
  236. }
  237. if (!$this->errno && (getDolGlobalString('MAIN_DISABLEDRAFTSTATUS') || getDolGlobalString('MAIN_DISABLEDRAFTSTATUS_CHEQUE'))) {
  238. $res = $this->validate($user);
  239. //if ($res < 0) $error++;
  240. }
  241. if (!$this->errno) {
  242. $this->db->commit();
  243. dol_syslog("RemiseCheque::Create end", LOG_DEBUG);
  244. return $this->id;
  245. } else {
  246. $this->db->rollback();
  247. dol_syslog("RemiseCheque::Create end", LOG_DEBUG);
  248. return $this->errno;
  249. }
  250. }
  251. /**
  252. * Delete deposit from database
  253. *
  254. * @param User $user User that delete
  255. * @return int
  256. */
  257. public function delete($user = null)
  258. {
  259. global $conf;
  260. $this->errno = 0;
  261. $this->db->begin();
  262. $sql = "DELETE FROM ".MAIN_DB_PREFIX."bordereau_cheque";
  263. $sql .= " WHERE rowid = ".((int) $this->id);
  264. $sql .= " AND entity = ".$conf->entity;
  265. $resql = $this->db->query($sql);
  266. if ($resql) {
  267. $num = $this->db->affected_rows($resql);
  268. if ($num != 1) {
  269. $this->errno = -2;
  270. dol_syslog("Remisecheque::Delete Erreur Lecture ID ($this->errno)");
  271. }
  272. if ($this->errno === 0) {
  273. $sql = "UPDATE ".MAIN_DB_PREFIX."bank";
  274. $sql .= " SET fk_bordereau = 0";
  275. $sql .= " WHERE fk_bordereau = ".((int) $this->id);
  276. $resql = $this->db->query($sql);
  277. if (!$resql) {
  278. $this->errno = -1028;
  279. dol_syslog("RemiseCheque::Delete ERREUR UPDATE ($this->errno)");
  280. }
  281. }
  282. }
  283. if ($this->errno === 0) {
  284. $this->db->commit();
  285. } else {
  286. $this->db->rollback();
  287. dol_syslog("RemiseCheque::Delete ROLLBACK ($this->errno)");
  288. }
  289. return $this->errno;
  290. }
  291. /**
  292. * Validate a receipt
  293. *
  294. * @param User $user User
  295. * @return int Return integer <0 if KO, >0 if OK
  296. */
  297. public function validate($user)
  298. {
  299. global $langs, $conf;
  300. $this->errno = 0;
  301. $this->db->begin();
  302. $numref = $this->getNextNumRef();
  303. if ($this->errno == 0 && $numref) {
  304. $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque";
  305. $sql .= " SET statut = 1, ref = '".$this->db->escape($numref)."'";
  306. $sql .= " WHERE rowid = ".((int) $this->id);
  307. $sql .= " AND entity = ".$conf->entity;
  308. $sql .= " AND statut = 0";
  309. dol_syslog("RemiseCheque::Validate", LOG_DEBUG);
  310. $resql = $this->db->query($sql);
  311. if ($resql) {
  312. $num = $this->db->affected_rows($resql);
  313. if ($num == 1) {
  314. $this->ref = $numref;
  315. $this->statut = 1;
  316. } else {
  317. $this->errno = -1029;
  318. dol_syslog("Remisecheque::Validate Error ".$this->errno, LOG_ERR);
  319. }
  320. } else {
  321. $this->errno = -1033;
  322. dol_syslog("Remisecheque::Validate Error ".$this->errno, LOG_ERR);
  323. }
  324. }
  325. // Commit/Rollback
  326. if ($this->errno == 0) {
  327. $this->db->commit();
  328. return 1;
  329. } else {
  330. $this->db->rollback();
  331. dol_syslog("RemiseCheque::Validate ".$this->errno, LOG_ERR);
  332. return $this->errno;
  333. }
  334. }
  335. /**
  336. * Return next reference of cheque receipts not already used (or last reference)
  337. * according to numbering module defined into constant FACTURE_ADDON
  338. *
  339. * @param string $mode 'next' for next value or 'last' for last value
  340. * @return string free ref or last ref
  341. */
  342. public function getNextNumRef($mode = 'next')
  343. {
  344. global $conf, $db, $langs, $mysoc;
  345. $langs->load("bills");
  346. // Clean parameters (if not defined or using deprecated value)
  347. if (!getDolGlobalString('CHEQUERECEIPTS_ADDON')) {
  348. $conf->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint';
  349. } elseif (getDolGlobalString('CHEQUERECEIPTS_ADDON') == 'thyme') {
  350. $conf->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_thyme';
  351. } elseif (getDolGlobalString('CHEQUERECEIPTS_ADDON') == 'mint') {
  352. $conf->global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint';
  353. }
  354. if (getDolGlobalString('CHEQUERECEIPTS_ADDON')) {
  355. $mybool = false;
  356. $file = getDolGlobalString('CHEQUERECEIPTS_ADDON') . ".php";
  357. $classname = $conf->global->CHEQUERECEIPTS_ADDON;
  358. // Include file with class
  359. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  360. foreach ($dirmodels as $reldir) {
  361. $dir = dol_buildpath($reldir."core/modules/cheque/");
  362. // Load file with numbering class (if found)
  363. if (is_file($dir.$file) && is_readable($dir.$file)) {
  364. $mybool |= include_once $dir.$file;
  365. }
  366. }
  367. // For compatibility
  368. if (!$mybool) {
  369. $file = getDolGlobalString('CHEQUERECEIPTS_ADDON') . ".php";
  370. $classname = "mod_chequereceipt_" . getDolGlobalString('CHEQUERECEIPTS_ADDON');
  371. $classname = preg_replace('/\-.*$/', '', $classname);
  372. // Include file with class
  373. foreach ($conf->file->dol_document_root as $dirroot) {
  374. $dir = $dirroot."/core/modules/cheque/";
  375. // Load file with numbering class (if found)
  376. if (is_file($dir.$file) && is_readable($dir.$file)) {
  377. $mybool |= include_once $dir.$file;
  378. }
  379. }
  380. }
  381. if (!$mybool) {
  382. dol_print_error('', "Failed to include file ".$file);
  383. return '';
  384. }
  385. $obj = new $classname();
  386. $numref = "";
  387. $numref = $obj->getNextValue($mysoc, $this);
  388. /**
  389. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  390. * set up mask.
  391. */
  392. if ($mode != 'last' && !$numref) {
  393. dol_print_error($db, "ChequeReceipts::getNextNumRef ".$obj->error);
  394. return "";
  395. }
  396. return $numref;
  397. } else {
  398. $langs->load("errors");
  399. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Bank"));
  400. return "";
  401. }
  402. }
  403. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  404. /**
  405. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  406. *
  407. * @param User $user Objet user
  408. * @param string $type Type of payment mode deposit ('CHQ', 'TRA', ...)
  409. * @return WorkboardResponse|int Return integer <0 if KO, WorkboardResponse if OK
  410. */
  411. public function load_board($user, $type = 'CHQ')
  412. {
  413. // phpcs:enable
  414. global $conf, $langs;
  415. if ($user->socid) {
  416. return -1; // protection pour eviter appel par utilisateur externe
  417. }
  418. $sql = "SELECT b.rowid, b.datev as datefin";
  419. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
  420. $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
  421. $sql .= " WHERE b.fk_account = ba.rowid";
  422. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  423. $sql .= " AND b.fk_type = '".$this->db->escape($type)."'";
  424. $sql .= " AND b.fk_bordereau = 0";
  425. $sql .= " AND b.amount > 0";
  426. $resql = $this->db->query($sql);
  427. if ($resql) {
  428. $langs->load("banks");
  429. $now = dol_now();
  430. $response = new WorkboardResponse();
  431. $response->warning_delay = $conf->bank->cheque->warning_delay / 60 / 60 / 24;
  432. $response->label = $langs->trans("BankChecksToReceipt");
  433. $response->labelShort = $langs->trans("BankChecksToReceiptShort");
  434. $response->url = DOL_URL_ROOT.'/compta/paiement/cheque/index.php?leftmenu=checks&amp;mainmenu=bank';
  435. $response->img = img_object('', "payment");
  436. while ($obj = $this->db->fetch_object($resql)) {
  437. $response->nbtodo++;
  438. if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->cheque->warning_delay)) {
  439. $response->nbtodolate++;
  440. }
  441. }
  442. return $response;
  443. } else {
  444. dol_print_error($this->db);
  445. $this->error = $this->db->error();
  446. return -1;
  447. }
  448. }
  449. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  450. /**
  451. * Charge indicateurs this->nb de tableau de bord
  452. *
  453. * @param string $type Type of payment mode deposit ('CHQ', 'TRA', ...)
  454. * @return int Return integer <0 if ko, >0 if ok
  455. */
  456. public function load_state_board($type = 'CHQ')
  457. {
  458. // phpcs:enable
  459. global $user;
  460. if ($user->socid) {
  461. return -1; // protection pour eviter appel par utilisateur externe
  462. }
  463. $sql = "SELECT count(b.rowid) as nb";
  464. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
  465. $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
  466. $sql .= " WHERE b.fk_account = ba.rowid";
  467. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  468. $sql .= " AND b.fk_type = '".$this->db->escape($type)."'";
  469. $sql .= " AND b.amount > 0";
  470. $resql = $this->db->query($sql);
  471. if ($resql) {
  472. while ($obj = $this->db->fetch_object($resql)) {
  473. $this->nb["cheques"] = $obj->nb;
  474. }
  475. $this->db->free($resql);
  476. return 1;
  477. } else {
  478. dol_print_error($this->db);
  479. $this->error = $this->db->error();
  480. return -1;
  481. }
  482. }
  483. /**
  484. * Build document
  485. *
  486. * @param string $model Model name
  487. * @param Translate $outputlangs Object langs
  488. * @return int Return integer <0 if KO, >0 if OK
  489. */
  490. public function generatePdf($model, $outputlangs)
  491. {
  492. global $langs, $conf;
  493. if (empty($model)) {
  494. $model = 'blochet';
  495. }
  496. dol_syslog("RemiseCheque::generatePdf model=".$model." id=".$this->id, LOG_DEBUG);
  497. $dir = DOL_DOCUMENT_ROOT."/core/modules/cheque/doc/";
  498. // Charge le modele
  499. $file = "pdf_".$model.".class.php";
  500. if (file_exists($dir.$file)) {
  501. include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  502. include_once $dir.$file;
  503. $classname = 'BordereauCheque'.ucfirst($model);
  504. $docmodel = new $classname($this->db);
  505. $sql = "SELECT b.banque, b.emetteur, b.amount, b.num_chq";
  506. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b";
  507. $sql .= ", ".MAIN_DB_PREFIX."bank_account as ba";
  508. $sql .= ", ".MAIN_DB_PREFIX."bordereau_cheque as bc";
  509. $sql .= " WHERE b.fk_account = ba.rowid";
  510. $sql .= " AND b.fk_bordereau = bc.rowid";
  511. $sql .= " AND bc.rowid = ".((int) $this->id);
  512. $sql .= " AND bc.entity = ".$conf->entity;
  513. $sql .= " ORDER BY b.dateo ASC, b.rowid ASC";
  514. dol_syslog("RemiseCheque::generatePdf", LOG_DEBUG);
  515. $result = $this->db->query($sql);
  516. if ($result) {
  517. $i = 0;
  518. while ($objp = $this->db->fetch_object($result)) {
  519. $docmodel->lines[$i] = new stdClass();
  520. $docmodel->lines[$i]->bank_chq = $objp->banque;
  521. $docmodel->lines[$i]->emetteur_chq = $objp->emetteur;
  522. $docmodel->lines[$i]->amount_chq = $objp->amount;
  523. $docmodel->lines[$i]->num_chq = $objp->num_chq;
  524. $i++;
  525. }
  526. }
  527. $docmodel->nbcheque = $this->nbcheque;
  528. $docmodel->ref = $this->ref;
  529. $docmodel->amount = $this->amount;
  530. $docmodel->date = $this->date_bordereau;
  531. $account = new Account($this->db);
  532. $account->fetch($this->account_id);
  533. $docmodel->account = &$account;
  534. // We save charset_output to restore it because write_file can change it if needed for
  535. // output format that does not support UTF8.
  536. $sav_charset_output = $outputlangs->charset_output;
  537. $result = $docmodel->write_file($this, $conf->bank->dir_output.'/checkdeposits', $this->ref, $outputlangs);
  538. if ($result > 0) {
  539. //$outputlangs->charset_output=$sav_charset_output;
  540. return 1;
  541. } else {
  542. //$outputlangs->charset_output=$sav_charset_output;
  543. dol_syslog("Error");
  544. dol_print_error($this->db, $docmodel->error);
  545. return 0;
  546. }
  547. } else {
  548. $this->error = $langs->trans("ErrorFileDoesNotExists", $dir.$file);
  549. return -1;
  550. }
  551. }
  552. /**
  553. * Mets a jour le montant total
  554. *
  555. * @return int 0 en cas de succes
  556. */
  557. public function updateAmount()
  558. {
  559. global $conf;
  560. $this->errno = 0;
  561. $this->db->begin();
  562. $total = 0;
  563. $nb = 0;
  564. $sql = "SELECT amount ";
  565. $sql .= " FROM ".MAIN_DB_PREFIX."bank";
  566. $sql .= " WHERE fk_bordereau = ".((int) $this->id);
  567. $resql = $this->db->query($sql);
  568. if ($resql) {
  569. while ($row = $this->db->fetch_row($resql)) {
  570. $total += $row[0];
  571. $nb++;
  572. }
  573. $this->db->free($resql);
  574. $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque";
  575. $sql .= " SET amount = ".price2num($total);
  576. $sql .= ", nbcheque = ".((int) $nb);
  577. $sql .= " WHERE rowid = ".((int) $this->id);
  578. $sql .= " AND entity = ".((int) $conf->entity);
  579. $resql = $this->db->query($sql);
  580. if (!$resql) {
  581. $this->errno = -1030;
  582. dol_syslog("RemiseCheque::updateAmount ERREUR UPDATE ($this->errno)");
  583. }
  584. } else {
  585. $this->errno = -1031;
  586. dol_syslog("RemiseCheque::updateAmount ERREUR SELECT ($this->errno)");
  587. }
  588. if ($this->errno === 0) {
  589. $this->db->commit();
  590. } else {
  591. $this->db->rollback();
  592. dol_syslog("RemiseCheque::updateAmount ROLLBACK ($this->errno)");
  593. }
  594. return $this->errno;
  595. }
  596. /**
  597. * Insere la remise en base
  598. *
  599. * @param int $account_id Compte bancaire concerne
  600. * @return int
  601. */
  602. public function removeCheck($account_id)
  603. {
  604. $this->errno = 0;
  605. if ($this->id > 0) {
  606. $sql = "UPDATE ".MAIN_DB_PREFIX."bank";
  607. $sql .= " SET fk_bordereau = 0";
  608. $sql .= " WHERE rowid = ".((int) $account_id);
  609. $sql .= " AND fk_bordereau = ".((int) $this->id);
  610. $resql = $this->db->query($sql);
  611. if ($resql) {
  612. $this->updateAmount();
  613. } else {
  614. $this->errno = -1032;
  615. dol_syslog("RemiseCheque::removeCheck ERREUR UPDATE ($this->errno)");
  616. }
  617. }
  618. return 0;
  619. }
  620. /**
  621. * Check return management
  622. * Reopen linked invoices and create a new negative payment.
  623. *
  624. * @param int $bank_id Id of bank transaction line concerned
  625. * @param integer $rejection_date Date to use on the negative payment
  626. * @return int Id of negative payment line created
  627. */
  628. public function rejectCheck($bank_id, $rejection_date)
  629. {
  630. global $db, $user;
  631. $payment = new Paiement($db);
  632. $payment->fetch(0, 0, $bank_id);
  633. $bankline = new AccountLine($db);
  634. $bankline->fetch($bank_id);
  635. /* Reconciliation is allowed because when check is returned, a new line is created onto bank transaction log.
  636. if ($bankline->rappro)
  637. {
  638. $this->error='ActionRefusedLineAlreadyConciliated';
  639. return -1;
  640. }*/
  641. $this->db->begin();
  642. // Not reconciled, we can delete it
  643. //$bankline->delete($user); // We delete
  644. $bankaccount = $payment->fk_account;
  645. // Get invoices list to reopen them
  646. $sql = 'SELECT pf.fk_facture, pf.amount';
  647. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
  648. $sql .= ' WHERE pf.fk_paiement = '.((int) $payment->id);
  649. $resql = $this->db->query($sql);
  650. if ($resql) {
  651. $rejectedPayment = new Paiement($this->db);
  652. $rejectedPayment->amounts = array();
  653. $rejectedPayment->datepaye = $rejection_date;
  654. $rejectedPayment->paiementid = dol_getIdFromCode($this->db, 'CHQ', 'c_paiement', 'code', 'id', 1);
  655. $rejectedPayment->num_payment = $payment->num_payment;
  656. while ($obj = $this->db->fetch_object($resql)) {
  657. $invoice = new Facture($this->db);
  658. $invoice->fetch($obj->fk_facture);
  659. $invoice->setUnpaid($user);
  660. $rejectedPayment->amounts[$obj->fk_facture] = price2num($obj->amount) * -1;
  661. }
  662. $result = $rejectedPayment->create($user);
  663. if ($result > 0) {
  664. // We created a negative payment, we also add the line as bank transaction
  665. $result = $rejectedPayment->addPaymentToBank($user, 'payment', '(CheckRejected)', $bankaccount, '', '');
  666. if ($result > 0) {
  667. $result = $payment->reject();
  668. if ($result > 0) {
  669. $this->db->commit();
  670. return $rejectedPayment->id;
  671. } else {
  672. $this->db->rollback();
  673. return -1;
  674. }
  675. } else {
  676. $this->error = $rejectedPayment->error;
  677. $this->errors = $rejectedPayment->errors;
  678. $this->db->rollback();
  679. return -1;
  680. }
  681. } else {
  682. $this->error = $rejectedPayment->error;
  683. $this->errors = $rejectedPayment->errors;
  684. $this->db->rollback();
  685. return -1;
  686. }
  687. } else {
  688. $this->error = $this->db->lasterror();
  689. $this->db->rollback();
  690. return -1;
  691. }
  692. }
  693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  694. /**
  695. * Set the creation date
  696. *
  697. * @param User $user Object user
  698. * @param int $date Date creation
  699. * @return int Return integer <0 if KO, >0 if OK
  700. */
  701. public function set_date($user, $date)
  702. {
  703. // phpcs:enable
  704. if ($user->hasRight('banque', 'cheque')) {
  705. $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque";
  706. $sql .= " SET date_bordereau = ".($date ? "'".$this->db->idate($date)."'" : 'null');
  707. $sql .= " WHERE rowid = ".((int) $this->id);
  708. dol_syslog("RemiseCheque::set_date", LOG_DEBUG);
  709. $resql = $this->db->query($sql);
  710. if ($resql) {
  711. $this->date_bordereau = $date;
  712. return 1;
  713. } else {
  714. $this->error = $this->db->error();
  715. return -1;
  716. }
  717. } else {
  718. return -2;
  719. }
  720. }
  721. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  722. /**
  723. * Set the ref of bordereau
  724. *
  725. * @param User $user Object user
  726. * @param int $ref ref of bordereau
  727. * @return int Return integer <0 if KO, >0 if OK
  728. */
  729. public function set_number($user, $ref)
  730. {
  731. // phpcs:enable
  732. if ($user->hasRight('banque', 'cheque')) {
  733. $sql = "UPDATE ".MAIN_DB_PREFIX."bordereau_cheque";
  734. $sql .= " SET ref = '".$this->db->escape($ref)."'";
  735. $sql .= " WHERE rowid = ".((int) $this->id);
  736. dol_syslog("RemiseCheque::set_number", LOG_DEBUG);
  737. $resql = $this->db->query($sql);
  738. if ($resql) {
  739. return 1;
  740. } else {
  741. $this->error = $this->db->error();
  742. return -1;
  743. }
  744. } else {
  745. return -2;
  746. }
  747. }
  748. /**
  749. * Initialise an instance with random values.
  750. * Used to build previews or test instances.
  751. * id must be 0 if object instance is a specimen.
  752. *
  753. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  754. * @return void
  755. */
  756. public function initAsSpecimen($option = '')
  757. {
  758. global $user, $langs, $conf;
  759. $now = dol_now();
  760. $arraynow = dol_getdate($now);
  761. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  762. // Initialize parameters
  763. $this->id = 0;
  764. $this->ref = 'SPECIMEN';
  765. $this->specimen = 1;
  766. $this->date_bordereau = $nownotime;
  767. }
  768. /**
  769. * Return clicable name (with picto eventually)
  770. *
  771. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  772. * @param string $option Sur quoi pointe le lien
  773. * @param int $notooltip 1=Disable tooltip
  774. * @param string $morecss Add more css on link
  775. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  776. * @return string Chaine avec URL
  777. */
  778. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  779. {
  780. global $conf, $langs;
  781. $result = '';
  782. $label = '<u>'.$langs->trans("ShowCheckReceipt").'</u>';
  783. $label .= '<br>';
  784. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  785. $url = DOL_URL_ROOT.'/compta/paiement/cheque/card.php?id='.$this->id;
  786. if ($option != 'nolink') {
  787. // Add param to save lastsearch_values or not
  788. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  789. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  790. $add_save_lastsearch_values = 1;
  791. }
  792. if ($add_save_lastsearch_values) {
  793. $url .= '&save_lastsearch_values=1';
  794. }
  795. }
  796. $linkclose = '';
  797. if (empty($notooltip)) {
  798. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  799. $label = $langs->trans("ShowCheckReceipt");
  800. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  801. }
  802. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  803. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  804. } else {
  805. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  806. }
  807. $linkstart = '<a href="'.$url.'"';
  808. $linkstart .= $linkclose.'>';
  809. $linkend = '</a>';
  810. $result .= $linkstart;
  811. if ($withpicto) {
  812. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  813. }
  814. if ($withpicto != 2) {
  815. $result .= $this->ref;
  816. }
  817. $result .= $linkend;
  818. return $result;
  819. }
  820. /**
  821. * Return the label of the status
  822. *
  823. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  824. * @return string Label of status
  825. */
  826. public function getLibStatut($mode = 0)
  827. {
  828. return $this->LibStatut($this->statut, $mode);
  829. }
  830. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  831. /**
  832. * Return the label of a given status
  833. *
  834. * @param int $status Id status
  835. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  836. * @return string Label of status
  837. */
  838. public function LibStatut($status, $mode = 0)
  839. {
  840. // phpcs:enable
  841. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  842. global $langs;
  843. $langs->load('compta');
  844. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ToValidate');
  845. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
  846. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ToValidate');
  847. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
  848. }
  849. $statusType = 'status'.$status;
  850. if ($status == self::STATUS_VALIDATED) {
  851. $statusType = 'status4';
  852. }
  853. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  854. }
  855. /**
  856. * Return clicable link of object (with eventually picto)
  857. *
  858. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  859. * @param array $arraydata Array of data
  860. * @return string HTML Code for Kanban thumb.
  861. */
  862. public function getKanbanView($option = '', $arraydata = null)
  863. {
  864. global $langs;
  865. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  866. $return = '<div class="box-flex-item box-flex-grow-zero">';
  867. $return .= '<div class="info-box info-box-sm">';
  868. $return .= '<span class="info-box-icon bg-infobox-action">';
  869. $return .= img_picto('', $this->picto);
  870. $return .= '</span>';
  871. $return .= '<div class="info-box-content">';
  872. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  873. if ($selected >= 0) {
  874. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  875. }
  876. if (property_exists($this, 'date_bordereau')) {
  877. $return .= '<br><span class="opacitymedium">'.$langs->trans("DateCreation").'</span> : <span class="info-box-label">'.dol_print_date($this->db->jdate($this->date_bordereau), 'day').'</span>';
  878. }
  879. if (property_exists($this, 'nbcheque')) {
  880. $return .= '<br><span class="opacitymedium">'.$langs->trans("Cheque", '', '', '', '', 5).'</span> : <span class="info-box-label">'.$this->nbcheque.'</span>';
  881. }
  882. if (property_exists($this, 'account_id')) {
  883. $return .= ' | <span class="info-box-label">'.$this->account_id.'</span>';
  884. }
  885. if (method_exists($this, 'LibStatut')) {
  886. $return .= '<br><div style="display:inline-block" class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  887. }
  888. if (property_exists($this, 'amount')) {
  889. $return .= ' | <div style="display:inline-block"><span class="opacitymedium">'.$langs->trans("Amount").'</span> : <span class="amount">'.price($this->amount).'</div>';
  890. }
  891. $return .= '</div>';
  892. $return .= '</div>';
  893. $return .= '</div>';
  894. return $return;
  895. }
  896. }