bonprelevement.class.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405
  1. <?php
  2. /* Copyright (C) 2004-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  4. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  5. * Copyright (C) 2010-2014 Laurent Destailleur <eldy@users.sourceforge.net>
  6. * Copyright (C) 2014-2016 Ferran Marcet <fmarcet@2byte.es>
  7. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  8. * Copyright (C) 2019 JC Prieto <jcprieto@virtual20.com><prietojc@gmail.com>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  22. */
  23. /**
  24. * \file htdocs/compta/prelevement/class/bonprelevement.class.php
  25. * \ingroup prelevement
  26. * \brief File of withdrawal receipts class
  27. */
  28. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  34. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  35. /**
  36. * Class to manage withdrawal receipts
  37. */
  38. class BonPrelevement extends CommonObject
  39. {
  40. /**
  41. * @var string ID to identify managed object
  42. */
  43. public $element = 'widthdraw';
  44. /**
  45. * @var string Name of table without prefix where object is stored
  46. */
  47. public $table_element = 'prelevement_bons';
  48. /**
  49. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  50. */
  51. public $picto = 'payment';
  52. public $date_echeance;
  53. public $raison_sociale;
  54. public $reference_remise;
  55. public $emetteur_code_guichet;
  56. public $emetteur_numero_compte;
  57. public $emetteur_code_banque;
  58. public $emetteur_number_key;
  59. public $sepa_xml_pti_in_ctti;
  60. public $emetteur_iban;
  61. public $emetteur_bic;
  62. public $emetteur_ics;
  63. public $date_trans;
  64. public $user_trans;
  65. public $total;
  66. public $fetched;
  67. public $statut; // 0-Wait, 1-Trans, 2-Done
  68. public $labelStatus = array();
  69. public $invoice_in_error = array();
  70. public $thirdparty_in_error = array();
  71. const STATUS_DRAFT = 0;
  72. const STATUS_TRANSFERED = 1;
  73. const STATUS_CREDITED = 2; // STATUS_CREDITED and STATUS_DEBITED is same. Difference is in ->type
  74. const STATUS_DEBITED = 2; // STATUS_CREDITED and STATUS_DEBITED is same. Difference is in ->type
  75. /**
  76. * Constructor
  77. *
  78. * @param DoliDB $db Database handler
  79. */
  80. public function __construct($db)
  81. {
  82. global $conf, $langs;
  83. $this->db = $db;
  84. $this->filename = '';
  85. $this->date_echeance = dol_now();
  86. $this->raison_sociale = "";
  87. $this->reference_remise = "";
  88. $this->emetteur_code_guichet = "";
  89. $this->emetteur_numero_compte = "";
  90. $this->emetteur_code_banque = "";
  91. $this->emetteur_number_key = "";
  92. $this->sepa_xml_pti_in_ctti = false;
  93. $this->emetteur_iban = "";
  94. $this->emetteur_bic = "";
  95. $this->emetteur_ics = "";
  96. $this->factures = array();
  97. $this->methodes_trans = array();
  98. $this->methodes_trans[0] = "Internet";
  99. $this->fetched = 0;
  100. }
  101. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  102. /**
  103. * Add invoice to withdrawal
  104. *
  105. * @param int $invoice_id id invoice to add
  106. * @param int $client_id id invoice customer
  107. * @param string $client_nom customer name
  108. * @param int $amount amount of invoice
  109. * @param string $code_banque code of bank withdrawal
  110. * @param string $code_guichet code of bank's office
  111. * @param string $number bank account number
  112. * @param string $number_key number key of account number
  113. * @param string $type 'debit-order' or 'bank-transfer'
  114. * @return int >0 if OK, <0 if KO
  115. */
  116. public function AddFacture($invoice_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $type = 'debit-order')
  117. {
  118. // phpcs:enable
  119. $result = 0;
  120. $line_id = 0;
  121. // Add lines
  122. $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
  123. if ($result == 0) {
  124. if ($line_id > 0) {
  125. $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
  126. if ($type != 'bank-transfer') {
  127. $sql .= "fk_facture";
  128. } else {
  129. $sql .= "fk_facture_fourn";
  130. }
  131. $sql .= ",fk_prelevement_lignes";
  132. $sql .= ") VALUES (";
  133. $sql .= ((int) $invoice_id);
  134. $sql .= ", ".((int) $line_id);
  135. $sql .= ")";
  136. if ($this->db->query($sql)) {
  137. $result = 0;
  138. } else {
  139. $result = -1;
  140. $this->errors[] = get_class($this)."::AddFacture ".$this->db->lasterror;
  141. dol_syslog(get_class($this)."::AddFacture Error $result");
  142. }
  143. } else {
  144. $result = -2;
  145. $this->errors[] = get_class($this)."::AddFacture linedid Empty";
  146. dol_syslog(get_class($this)."::AddFacture Error $result");
  147. }
  148. } else {
  149. $result = -3;
  150. dol_syslog(get_class($this)."::AddFacture Error $result");
  151. }
  152. return $result;
  153. }
  154. /**
  155. * Add line to withdrawal
  156. *
  157. * @param int $line_id id line to add
  158. * @param int $client_id id invoice customer
  159. * @param string $client_nom customer name
  160. * @param int $amount amount of invoice
  161. * @param string $code_banque code of bank withdrawal
  162. * @param string $code_guichet code of bank's office
  163. * @param string $number bank account number
  164. * @param string $number_key number key of account number
  165. * @return int >0 if OK, <0 if KO
  166. */
  167. public function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
  168. {
  169. $result = -1;
  170. $concat = 0;
  171. if ($concat == 1) {
  172. /*
  173. * We aggregate the lines
  174. */
  175. $sql = "SELECT rowid";
  176. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_lignes";
  177. $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id);
  178. $sql .= " AND fk_soc =".((int) $client_id);
  179. $sql .= " AND code_banque = '".$this->db->escape($code_banque)."'";
  180. $sql .= " AND code_guichet = '".$this->db->escape($code_guichet)."'";
  181. $sql .= " AND number = '".$this->db->escape($number)."'";
  182. $resql = $this->db->query($sql);
  183. if ($resql) {
  184. $num = $this->db->num_rows($resql);
  185. } else {
  186. $result = -1;
  187. }
  188. } else {
  189. /*
  190. * No aggregate
  191. */
  192. $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_lignes (";
  193. $sql .= "fk_prelevement_bons";
  194. $sql .= ", fk_soc";
  195. $sql .= ", client_nom";
  196. $sql .= ", amount";
  197. $sql .= ", code_banque";
  198. $sql .= ", code_guichet";
  199. $sql .= ", number";
  200. $sql .= ", cle_rib";
  201. $sql .= ") VALUES (";
  202. $sql .= $this->id;
  203. $sql .= ", ".((int) $client_id);
  204. $sql .= ", '".$this->db->escape($client_nom)."'";
  205. $sql .= ", ".((float) price2num($amount));
  206. $sql .= ", '".$this->db->escape($code_banque)."'";
  207. $sql .= ", '".$this->db->escape($code_guichet)."'";
  208. $sql .= ", '".$this->db->escape($number)."'";
  209. $sql .= ", '".$this->db->escape($number_key)."'";
  210. $sql .= ")";
  211. if ($this->db->query($sql)) {
  212. $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes");
  213. $result = 0;
  214. } else {
  215. $this->errors[] = get_class($this)."::addline Error -2 ".$this->db->lasterror;
  216. dol_syslog(get_class($this)."::addline Error -2");
  217. $result = -2;
  218. }
  219. }
  220. return $result;
  221. }
  222. /**
  223. * Return error string
  224. *
  225. * @param int $error Id of error
  226. * @return string Error string
  227. */
  228. public function getErrorString($error)
  229. {
  230. global $langs;
  231. $errors = array();
  232. $errors[1027] = $langs->trans("DateInvalid");
  233. return $errors[abs($error)];
  234. }
  235. /**
  236. * Get object and lines from database
  237. *
  238. * @param int $rowid Id of object to load
  239. * @param string $ref Ref of direct debit
  240. * @return int >0 if OK, <0 if KO
  241. */
  242. public function fetch($rowid, $ref = '')
  243. {
  244. global $conf;
  245. $sql = "SELECT p.rowid, p.ref, p.amount, p.note";
  246. $sql .= ", p.datec as dc";
  247. $sql .= ", p.date_trans as date_trans";
  248. $sql .= ", p.method_trans, p.fk_user_trans";
  249. $sql .= ", p.date_credit as date_credit";
  250. $sql .= ", p.fk_user_credit";
  251. $sql .= ", p.type";
  252. $sql .= ", p.statut as status";
  253. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
  254. $sql .= " WHERE p.entity IN (".getEntity('invoice').")";
  255. if ($rowid > 0) {
  256. $sql .= " AND p.rowid = ".((int) $rowid);
  257. } else {
  258. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  259. }
  260. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  261. $result = $this->db->query($sql);
  262. if ($result) {
  263. if ($this->db->num_rows($result)) {
  264. $obj = $this->db->fetch_object($result);
  265. $this->id = $obj->rowid;
  266. $this->ref = $obj->ref;
  267. $this->amount = $obj->amount;
  268. $this->note = $obj->note;
  269. $this->datec = $this->db->jdate($obj->dc);
  270. $this->date_trans = $this->db->jdate($obj->date_trans);
  271. $this->method_trans = $obj->method_trans;
  272. $this->user_trans = $obj->fk_user_trans;
  273. $this->date_credit = $this->db->jdate($obj->date_credit);
  274. $this->user_credit = $obj->fk_user_credit;
  275. $this->type = $obj->type;
  276. $this->status = $obj->status;
  277. $this->statut = $obj->status; // For backward compatibility
  278. $this->fetched = 1;
  279. return 1;
  280. } else {
  281. dol_syslog(get_class($this)."::Fetch Erreur aucune ligne retournee");
  282. return -1;
  283. }
  284. } else {
  285. return -2;
  286. }
  287. }
  288. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  289. /**
  290. * Set direct debit or credit transfer order to "paid" status.
  291. *
  292. * @param User $user Id of user
  293. * @param int $date date of action
  294. * @return int >0 if OK, <0 if KO
  295. */
  296. public function set_infocredit($user, $date)
  297. {
  298. // phpcs:enable
  299. global $conf, $langs;
  300. $error = 0;
  301. if ($this->fetched == 1) {
  302. if ($date < $this->date_trans) {
  303. $this->error = 'DateOfMovementLowerThanDateOfFileTransmission';
  304. dol_syslog("bon-prelevment::set_infocredit 1027 ".$this->error);
  305. return -1027;
  306. }
  307. $this->db->begin();
  308. $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
  309. $sql .= " SET fk_user_credit = ".$user->id;
  310. $sql .= ", statut = ".self::STATUS_CREDITED;
  311. $sql .= ", date_credit = '".$this->db->idate($date)."'";
  312. $sql .= " WHERE rowid=".((int) $this->id);
  313. $sql .= " AND entity = ".((int) $conf->entity);
  314. $sql .= " AND statut = ".self::STATUS_TRANSFERED;
  315. $resql = $this->db->query($sql);
  316. if ($resql) {
  317. $langs->load('withdrawals');
  318. $subject = $langs->trans("InfoCreditSubject", $this->ref);
  319. $message = $langs->trans("InfoCreditMessage", $this->ref, dol_print_date($date, 'dayhour'));
  320. //Add payment of withdrawal into bank
  321. $bankaccount = ($this->type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT);
  322. $facs = array();
  323. $amounts = array();
  324. $amountsperthirdparty = array();
  325. $facs = $this->getListInvoices(1);
  326. // Loop on each invoice. $facs=array(0=>id, 1=>amount requested)
  327. $num = count($facs);
  328. for ($i = 0; $i < $num; $i++) {
  329. if ($this->type == 'bank-transfer') {
  330. $fac = new FactureFournisseur($this->db);
  331. } else {
  332. $fac = new Facture($this->db);
  333. }
  334. $result = $fac->fetch($facs[$i][0]);
  335. $amounts[$fac->id] = $facs[$i][1];
  336. $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1];
  337. $totalpaye = $fac->getSommePaiement();
  338. $totalcreditnotes = $fac->getSumCreditNotesUsed();
  339. $totaldeposits = $fac->getSumDepositsUsed();
  340. $alreadypayed = $totalpaye + $totalcreditnotes + $totaldeposits;
  341. // @TODO Move this after creation of payment
  342. if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) {
  343. $result = $fac->setPaid($user);
  344. if ($result < 0) {
  345. $this->error = $fac->error;
  346. $this->errors = $fac->errors;
  347. }
  348. }
  349. }
  350. //var_dump($amountsperthirdparty);exit;
  351. // Make one payment per customer
  352. foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) {
  353. if ($this->type == 'bank-transfer') {
  354. $paiement = new PaiementFourn($this->db);
  355. } else {
  356. $paiement = new Paiement($this->db);
  357. }
  358. $paiement->datepaye = $date;
  359. $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice
  360. if ($this->type == 'bank-transfer') {
  361. $paiement->paiementid = 2;
  362. $paiement->paiementcode = 'VIR';
  363. } else {
  364. $paiement->paiementid = 3;
  365. $paiement->paiementcode = 'PRE';
  366. }
  367. $paiement->num_payment = $this->ref; // Set ref of direct debit note
  368. $paiement->id_prelevement = $this->id;
  369. $paiement_id = $paiement->create($user); // This use ->paiementid, that is ID of payment mode
  370. if ($paiement_id < 0) {
  371. $error++;
  372. $this->error = $paiement->error;
  373. $this->errors = $paiement->errors;
  374. dol_syslog(get_class($this)."::set_infocredit AddPayment Error ".$this->error);
  375. } else {
  376. if ($this->type == 'bank-transfer') {
  377. $modeforaddpayment = 'payment_supplier';
  378. } else {
  379. $modeforaddpayment = 'payment';
  380. }
  381. $result = $paiement->addPaymentToBank($user, $modeforaddpayment, '(WithdrawalPayment)', $bankaccount, '', '');
  382. if ($result < 0) {
  383. $error++;
  384. $this->error = $paiement->error;
  385. $this->errors = $paiement->errors;
  386. dol_syslog(get_class($this)."::set_infocredit AddPaymentToBank Error ".$this->error);
  387. }
  388. }
  389. //var_dump($paiement->amounts);
  390. //var_dump($thirdpartyid);
  391. //var_dump($cursoramounts);
  392. }
  393. // Update withdrawal line
  394. // TODO: Translate to ligneprelevement.class.php
  395. if (!$error) {
  396. $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
  397. $sql .= " SET statut = 2";
  398. $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id);
  399. if (!$this->db->query($sql)) {
  400. dol_syslog(get_class($this)."::set_infocredit Update lines Error");
  401. $error++;
  402. }
  403. }
  404. } else {
  405. $this->error = $this->db->lasterror();
  406. dol_syslog(get_class($this)."::set_infocredit Update Bons Error");
  407. $error++;
  408. }
  409. /*
  410. * End of procedure
  411. */
  412. if ($error == 0) {
  413. $this->date_credit = $date;
  414. $this->statut = self::STATUS_CREDITED;
  415. $this->db->commit();
  416. return 0;
  417. } else {
  418. $this->db->rollback();
  419. return -1;
  420. }
  421. } else {
  422. return -1026;
  423. }
  424. }
  425. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  426. /**
  427. * Set withdrawal to transmited status
  428. *
  429. * @param User $user id of user
  430. * @param int $date date of action
  431. * @param string $method method of transmision to bank
  432. * @return int >0 if OK, <0 if KO
  433. */
  434. public function set_infotrans($user, $date, $method)
  435. {
  436. // phpcs:enable
  437. global $conf, $langs;
  438. $error = 0;
  439. dol_syslog(get_class($this)."::set_infotrans Start", LOG_INFO);
  440. if ($this->db->begin()) {
  441. $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons ";
  442. $sql .= " SET fk_user_trans = ".$user->id;
  443. $sql .= " , date_trans = '".$this->db->idate($date)."'";
  444. $sql .= " , method_trans = ".((int) $method);
  445. $sql .= " , statut = ".self::STATUS_TRANSFERED;
  446. $sql .= " WHERE rowid = ".((int) $this->id);
  447. $sql .= " AND entity = ".((int) $conf->entity);
  448. $sql .= " AND statut = 0";
  449. if ($this->db->query($sql)) {
  450. $this->method_trans = $method;
  451. $langs->load('withdrawals');
  452. $subject = $langs->trans("InfoTransSubject", $this->ref);
  453. $message = $langs->trans("InfoTransMessage", $this->ref, dolGetFirstLastname($user->firstname, $user->lastname));
  454. $message .= $langs->trans("InfoTransData", price($this->amount), $this->methodes_trans[$this->method_trans], dol_print_date($date, 'day'));
  455. // TODO Call trigger to create a notification using notification module
  456. } else {
  457. $error++;
  458. }
  459. if ($error == 0) {
  460. $this->date_trans = $date;
  461. $this->statut = 1;
  462. $this->user_trans = $user->id;
  463. $this->db->commit();
  464. return 0;
  465. } else {
  466. $this->db->rollback();
  467. dol_syslog(get_class($this)."::set_infotrans ROLLBACK", LOG_ERR);
  468. return -1;
  469. }
  470. } else {
  471. dol_syslog(get_class($this)."::set_infotrans Ouverture transaction SQL impossible", LOG_CRIT);
  472. return -2;
  473. }
  474. }
  475. /**
  476. * Get invoice list
  477. *
  478. * @param int $amounts If you want to get the amount of the order for each invoice
  479. * @return array Id of invoices
  480. */
  481. private function getListInvoices($amounts = 0)
  482. {
  483. global $conf;
  484. $arr = array();
  485. /*
  486. * Returns all invoices presented within same order
  487. */
  488. $sql = "SELECT ";
  489. if ($this->type == 'bank-transfer') {
  490. $sql .= " pf.fk_facture_fourn";
  491. } else {
  492. $sql .= " pf.fk_facture";
  493. }
  494. if ($amounts) {
  495. $sql .= ", SUM(pl.amount)";
  496. }
  497. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
  498. $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl";
  499. $sql .= " , ".MAIN_DB_PREFIX."prelevement_facture as pf";
  500. $sql .= " WHERE pf.fk_prelevement_lignes = pl.rowid";
  501. $sql .= " AND pl.fk_prelevement_bons = p.rowid";
  502. $sql .= " AND p.rowid = ".((int) $this->id);
  503. $sql .= " AND p.entity = ".((int) $conf->entity);
  504. if ($amounts) {
  505. if ($this->type == 'bank-transfer') {
  506. $sql .= " GROUP BY fk_facture_fourn";
  507. } else {
  508. $sql .= " GROUP BY fk_facture";
  509. }
  510. }
  511. $resql = $this->db->query($sql);
  512. if ($resql) {
  513. $num = $this->db->num_rows($resql);
  514. if ($num) {
  515. $i = 0;
  516. while ($i < $num) {
  517. $row = $this->db->fetch_row($resql);
  518. if (!$amounts) {
  519. $arr[$i] = $row[0];
  520. } else {
  521. $arr[$i] = array(
  522. $row[0],
  523. $row[1]
  524. );
  525. }
  526. $i++;
  527. }
  528. }
  529. $this->db->free($resql);
  530. } else {
  531. dol_syslog(get_class($this)."::getListInvoices Erreur");
  532. }
  533. return $arr;
  534. }
  535. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  536. /**
  537. * Returns amount waiting for direct debit payment or credit transfer payment
  538. *
  539. * @param string $mode 'direct-debit' or 'bank-transfer'
  540. * @return double <O if KO, Total amount
  541. */
  542. public function SommeAPrelever($mode = 'direct-debit')
  543. {
  544. // phpcs:enable
  545. global $conf;
  546. $sql = "SELECT sum(pfd.amount) as nb";
  547. if ($mode != 'bank-transfer') {
  548. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
  549. } else {
  550. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,";
  551. }
  552. $sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
  553. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  554. if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
  555. $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
  556. }
  557. if ($mode != 'bank-transfer') {
  558. $sql .= " AND f.rowid = pfd.fk_facture";
  559. } else {
  560. $sql .= " AND f.rowid = pfd.fk_facture_fourn";
  561. }
  562. $sql .= " AND f.paye = 0";
  563. $sql .= " AND pfd.traite = 0";
  564. $sql .= " AND pfd.ext_payment_id IS NULL";
  565. $sql .= " AND f.total_ttc > 0";
  566. $resql = $this->db->query($sql);
  567. if ($resql) {
  568. $obj = $this->db->fetch_object($resql);
  569. $this->db->free($resql);
  570. return $obj->nb;
  571. } else {
  572. $error = 1;
  573. dol_syslog(get_class($this)."::SommeAPrelever Erreur -1");
  574. dol_syslog($this->db->error());
  575. return -1;
  576. }
  577. }
  578. /**
  579. * Get number of invoices waiting for payment
  580. *
  581. * @param string $mode 'direct-debit' or 'bank-transfer'
  582. * @return int <O if KO, number of invoices if OK
  583. */
  584. public function nbOfInvoiceToPay($mode = 'direct-debit')
  585. {
  586. return $this->NbFactureAPrelever($mode);
  587. }
  588. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  589. /**
  590. * Get number of invoices to pay
  591. *
  592. * @param string $type 'direct-debit' or 'bank-transfer'
  593. * @return int <O if KO, number of invoices if OK
  594. */
  595. public function NbFactureAPrelever($type = 'direct-debit')
  596. {
  597. // phpcs:enable
  598. global $conf;
  599. $sql = "SELECT count(f.rowid) as nb";
  600. if ($type == 'bank-transfer') {
  601. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  602. } else {
  603. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  604. }
  605. $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
  606. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  607. if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS)) {
  608. $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
  609. }
  610. if ($type == 'bank-transfer') {
  611. $sql .= " AND f.rowid = pfd.fk_facture_fourn";
  612. } else {
  613. $sql .= " AND f.rowid = pfd.fk_facture";
  614. }
  615. $sql .= " AND pfd.traite = 0";
  616. $sql .= " AND pfd.ext_payment_id IS NULL";
  617. $sql .= " AND f.total_ttc > 0";
  618. dol_syslog(get_class($this)."::NbFactureAPrelever");
  619. $resql = $this->db->query($sql);
  620. if ($resql) {
  621. $obj = $this->db->fetch_object($resql);
  622. $this->db->free($resql);
  623. return $obj->nb;
  624. } else {
  625. $this->error = get_class($this)."::NbFactureAPrelever Erreur -1 sql=".$this->db->error();
  626. return -1;
  627. }
  628. }
  629. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  630. /**
  631. * Create a direct debit order or a credit transfer order
  632. * TODO delete params banque and agence when not necessary
  633. *
  634. * @param int $banque dolibarr mysoc bank
  635. * @param int $agence dolibarr mysoc bank office (guichet)
  636. * @param string $mode real=do action, simu=test only
  637. * @param string $format FRST, RCUR or ALL
  638. * @param string $executiondate Date to execute the transfer
  639. * @param int $notrigger Disable triggers
  640. * @param string $type 'direct-debit' or 'bank-transfer'
  641. * @return int <0 if KO, No of invoice included into file if OK
  642. */
  643. public function create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0, $type = 'direct-debit')
  644. {
  645. // phpcs:enable
  646. global $conf, $langs, $user;
  647. dol_syslog(__METHOD__."::Bank=".$banque." Office=".$agence." mode=".$mode." format=".$format, LOG_DEBUG);
  648. require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php";
  649. require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
  650. if ($type != 'bank-transfer') {
  651. if (empty($format)) {
  652. $this->error = 'ErrorBadParametersForDirectDebitFileCreate';
  653. return -1;
  654. }
  655. }
  656. $error = 0;
  657. $datetimeprev = time();
  658. //Choice the date of the execution direct debit
  659. if (!empty($executiondate)) {
  660. $datetimeprev = $executiondate;
  661. }
  662. $month = strftime("%m", $datetimeprev);
  663. $year = strftime("%Y", $datetimeprev);
  664. $this->invoice_in_error = array();
  665. $this->thirdparty_in_error = array();
  666. // Read invoices
  667. $factures = array();
  668. $factures_prev = array();
  669. $factures_result = array();
  670. $factures_prev_id = array();
  671. $factures_errors = array();
  672. if (!$error) {
  673. $sql = "SELECT f.rowid, pfd.rowid as pfdrowid, f.fk_soc";
  674. $sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
  675. $sql .= ", pfd.amount";
  676. $sql .= ", s.nom as name";
  677. if ($type != 'bank-transfer') {
  678. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  679. } else {
  680. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  681. }
  682. $sql .= ", ".MAIN_DB_PREFIX."societe as s";
  683. $sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
  684. $sql .= " WHERE f.entity IN (".getEntity('invoice').')';
  685. if ($type != 'bank-transfer') {
  686. $sql .= " AND f.rowid = pfd.fk_facture";
  687. } else {
  688. $sql .= " AND f.rowid = pfd.fk_facture_fourn";
  689. }
  690. $sql .= " AND s.rowid = f.fk_soc";
  691. $sql .= " AND f.fk_statut = 1"; // Invoice validated
  692. $sql .= " AND f.paye = 0";
  693. $sql .= " AND pfd.traite = 0";
  694. $sql .= " AND f.total_ttc > 0";
  695. $sql .= " AND pfd.ext_payment_id IS NULL";
  696. dol_syslog(__METHOD__."::Read invoices,", LOG_DEBUG);
  697. $resql = $this->db->query($sql);
  698. if ($resql) {
  699. $num = $this->db->num_rows($resql);
  700. $i = 0;
  701. while ($i < $num) {
  702. $row = $this->db->fetch_row($resql);
  703. $factures[$i] = $row; // All fields
  704. if ($row[7] == 0) {
  705. $error++;
  706. dol_syslog(__METHOD__."::Read invoices error Found a null invoice", LOG_ERR);
  707. $this->invoice_in_error[$row[0]] = "Error for invoice id ".$row[0].", found a null amount";
  708. break;
  709. }
  710. $i++;
  711. }
  712. $this->db->free($resql);
  713. dol_syslog(__METHOD__."::Read invoices, ".$i." invoices to withdraw", LOG_DEBUG);
  714. } else {
  715. $error++;
  716. dol_syslog(__METHOD__."::Read invoices error ".$this->db->error(), LOG_ERR);
  717. }
  718. }
  719. if (!$error) {
  720. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  721. $soc = new Societe($this->db);
  722. // Check BAN
  723. $i = 0;
  724. dol_syslog(__METHOD__."::Check BAN", LOG_DEBUG);
  725. if (count($factures) > 0) {
  726. foreach ($factures as $key => $fac) {
  727. if ($type != 'bank-transfer') {
  728. $tmpinvoice = new Facture($this->db);
  729. } else {
  730. $tmpinvoice = new FactureFournisseur($this->db);
  731. }
  732. $resfetch = $tmpinvoice->fetch($fac[0]);
  733. if ($resfetch >= 0) { // Field 0 of $fac is rowid of invoice
  734. if ($soc->fetch($tmpinvoice->socid) >= 0) {
  735. $bac = new CompanyBankAccount($this->db);
  736. $bac->fetch(0, $soc->id);
  737. if ($type != 'bank-transfer') {
  738. if ($format == 'FRST' && $bac->frstrecur != 'FRST') {
  739. continue;
  740. }
  741. if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR')) {
  742. continue;
  743. }
  744. }
  745. if ($bac->verif() >= 1) {
  746. $factures_prev[$i] = $fac;
  747. /* second array necessary for BonPrelevement */
  748. $factures_prev_id[$i] = $fac[0];
  749. $i++;
  750. //dol_syslog(__METHOD__."::RIB is ok", LOG_DEBUG);
  751. } else {
  752. dol_syslog(__METHOD__."::Check BAN Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$tmpinvoice->socid." ".$soc->name, LOG_WARNING);
  753. $this->invoice_in_error[$fac[0]] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
  754. $this->thirdparty_in_error[$soc->id] = "Error on default bank number IBAN/BIC for invoice ".$tmpinvoice->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
  755. }
  756. } else {
  757. dol_syslog(__METHOD__."::Check BAN Failed to read company", LOG_WARNING);
  758. }
  759. } else {
  760. dol_syslog(__METHOD__."::Check BAN Failed to read invoice", LOG_WARNING);
  761. }
  762. }
  763. } else {
  764. dol_syslog(__METHOD__."::Check BAN No invoice to process", LOG_WARNING);
  765. }
  766. }
  767. $ok = 0;
  768. // Withdraw invoices in factures_prev array
  769. $out = count($factures_prev)." invoices will be included.";
  770. //print $out."\n";
  771. dol_syslog($out);
  772. // Return warning
  773. /*$i=0;
  774. foreach ($this->thirdparty_in_error as $key => $val)
  775. {
  776. if ($i < 10) setEventMessages($val, null, 'warnings');
  777. else setEventMessages('More error were discarded...', null, 'warnings');
  778. $i++;
  779. }*/
  780. if (count($factures_prev) > 0) {
  781. if ($mode == 'real') {
  782. $ok = 1;
  783. } else {
  784. print $langs->trans("ModeWarning"); // "Option for real mode was not set, we stop after this simulation\n";
  785. }
  786. }
  787. if ($ok) {
  788. /*
  789. * We are in real mode.
  790. * We create order and build file into disk
  791. */
  792. $this->db->begin();
  793. $now = dol_now();
  794. /*
  795. * Process order generation
  796. */
  797. if (!$error) {
  798. $ref = substr($year, -2).$month;
  799. $sql = "SELECT substring(ref from char_length(ref) - 1)"; // To extract "YYMMXX" from "TYYMMXX"
  800. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons";
  801. $sql .= " WHERE ref LIKE '_".$this->db->escape($ref)."%'";
  802. $sql .= " AND entity = ".((int) $conf->entity);
  803. $sql .= " ORDER BY ref DESC LIMIT 1";
  804. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  805. $resql = $this->db->query($sql);
  806. if ($resql) {
  807. $row = $this->db->fetch_row($resql);
  808. // Build the new ref
  809. $ref = "T".$ref.sprintf("%02d", (intval($row[0]) + 1));
  810. // $conf->abc->dir_output may be:
  811. // /home/ldestailleur/git/dolibarr_15.0/documents/abc/
  812. // or
  813. // /home/ldestailleur/git/dolibarr_15.0/documents/X/abc with X >= 2 with multicompany.
  814. if ($type != 'bank-transfer') {
  815. $dir = $conf->prelevement->dir_output.'/receipts';
  816. } else {
  817. $dir = $conf->paymentbybanktransfer->dir_output.'/receipts';
  818. }
  819. if (!is_dir($dir)) {
  820. dol_mkdir($dir);
  821. }
  822. $this->filename = $dir.'/'.$ref.'.xml';
  823. // Create withdraw receipt in database
  824. $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
  825. $sql .= "ref, entity, datec, type";
  826. $sql .= ") VALUES (";
  827. $sql .= "'".$this->db->escape($ref)."'";
  828. $sql .= ", ".((int) $conf->entity);
  829. $sql .= ", '".$this->db->idate($now)."'";
  830. $sql .= ", '".($type == 'bank-transfer' ? 'bank-transfer' : 'debit-order')."'";
  831. $sql .= ")";
  832. $resql = $this->db->query($sql);
  833. if ($resql) {
  834. $prev_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_bons");
  835. $this->id = $prev_id;
  836. $this->ref = $ref;
  837. } else {
  838. $error++;
  839. dol_syslog(__METHOD__."::Create withdraw receipt ".$this->db->lasterror(), LOG_ERR);
  840. }
  841. } else {
  842. $error++;
  843. dol_syslog(__METHOD__."::Get last withdraw receipt ".$this->db->lasterror(), LOG_ERR);
  844. }
  845. }
  846. if (!$error) {
  847. if ($type != 'bank-transfer') {
  848. $fact = new Facture($this->db);
  849. } else {
  850. $fact = new FactureFournisseur($this->db);
  851. }
  852. /*
  853. * Create withdrawal receipt in database
  854. */
  855. if (count($factures_prev) > 0) {
  856. foreach ($factures_prev as $fac) { // Add a link in database for each invoice
  857. // Fetch invoice
  858. $result = $fact->fetch($fac[0]);
  859. if ($result < 0) {
  860. $this->error = 'ERRORBONPRELEVEMENT Failed to load invoice with id '.$fac[0];
  861. break;
  862. }
  863. /*
  864. * Add standing order. This add record into llx_prelevement_lignes
  865. *
  866. * $fac[0] : invoice_id
  867. * $fac[1] : ???
  868. * $fac[2] : third party id
  869. * $fac[3] : banque
  870. * $fac[4] : guichet
  871. * $fac[5] : number
  872. * $fac[6] : cle rib
  873. * $fac[7] : amount
  874. * $fac[8] : client nom
  875. */
  876. $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type);
  877. if ($ri <> 0) {
  878. $error++;
  879. }
  880. // Update invoice requests as done
  881. $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande";
  882. $sql .= " SET traite = 1";
  883. $sql .= ", date_traite = '".$this->db->idate($now)."'";
  884. $sql .= ", fk_prelevement_bons = ".((int) $this->id);
  885. $sql .= " WHERE rowid = ".((int) $fac[1]);
  886. $resql = $this->db->query($sql);
  887. if (!$resql) {
  888. $error++;
  889. $this->errors[] = $this->db->lasterror();
  890. dol_syslog(__METHOD__."::Update Error=".$this->db->lasterror(), LOG_ERR);
  891. }
  892. }
  893. }
  894. }
  895. if (!$error) {
  896. /*
  897. * Create file of type='direct-debit' for direct debit order or type='bank-transfer' for credit transfer into a XML file
  898. */
  899. dol_syslog(__METHOD__."::Init direct debit or credit transfer file for ".count($factures_prev)." invoices", LOG_DEBUG);
  900. if (count($factures_prev) > 0) {
  901. $this->date_echeance = $datetimeprev;
  902. $this->reference_remise = $ref;
  903. $id = $conf->global->PRELEVEMENT_ID_BANKACCOUNT;
  904. if ($type == 'bank-transfer') {
  905. $id = $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT;
  906. }
  907. $account = new Account($this->db);
  908. if ($account->fetch($id) > 0) {
  909. $this->emetteur_code_banque = $account->code_banque;
  910. $this->emetteur_code_guichet = $account->code_guichet;
  911. $this->emetteur_numero_compte = $account->number;
  912. $this->emetteur_number_key = $account->cle_rib;
  913. $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
  914. $this->emetteur_iban = $account->iban;
  915. $this->emetteur_bic = $account->bic;
  916. $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics);
  917. $this->raison_sociale = $account->proprio;
  918. }
  919. $this->factures = $factures_prev_id;
  920. $this->context['factures_prev'] = $factures_prev;
  921. // Generation of direct debit or credti transfer file $this->filename (May be a SEPA file for european countries)
  922. // This also set the property $this->total with amount that is included into file
  923. $result = $this->generate($format, $executiondate, $type);
  924. if ($result < 0) {
  925. //var_dump($this->error);
  926. //var_dump($this->invoice_in_error);
  927. $error++;
  928. }
  929. }
  930. dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
  931. }
  932. //var_dump($this->total);exit;
  933. /*
  934. * Update total defined after generation of file
  935. */
  936. if (!$error) {
  937. $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
  938. $sql .= " SET amount = ".price2num($this->total);
  939. $sql .= " WHERE rowid = ".((int) $this->id);
  940. $sql .= " AND entity = ".((int) $conf->entity);
  941. $resql = $this->db->query($sql);
  942. if (!$resql) {
  943. $error++;
  944. dol_syslog(__METHOD__."::Error update total: ".$this->db->error(), LOG_ERR);
  945. }
  946. }
  947. if (!$error && !$notrigger) {
  948. $triggername = 'DIRECT_DEBIT_ORDER_CREATE';
  949. if ($type != 'bank-transfer') {
  950. $triggername = 'CREDIT_TRANSFER_ORDER_CREATE';
  951. }
  952. // Call trigger
  953. $result = $this->call_trigger($triggername, $user);
  954. if ($result < 0) {
  955. $error++;
  956. }
  957. // End call triggers
  958. }
  959. if (!$error) {
  960. $this->db->commit();
  961. return count($factures_prev);
  962. } else {
  963. $this->db->rollback();
  964. return -1;
  965. }
  966. } else {
  967. return 0;
  968. }
  969. }
  970. /**
  971. * Get object and lines from database
  972. *
  973. * @param User $user Object user that delete
  974. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  975. * @return int >0 if OK, <0 if KO
  976. */
  977. public function delete($user = null, $notrigger = 0)
  978. {
  979. $this->db->begin();
  980. $error = 0;
  981. $resql1 = $resql2 = $resql3 = $resql4 = 0;
  982. if (!$notrigger) {
  983. $triggername = 'DIRECT_DEBIT_ORDER_DELETE';
  984. if ($this->type == 'bank-transfer') {
  985. $triggername = 'PAYMENTBYBANKTRANFER_DELETE';
  986. }
  987. // Call trigger
  988. $result = $this->call_trigger($triggername, $user);
  989. if ($result < 0) {
  990. $error++;
  991. }
  992. // End call triggers
  993. }
  994. if (!$error) {
  995. $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_facture WHERE fk_prelevement_lignes IN (SELECT rowid FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".((int) $this->id).")";
  996. $resql1 = $this->db->query($sql);
  997. if (!$resql1) {
  998. dol_print_error($this->db);
  999. }
  1000. }
  1001. if (!$error) {
  1002. $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_lignes WHERE fk_prelevement_bons = ".((int) $this->id);
  1003. $resql2 = $this->db->query($sql);
  1004. if (!$resql2) {
  1005. dol_print_error($this->db);
  1006. }
  1007. }
  1008. if (!$error) {
  1009. $sql = "DELETE FROM ".MAIN_DB_PREFIX."prelevement_bons WHERE rowid = ".((int) $this->id);
  1010. $resql3 = $this->db->query($sql);
  1011. if (!$resql3) {
  1012. dol_print_error($this->db);
  1013. }
  1014. }
  1015. if (!$error) {
  1016. $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_facture_demande SET fk_prelevement_bons = NULL, traite = 0 WHERE fk_prelevement_bons = ".((int) $this->id);
  1017. $resql4 = $this->db->query($sql);
  1018. if (!$resql4) {
  1019. dol_print_error($this->db);
  1020. }
  1021. }
  1022. if ($resql1 && $resql2 && $resql3 && $resql4 && !$error) {
  1023. $this->db->commit();
  1024. return 1;
  1025. } else {
  1026. $this->db->rollback();
  1027. return -1;
  1028. }
  1029. }
  1030. /**
  1031. * Returns clickable name (with picto)
  1032. *
  1033. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1034. * @param string $option On what the link point to ('nolink', ...)
  1035. * @param int $notooltip 1=Disable tooltip
  1036. * @param string $morecss Add more css on link
  1037. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1038. * @return string URL of target
  1039. */
  1040. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1041. {
  1042. global $conf, $langs, $hookmanager;
  1043. if (!empty($conf->dol_no_mouse_hover)) {
  1044. $notooltip = 1; // Force disable tooltips
  1045. }
  1046. $result = '';
  1047. $labeltoshow = 'PaymentByDirectDebit';
  1048. if ($this->type == 'bank-transfer') {
  1049. $labeltoshow = 'PaymentByBankTransfer';
  1050. }
  1051. $label = '<u>'.$langs->trans($labeltoshow).'</u>';
  1052. $label .= '<br>';
  1053. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1054. if (isset($this->statut)) {
  1055. $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
  1056. }
  1057. $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
  1058. if ($this->type == 'bank-transfer') {
  1059. $url = DOL_URL_ROOT.'/compta/prelevement/card.php?id='.$this->id;
  1060. }
  1061. if ($option != 'nolink') {
  1062. // Add param to save lastsearch_values or not
  1063. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1064. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1065. $add_save_lastsearch_values = 1;
  1066. }
  1067. if ($add_save_lastsearch_values) {
  1068. $url .= '&save_lastsearch_values=1';
  1069. }
  1070. }
  1071. $linkclose = '';
  1072. if (empty($notooltip)) {
  1073. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1074. $label = $langs->trans("ShowMyObject");
  1075. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1076. }
  1077. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1078. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1079. /*
  1080. $hookmanager->initHooks(array('myobjectdao'));
  1081. $parameters=array('id'=>$this->id);
  1082. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1083. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  1084. */
  1085. } else {
  1086. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1087. }
  1088. $linkstart = '<a href="'.$url.'"';
  1089. $linkstart .= $linkclose.'>';
  1090. $linkend = '</a>';
  1091. $result .= $linkstart;
  1092. if ($withpicto) {
  1093. $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);
  1094. }
  1095. if ($withpicto != 2) {
  1096. $result .= $this->ref;
  1097. }
  1098. $result .= $linkend;
  1099. global $action, $hookmanager;
  1100. $hookmanager->initHooks(array('banktransferdao'));
  1101. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1102. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1103. if ($reshook > 0) {
  1104. $result = $hookmanager->resPrint;
  1105. } else {
  1106. $result .= $hookmanager->resPrint;
  1107. }
  1108. return $result;
  1109. }
  1110. /**
  1111. * Delete a notification def by id
  1112. *
  1113. * @param int $rowid id of notification
  1114. * @return int 0 if OK, <0 if KO
  1115. */
  1116. public function deleteNotificationById($rowid)
  1117. {
  1118. $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
  1119. $sql .= " WHERE rowid = ".((int) $rowid);
  1120. if ($this->db->query($sql)) {
  1121. return 0;
  1122. } else {
  1123. return -1;
  1124. }
  1125. }
  1126. /**
  1127. * Delete a notification
  1128. *
  1129. * @param int|User $user notification user
  1130. * @param string $action notification action
  1131. * @return int >0 if OK, <0 if KO
  1132. */
  1133. public function deleteNotification($user, $action)
  1134. {
  1135. if (is_object($user)) {
  1136. $userid = $user->id;
  1137. } else { // If user is an id
  1138. $userid = $user;
  1139. }
  1140. $sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
  1141. $sql .= " WHERE fk_user=".((int) $userid)." AND fk_action='".$this->db->escape($action)."'";
  1142. if ($this->db->query($sql)) {
  1143. return 0;
  1144. } else {
  1145. return -1;
  1146. }
  1147. }
  1148. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1149. /**
  1150. * Add a notification
  1151. *
  1152. * @param DoliDB $db database handler
  1153. * @param int|User $user notification user
  1154. * @param string $action notification action
  1155. * @return int 0 if OK, <0 if KO
  1156. */
  1157. public function addNotification($db, $user, $action)
  1158. {
  1159. // phpcs:enable
  1160. $result = 0;
  1161. if (is_object($user)) {
  1162. $userid = $user->id;
  1163. } else { // If user is an id
  1164. $userid = $user;
  1165. }
  1166. if ($this->deleteNotification($user, $action) == 0) {
  1167. $now = dol_now();
  1168. $sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_user, fk_soc, fk_contact, fk_action)";
  1169. $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $userid).", 'NULL', 'NULL', '".$this->db->escape($action)."')";
  1170. dol_syslog("adnotiff: ".$sql);
  1171. if ($this->db->query($sql)) {
  1172. $result = 0;
  1173. } else {
  1174. $result = -1;
  1175. dol_syslog(get_class($this)."::addNotification Error $result");
  1176. }
  1177. }
  1178. return $result;
  1179. }
  1180. /**
  1181. * Generate a direct debit or credit transfer file.
  1182. * Generation Formats:
  1183. * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled)
  1184. * - Others countries: Warning message
  1185. * File is generated with name this->filename
  1186. *
  1187. * @param string $format FRST, RCUR or ALL
  1188. * @param string $executiondate Date to execute transfer
  1189. * @param string $type 'direct-debit' or 'bank-transfer'
  1190. * @return int >=0 if OK, <0 if KO
  1191. */
  1192. public function generate($format = 'ALL', $executiondate = '', $type = 'direct-debit')
  1193. {
  1194. global $conf, $langs, $mysoc;
  1195. //TODO: Optimize code to read lines in a single function
  1196. $result = 0;
  1197. dol_syslog(get_class($this)."::generate build file=".$this->filename." type=".$type);
  1198. $this->file = fopen($this->filename, "w");
  1199. if (empty($this->file)) {
  1200. $this->error = $langs->trans('ErrorFailedToOpenFile', $this->filename);
  1201. return -1;
  1202. }
  1203. $found = 0;
  1204. $this->total = 0;
  1205. // Build file for European countries
  1206. if ($mysoc->isInEEC()) {
  1207. $found++;
  1208. if ($type != 'bank-transfer') {
  1209. /**
  1210. * SECTION CREATION FICHIER SEPA - DIRECT DEBIT
  1211. */
  1212. // SEPA Initialisation
  1213. $CrLf = "\n";
  1214. $now = dol_now();
  1215. $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
  1216. $date_actu = $now;
  1217. if (!empty($executiondate)) {
  1218. $date_actu = $executiondate;
  1219. }
  1220. $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
  1221. $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
  1222. $fileDebiteurSection = '';
  1223. $fileEmetteurSection = '';
  1224. $i = 0;
  1225. /*
  1226. * Section Debitor (sepa Debiteurs bloc lines)
  1227. */
  1228. $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
  1229. $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
  1230. $sql .= " f.ref as fac, pf.fk_facture as idfac,";
  1231. $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
  1232. $sql .= " FROM";
  1233. $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
  1234. $sql .= " ".MAIN_DB_PREFIX."facture as f,";
  1235. $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
  1236. $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
  1237. $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
  1238. $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
  1239. $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
  1240. $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
  1241. $sql .= " AND pf.fk_facture = f.rowid";
  1242. $sql .= " AND f.fk_soc = soc.rowid";
  1243. $sql .= " AND soc.fk_pays = c.rowid";
  1244. $sql .= " AND rib.fk_soc = f.fk_soc";
  1245. $sql .= " AND rib.default_rib = 1";
  1246. $sql .= " AND rib.type = 'ban'";
  1247. // Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
  1248. $resql = $this->db->query($sql);
  1249. if ($resql) {
  1250. $cachearraytotestduplicate = array();
  1251. $num = $this->db->num_rows($resql);
  1252. while ($i < $num) {
  1253. $obj = $this->db->fetch_object($resql);
  1254. if (!empty($cachearraytotestduplicate[$obj->idfac])) {
  1255. $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
  1256. $this->invoice_in_error[$obj->idfac] = $this->error;
  1257. $result = -2;
  1258. break;
  1259. }
  1260. $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
  1261. $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
  1262. $fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum, $type);
  1263. $this->total = $this->total + $obj->somme;
  1264. $i++;
  1265. }
  1266. $nbtotalDrctDbtTxInf = $i;
  1267. } else {
  1268. $this->error = $this->db->lasterror();
  1269. fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
  1270. $result = -2;
  1271. }
  1272. // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
  1273. if ($result != -2) {
  1274. $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
  1275. }
  1276. /**
  1277. * SECTION CREATION SEPA FILE - ISO200022
  1278. */
  1279. // SEPA File Header
  1280. fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
  1281. fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
  1282. fputs($this->file, ' <CstmrDrctDbtInitn>'.$CrLf);
  1283. // SEPA Group header
  1284. fputs($this->file, ' <GrpHdr>'.$CrLf);
  1285. fputs($this->file, ' <MsgId>'.('DD/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
  1286. fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
  1287. fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
  1288. fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
  1289. fputs($this->file, ' <InitgPty>'.$CrLf);
  1290. fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf);
  1291. fputs($this->file, ' <Id>'.$CrLf);
  1292. fputs($this->file, ' <PrvtId>'.$CrLf);
  1293. fputs($this->file, ' <Othr>'.$CrLf);
  1294. fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
  1295. fputs($this->file, ' </Othr>'.$CrLf);
  1296. fputs($this->file, ' </PrvtId>'.$CrLf);
  1297. fputs($this->file, ' </Id>'.$CrLf);
  1298. fputs($this->file, ' </InitgPty>'.$CrLf);
  1299. fputs($this->file, ' </GrpHdr>'.$CrLf);
  1300. // SEPA File Emetteur
  1301. if ($result != -2) {
  1302. fputs($this-> file, $fileEmetteurSection);
  1303. }
  1304. // SEPA File Debiteurs
  1305. if ($result != -2) {
  1306. fputs($this-> file, $fileDebiteurSection);
  1307. }
  1308. // SEPA FILE FOOTER
  1309. fputs($this->file, ' </PmtInf>'.$CrLf);
  1310. fputs($this->file, ' </CstmrDrctDbtInitn>'.$CrLf);
  1311. fputs($this->file, '</Document>'.$CrLf);
  1312. } else {
  1313. /**
  1314. * SECTION CREATION FICHIER SEPA - CREDIT TRANSFER
  1315. */
  1316. // SEPA Initialisation
  1317. $CrLf = "\n";
  1318. $now = dol_now();
  1319. $dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
  1320. $date_actu = $now;
  1321. if (!empty($executiondate)) {
  1322. $date_actu = $executiondate;
  1323. }
  1324. $dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
  1325. $dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
  1326. $fileCrediteurSection = '';
  1327. $fileEmetteurSection = '';
  1328. $i = 0;
  1329. /*
  1330. * Section Creditor (sepa Crediteurs bloc lines)
  1331. */
  1332. $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
  1333. $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
  1334. $sql .= " f.ref as fac, pf.fk_facture_fourn as idfac, f.ref_supplier as fac_ref_supplier,";
  1335. $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
  1336. $sql .= " FROM";
  1337. $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
  1338. $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
  1339. $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
  1340. $sql .= " ".MAIN_DB_PREFIX."societe as soc,";
  1341. $sql .= " ".MAIN_DB_PREFIX."c_country as c,";
  1342. $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
  1343. $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
  1344. $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
  1345. $sql .= " AND pf.fk_facture_fourn = f.rowid";
  1346. $sql .= " AND f.fk_soc = soc.rowid";
  1347. $sql .= " AND soc.fk_pays = c.rowid";
  1348. $sql .= " AND rib.fk_soc = f.fk_soc";
  1349. $sql .= " AND rib.default_rib = 1";
  1350. $sql .= " AND rib.type = 'ban'";
  1351. // Define $fileCrediteurSection. One section DrctDbtTxInf per invoice.
  1352. $resql = $this->db->query($sql);
  1353. if ($resql) {
  1354. $cachearraytotestduplicate = array();
  1355. $num = $this->db->num_rows($resql);
  1356. while ($i < $num) {
  1357. $obj = $this->db->fetch_object($resql);
  1358. if (!empty($cachearraytotestduplicate[$obj->idfac])) {
  1359. $this->error = $langs->trans('ErrorCompanyHasDuplicateDefaultBAN', $obj->socid);
  1360. $this->invoice_in_error[$obj->idfac] = $this->error;
  1361. $result = -2;
  1362. break;
  1363. }
  1364. $cachearraytotestduplicate[$obj->idfac] = $obj->rowid;
  1365. $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
  1366. $fileCrediteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac_ref_supplier, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum, $type);
  1367. $this->total = $this->total + $obj->somme;
  1368. $i++;
  1369. }
  1370. $nbtotalDrctDbtTxInf = $i;
  1371. } else {
  1372. $this->error = $this->db->lasterror();
  1373. fputs($this->file, 'ERROR CREDITOR '.$sql.$CrLf); // CREDITORS = Suppliers
  1374. $result = -2;
  1375. }
  1376. // Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all $nbtotalDrctDbtTxInf
  1377. if ($result != -2) {
  1378. $fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format, $type);
  1379. }
  1380. /**
  1381. * SECTION CREATION SEPA FILE - CREDIT TRANSFER - ISO200022
  1382. */
  1383. // SEPA File Header
  1384. fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
  1385. fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
  1386. fputs($this->file, ' <CstmrCdtTrfInitn>'.$CrLf);
  1387. // SEPA Group header
  1388. fputs($this->file, ' <GrpHdr>'.$CrLf);
  1389. fputs($this->file, ' <MsgId>'.('TRF/'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
  1390. fputs($this->file, ' <CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
  1391. fputs($this->file, ' <NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
  1392. fputs($this->file, ' <CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
  1393. fputs($this->file, ' <InitgPty>'.$CrLf);
  1394. fputs($this->file, ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf);
  1395. fputs($this->file, ' <Id>'.$CrLf);
  1396. fputs($this->file, ' <PrvtId>'.$CrLf);
  1397. fputs($this->file, ' <Othr>'.$CrLf);
  1398. fputs($this->file, ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf);
  1399. fputs($this->file, ' </Othr>'.$CrLf);
  1400. fputs($this->file, ' </PrvtId>'.$CrLf);
  1401. fputs($this->file, ' </Id>'.$CrLf);
  1402. fputs($this->file, ' </InitgPty>'.$CrLf);
  1403. fputs($this->file, ' </GrpHdr>'.$CrLf);
  1404. // SEPA File Emetteur (mycompany)
  1405. if ($result != -2) {
  1406. fputs($this-> file, $fileEmetteurSection);
  1407. }
  1408. // SEPA File Creditors
  1409. if ($result != -2) {
  1410. fputs($this-> file, $fileCrediteurSection);
  1411. }
  1412. // SEPA FILE FOOTER
  1413. fputs($this->file, ' </PmtInf>'.$CrLf);
  1414. fputs($this->file, ' </CstmrCdtTrfInitn>'.$CrLf);
  1415. fputs($this->file, '</Document>'.$CrLf);
  1416. }
  1417. }
  1418. // Build file for Other Countries with unknow format
  1419. if (!$found) {
  1420. if ($type != 'bank-transfer') {
  1421. $sql = "SELECT pl.amount";
  1422. $sql .= " FROM";
  1423. $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
  1424. $sql .= " ".MAIN_DB_PREFIX."facture as f,";
  1425. $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
  1426. $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
  1427. $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
  1428. $sql .= " AND pf.fk_facture = f.rowid";
  1429. // Lines
  1430. $i = 0;
  1431. $resql = $this->db->query($sql);
  1432. if ($resql) {
  1433. $num = $this->db->num_rows($resql);
  1434. while ($i < $num) {
  1435. $obj = $this->db->fetch_object($resql);
  1436. $this->total = $this->total + $obj->amount;
  1437. // TODO Write record into file
  1438. $i++;
  1439. }
  1440. } else {
  1441. $result = -2;
  1442. }
  1443. } else {
  1444. $sql = "SELECT pl.amount";
  1445. $sql .= " FROM";
  1446. $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
  1447. $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
  1448. $sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
  1449. $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id);
  1450. $sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
  1451. $sql .= " AND pf.fk_facture_fourn = f.rowid";
  1452. // Lines
  1453. $i = 0;
  1454. $resql = $this->db->query($sql);
  1455. if ($resql) {
  1456. $num = $this->db->num_rows($resql);
  1457. while ($i < $num) {
  1458. $obj = $this->db->fetch_object($resql);
  1459. $this->total = $this->total + $obj->amount;
  1460. // TODO Write record into file
  1461. $i++;
  1462. }
  1463. } else {
  1464. $result = -2;
  1465. }
  1466. }
  1467. $langs->load('withdrawals');
  1468. // TODO Add here code to generate a generic file
  1469. fputs($this->file, $langs->transnoentitiesnoconv('WithdrawalFileNotCapable', $mysoc->country_code));
  1470. }
  1471. fclose($this->file);
  1472. if (!empty($conf->global->MAIN_UMASK)) {
  1473. @chmod($this->file, octdec($conf->global->MAIN_UMASK));
  1474. }
  1475. return $result;
  1476. }
  1477. /**
  1478. * Generate dynamically a RUM number for a customer bank account
  1479. *
  1480. * @param string $row_code_client Customer code (soc.code_client)
  1481. * @param int $row_datec Creation date of bank account (rib.datec)
  1482. * @param string $row_drum Id of customer bank account (rib.rowid)
  1483. * @return string RUM number
  1484. */
  1485. public static function buildRumNumber($row_code_client, $row_datec, $row_drum)
  1486. {
  1487. global $langs;
  1488. $pre = substr(dol_string_nospecial(dol_string_unaccent($langs->transnoentitiesnoconv('RUM'))), 0, 3); // Must always be on 3 char ('RUM' or 'UMR'. This is a protection against bad translation)
  1489. return $pre.'-'.$row_code_client.'-'.$row_drum.'-'.date('U', $row_datec);
  1490. }
  1491. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1492. /**
  1493. * Write recipient of request (customer)
  1494. *
  1495. * @param int $rowid id of line
  1496. * @param string $client_nom name of customer
  1497. * @param string $rib_banque code of bank
  1498. * @param string $rib_guichet code of bank office
  1499. * @param string $rib_number bank account
  1500. * @param float $amount amount
  1501. * @param string $ref ref of invoice
  1502. * @param int $facid id of invoice
  1503. * @param string $rib_dom rib domiciliation
  1504. * @param string $type 'direct-debit' or 'bank-transfer'
  1505. * @return void
  1506. * @see EnregDestinataireSEPA()
  1507. */
  1508. public function EnregDestinataire($rowid, $client_nom, $rib_banque, $rib_guichet, $rib_number, $amount, $ref, $facid, $rib_dom = '', $type = 'direct-debit')
  1509. {
  1510. // phpcs:enable
  1511. fputs($this->file, "06");
  1512. fputs($this->file, "08"); // Prelevement ordinaire
  1513. fputs($this->file, " "); // Zone Reservee B2
  1514. fputs($this->file, $this->emetteur_ics); // ICS
  1515. // Date d'echeance C1
  1516. fputs($this->file, " ");
  1517. fputs($this->file, strftime("%d%m", $this->date_echeance));
  1518. fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
  1519. // Raison Sociale Destinataire C2
  1520. fputs($this->file, substr(strtoupper($client_nom)." ", 0, 24));
  1521. // Domiciliation facultative D1
  1522. $domiciliation = strtr($rib_dom, array(" " => "-", CHR(13) => " ", CHR(10) => ""));
  1523. fputs($this->file, substr($domiciliation." ", 0, 24));
  1524. // Zone Reservee D2
  1525. fputs($this->file, substr(" ", 0, 8));
  1526. // Code Guichet D3
  1527. fputs($this->file, $rib_guichet);
  1528. // Numero de compte D4
  1529. fputs($this->file, substr("000000000000000".$rib_number, -11));
  1530. // Zone E Montant
  1531. $montant = (round($amount, 2) * 100);
  1532. fputs($this->file, substr("000000000000000".$montant, -16));
  1533. // Libelle F
  1534. fputs($this->file, substr("*_".$ref."_RDVnet".$rowid." ", 0, 31));
  1535. // Code etablissement G1
  1536. fputs($this->file, $rib_banque);
  1537. // Zone Reservee G2
  1538. fputs($this->file, substr(" ", 0, 5));
  1539. fputs($this->file, "\n");
  1540. }
  1541. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1542. /**
  1543. * Write recipient of request (customer)
  1544. *
  1545. * @param string $row_code_client soc.code_client as code,
  1546. * @param string $row_nom pl.client_nom AS name,
  1547. * @param string $row_address soc.address AS adr,
  1548. * @param string $row_zip soc.zip
  1549. * @param string $row_town soc.town
  1550. * @param string $row_country_code c.code AS country,
  1551. * @param string $row_cb pl.code_banque AS cb, Not used for SEPA
  1552. * @param string $row_cg pl.code_guichet AS cg, Not used for SEPA
  1553. * @param string $row_cc pl.number AS cc, Not used for SEPA
  1554. * @param string $row_somme pl.amount AS somme,
  1555. * @param string $row_ref f.ref
  1556. * @param string $row_idfac pf.fk_facture AS idfac,
  1557. * @param string $row_iban rib.iban_prefix AS iban,
  1558. * @param string $row_bic rib.bic AS bic,
  1559. * @param string $row_datec rib.datec,
  1560. * @param string $row_drum rib.rowid used to generate rum
  1561. * @param string $row_rum rib.rum Rum defined on company bank account
  1562. * @param string $type 'direct-debit' or 'bank-transfer'
  1563. * @return string Return string with SEPA part DrctDbtTxInf
  1564. * @see EnregDestinataire()
  1565. */
  1566. public function EnregDestinataireSEPA($row_code_client, $row_nom, $row_address, $row_zip, $row_town, $row_country_code, $row_cb, $row_cg, $row_cc, $row_somme, $row_ref, $row_idfac, $row_iban, $row_bic, $row_datec, $row_drum, $row_rum, $type = 'direct-debit')
  1567. {
  1568. // phpcs:enable
  1569. global $conf;
  1570. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  1571. $CrLf = "\n";
  1572. $Rowing = sprintf("%010d", $row_idfac);
  1573. // Define value for RUM
  1574. // Example: RUMCustomerCode-CustomerBankAccountId-01424448606 (note: Date is date of creation of CustomerBankAccountId)
  1575. $Rum = empty($row_rum) ? $this->buildRumNumber($row_code_client, $row_datec, $row_drum) : $row_rum;
  1576. // Define date of RUM signature
  1577. $DtOfSgntr = dol_print_date($row_datec, '%Y-%m-%d');
  1578. if ($type != 'bank-transfer') {
  1579. // SEPA Paiement Information of buyer for Direct Debit
  1580. $XML_DEBITOR = '';
  1581. $XML_DEBITOR .= ' <DrctDbtTxInf>'.$CrLf;
  1582. $XML_DEBITOR .= ' <PmtId>'.$CrLf;
  1583. // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
  1584. $XML_DEBITOR .= ' <EndToEndId>'.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('DD-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).'</EndToEndId>'.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters
  1585. $XML_DEBITOR .= ' </PmtId>'.$CrLf;
  1586. $XML_DEBITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
  1587. $XML_DEBITOR .= ' <DrctDbtTx>'.$CrLf;
  1588. $XML_DEBITOR .= ' <MndtRltdInf>'.$CrLf;
  1589. $XML_DEBITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
  1590. $XML_DEBITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
  1591. $XML_DEBITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
  1592. $XML_DEBITOR .= ' </MndtRltdInf>'.$CrLf;
  1593. $XML_DEBITOR .= ' </DrctDbtTx>'.$CrLf;
  1594. $XML_DEBITOR .= ' <DbtrAgt>'.$CrLf;
  1595. $XML_DEBITOR .= ' <FinInstnId>'.$CrLf;
  1596. $XML_DEBITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
  1597. $XML_DEBITOR .= ' </FinInstnId>'.$CrLf;
  1598. $XML_DEBITOR .= ' </DbtrAgt>'.$CrLf;
  1599. $XML_DEBITOR .= ' <Dbtr>'.$CrLf;
  1600. $XML_DEBITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).'</Nm>'.$CrLf;
  1601. $XML_DEBITOR .= ' <PstlAdr>'.$CrLf;
  1602. $XML_DEBITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
  1603. $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
  1604. $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
  1605. if (trim($addressline1)) {
  1606. $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline1), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1607. }
  1608. if (trim($addressline2)) {
  1609. $XML_DEBITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline2), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1610. }
  1611. $XML_DEBITOR .= ' </PstlAdr>'.$CrLf;
  1612. $XML_DEBITOR .= ' </Dbtr>'.$CrLf;
  1613. $XML_DEBITOR .= ' <DbtrAcct>'.$CrLf;
  1614. $XML_DEBITOR .= ' <Id>'.$CrLf;
  1615. $XML_DEBITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
  1616. $XML_DEBITOR .= ' </Id>'.$CrLf;
  1617. $XML_DEBITOR .= ' </DbtrAcct>'.$CrLf;
  1618. $XML_DEBITOR .= ' <RmtInf>'.$CrLf;
  1619. // A string with some information on payment - 140 max
  1620. $XML_DEBITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
  1621. $XML_DEBITOR .= ' </RmtInf>'.$CrLf;
  1622. $XML_DEBITOR .= ' </DrctDbtTxInf>'.$CrLf;
  1623. return $XML_DEBITOR;
  1624. } else {
  1625. // SEPA Paiement Information of seller for Credit Transfer
  1626. $XML_CREDITOR = '';
  1627. $XML_CREDITOR .= ' <CdtTrfTxInf>'.$CrLf;
  1628. $XML_CREDITOR .= ' <PmtId>'.$CrLf;
  1629. // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum)
  1630. $XML_CREDITOR .= ' <EndToEndId>'.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('CT-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).'</EndToEndId>'.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters
  1631. $XML_CREDITOR .= ' </PmtId>'.$CrLf;
  1632. if (!empty($this->sepa_xml_pti_in_ctti)) {
  1633. $XML_CREDITOR .= ' <PmtTpInf>' . $CrLf;
  1634. // Can be 'NORM' for normal or 'HIGH' for high priority level
  1635. if (!empty($conf->global->PAYMENTBYBANKTRANSFER_FORCE_HIGH_PRIORITY)) {
  1636. $instrprty = 'HIGH';
  1637. } else {
  1638. $instrprty = 'NORM';
  1639. }
  1640. $XML_CREDITOR .= ' <InstrPrty>'.$instrprty.'</InstrPrty>' . $CrLf;
  1641. $XML_CREDITOR .= ' <SvcLvl>' . $CrLf;
  1642. $XML_CREDITOR .= ' <Cd>SEPA</Cd>' . $CrLf;
  1643. $XML_CREDITOR .= ' </SvcLvl>' . $CrLf;
  1644. $XML_CREDITOR .= ' <CtgyPurp>' . $CrLf;
  1645. $XML_CREDITOR .= ' <Cd>CORE</Cd>' . $CrLf;
  1646. $XML_CREDITOR .= ' </CtgyPurp>' . $CrLf;
  1647. $XML_CREDITOR .= ' </PmtTpInf>' . $CrLf;
  1648. }
  1649. $XML_CREDITOR .= ' <Amt>'.$CrLf;
  1650. $XML_CREDITOR .= ' <InstdAmt Ccy="EUR">'.round($row_somme, 2).'</InstdAmt>'.$CrLf;
  1651. $XML_CREDITOR .= ' </Amt>'.$CrLf;
  1652. /*
  1653. $XML_CREDITOR .= ' <DrctDbtTx>'.$CrLf;
  1654. $XML_CREDITOR .= ' <MndtRltdInf>'.$CrLf;
  1655. $XML_CREDITOR .= ' <MndtId>'.$Rum.'</MndtId>'.$CrLf;
  1656. $XML_CREDITOR .= ' <DtOfSgntr>'.$DtOfSgntr.'</DtOfSgntr>'.$CrLf;
  1657. $XML_CREDITOR .= ' <AmdmntInd>false</AmdmntInd>'.$CrLf;
  1658. $XML_CREDITOR .= ' </MndtRltdInf>'.$CrLf;
  1659. $XML_CREDITOR .= ' </DrctDbtTx>'.$CrLf;
  1660. */
  1661. //$XML_CREDITOR .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf;
  1662. $XML_CREDITOR .= ' <CdtrAgt>'.$CrLf;
  1663. $XML_CREDITOR .= ' <FinInstnId>'.$CrLf;
  1664. $XML_CREDITOR .= ' <BIC>'.$row_bic.'</BIC>'.$CrLf;
  1665. $XML_CREDITOR .= ' </FinInstnId>'.$CrLf;
  1666. $XML_CREDITOR .= ' </CdtrAgt>'.$CrLf;
  1667. $XML_CREDITOR .= ' <Cdtr>'.$CrLf;
  1668. $XML_CREDITOR .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($row_nom))).'</Nm>'.$CrLf;
  1669. $XML_CREDITOR .= ' <PstlAdr>'.$CrLf;
  1670. $XML_CREDITOR .= ' <Ctry>'.$row_country_code.'</Ctry>'.$CrLf;
  1671. $addressline1 = strtr($row_address, array(CHR(13) => ", ", CHR(10) => ""));
  1672. $addressline2 = strtr($row_zip.(($row_zip && $row_town) ? ' ' : ''.$row_town), array(CHR(13) => ", ", CHR(10) => ""));
  1673. if (trim($addressline1)) {
  1674. $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline1), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1675. }
  1676. if (trim($addressline2)) {
  1677. $XML_CREDITOR .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline2), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1678. }
  1679. $XML_CREDITOR .= ' </PstlAdr>'.$CrLf;
  1680. $XML_CREDITOR .= ' </Cdtr>'.$CrLf;
  1681. $XML_CREDITOR .= ' <CdtrAcct>'.$CrLf;
  1682. $XML_CREDITOR .= ' <Id>'.$CrLf;
  1683. $XML_CREDITOR .= ' <IBAN>'.preg_replace('/\s/', '', $row_iban).'</IBAN>'.$CrLf;
  1684. $XML_CREDITOR .= ' </Id>'.$CrLf;
  1685. $XML_CREDITOR .= ' </CdtrAcct>'.$CrLf;
  1686. $XML_CREDITOR .= ' <RmtInf>'.$CrLf;
  1687. // A string with some information on payment - 140 max
  1688. $XML_CREDITOR .= ' <Ustrd>'.(($conf->global->PRELEVEMENT_USTRD != "") ? $conf->global->PRELEVEMENT_USTRD : dol_trunc($row_ref, 135, 'right', 'UTF-8', 1)).'</Ustrd>'.$CrLf; // 140 max
  1689. $XML_CREDITOR .= ' </RmtInf>'.$CrLf;
  1690. $XML_CREDITOR .= ' </CdtTrfTxInf>'.$CrLf;
  1691. return $XML_CREDITOR;
  1692. }
  1693. }
  1694. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1695. /**
  1696. * Write sender of request (me).
  1697. *
  1698. * @param string $type 'direct-debit' or 'bank-transfer'
  1699. * @return void
  1700. * @see EnregEmetteurSEPA()
  1701. */
  1702. public function EnregEmetteur($type = 'direct-debit')
  1703. {
  1704. // phpcs:enable
  1705. fputs($this->file, "03");
  1706. fputs($this->file, "08"); // Prelevement ordinaire
  1707. fputs($this->file, " "); // Zone Reservee B2
  1708. fputs($this->file, $this->emetteur_ics); // ICS
  1709. // Date d'echeance C1
  1710. fputs($this->file, " ");
  1711. fputs($this->file, strftime("%d%m", $this->date_echeance));
  1712. fputs($this->file, substr(strftime("%y", $this->date_echeance), 1));
  1713. // Raison Sociale C2
  1714. fputs($this->file, substr($this->raison_sociale." ", 0, 24));
  1715. // Reference de la remise creancier D1 sur 7 caracteres
  1716. fputs($this->file, substr($this->reference_remise." ", 0, 7));
  1717. // Zone Reservee D1-2
  1718. fputs($this->file, substr(" ", 0, 17));
  1719. // Zone Reservee D2
  1720. fputs($this->file, substr(" ", 0, 2));
  1721. fputs($this->file, "E");
  1722. fputs($this->file, substr(" ", 0, 5));
  1723. // Code Guichet D3
  1724. fputs($this->file, $this->emetteur_code_guichet);
  1725. // Numero de compte D4
  1726. fputs($this->file, substr("000000000000000".$this->emetteur_numero_compte, -11));
  1727. // Zone Reservee E
  1728. fputs($this->file, substr(" ", 0, 16));
  1729. // Zone Reservee F
  1730. fputs($this->file, substr(" ", 0, 31));
  1731. // Code etablissement
  1732. fputs($this->file, $this->emetteur_code_banque);
  1733. // Zone Reservee G
  1734. fputs($this->file, substr(" ", 0, 5));
  1735. fputs($this->file, "\n");
  1736. }
  1737. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1738. /**
  1739. * Write sender of request (me).
  1740. * Note: The tag PmtInf is opened here but closed into caller
  1741. *
  1742. * @param Conf $configuration conf
  1743. * @param int $ladate Date
  1744. * @param int $nombre 0 or 1
  1745. * @param float $total Total
  1746. * @param string $CrLf End of line character
  1747. * @param string $format FRST or RCUR or ALL
  1748. * @param string $type 'direct-debit' or 'bank-transfer'
  1749. * @return string String with SEPA Sender
  1750. * @see EnregEmetteur()
  1751. */
  1752. public function EnregEmetteurSEPA($configuration, $ladate, $nombre, $total, $CrLf = '\n', $format = 'FRST', $type = 'direct-debit')
  1753. {
  1754. // phpcs:enable
  1755. // SEPA INITIALISATION
  1756. global $conf;
  1757. $dateTime_YMD = dol_print_date($ladate, '%Y%m%d');
  1758. $dateTime_ETAD = dol_print_date($ladate, '%Y-%m-%d');
  1759. $dateTime_YMDHMS = dol_print_date($ladate, '%Y-%m-%dT%H:%M:%S');
  1760. // Get data of bank account
  1761. //$id = $configuration->global->PRELEVEMENT_ID_BANKACCOUNT;
  1762. $id = ($type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT);
  1763. $account = new Account($this->db);
  1764. if ($account->fetch($id) > 0) {
  1765. $this->emetteur_code_banque = $account->code_banque;
  1766. $this->emetteur_code_guichet = $account->code_guichet;
  1767. $this->emetteur_numero_compte = $account->number;
  1768. $this->emetteur_number_key = $account->cle_rib;
  1769. $this->sepa_xml_pti_in_ctti = (bool) $account->pti_in_ctti;
  1770. $this->emetteur_iban = $account->iban;
  1771. $this->emetteur_bic = $account->bic;
  1772. $this->emetteur_ics = ($type == 'bank-transfer' ? $account->ics_transfer : $account->ics); // Ex: PRELEVEMENT_ICS = "FR78ZZZ123456";
  1773. $this->raison_sociale = $account->proprio;
  1774. }
  1775. // Get pending payments
  1776. $sql = "SELECT rowid, ref";
  1777. $sql .= " FROM";
  1778. $sql .= " ".MAIN_DB_PREFIX."prelevement_bons as pb";
  1779. $sql .= " WHERE pb.rowid = ".((int) $this->id);
  1780. $resql = $this->db->query($sql);
  1781. if ($resql) {
  1782. $obj = $this->db->fetch_object($resql);
  1783. $country = explode(':', $configuration->global->MAIN_INFO_SOCIETE_COUNTRY);
  1784. $IdBon = sprintf("%05d", $obj->rowid);
  1785. $RefBon = $obj->ref;
  1786. if ($type != 'bank-transfer') {
  1787. // SEPA Paiement Information of my company for Direct Debit
  1788. $XML_SEPA_INFO = '';
  1789. $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
  1790. $XML_SEPA_INFO .= ' <PmtInfId>'.('DD/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
  1791. $XML_SEPA_INFO .= ' <PmtMtd>DD</PmtMtd>'.$CrLf;
  1792. $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
  1793. $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
  1794. $XML_SEPA_INFO .= ' <PmtTpInf>'.$CrLf;
  1795. $XML_SEPA_INFO .= ' <SvcLvl>'.$CrLf;
  1796. $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>'.$CrLf;
  1797. $XML_SEPA_INFO .= ' </SvcLvl>'.$CrLf;
  1798. $XML_SEPA_INFO .= ' <LclInstrm>'.$CrLf;
  1799. $XML_SEPA_INFO .= ' <Cd>CORE</Cd>'.$CrLf;
  1800. $XML_SEPA_INFO .= ' </LclInstrm>'.$CrLf;
  1801. $XML_SEPA_INFO .= ' <SeqTp>'.$format.'</SeqTp>'.$CrLf;
  1802. $XML_SEPA_INFO .= ' </PmtTpInf>'.$CrLf;
  1803. $XML_SEPA_INFO .= ' <ReqdColltnDt>'.$dateTime_ETAD.'</ReqdColltnDt>'.$CrLf;
  1804. $XML_SEPA_INFO .= ' <Cdtr>'.$CrLf;
  1805. $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf;
  1806. $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
  1807. $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
  1808. $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
  1809. $addressline2 = strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN) ? ' ' : '').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => ""));
  1810. if ($addressline1) {
  1811. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline1), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1812. }
  1813. if ($addressline2) {
  1814. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline2), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1815. }
  1816. $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
  1817. $XML_SEPA_INFO .= ' </Cdtr>'.$CrLf;
  1818. $XML_SEPA_INFO .= ' <CdtrAcct>'.$CrLf;
  1819. $XML_SEPA_INFO .= ' <Id>'.$CrLf;
  1820. $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
  1821. $XML_SEPA_INFO .= ' </Id>'.$CrLf;
  1822. $XML_SEPA_INFO .= ' </CdtrAcct>'.$CrLf;
  1823. $XML_SEPA_INFO .= ' <CdtrAgt>'.$CrLf;
  1824. $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
  1825. $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
  1826. $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
  1827. $XML_SEPA_INFO .= ' </CdtrAgt>'.$CrLf;
  1828. /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
  1829. $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf;
  1830. $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
  1831. $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
  1832. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS.'</AdrLine>').$CrLf;
  1833. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN).'</AdrLine>'.$CrLf;
  1834. $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
  1835. $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
  1836. $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
  1837. $XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
  1838. $XML_SEPA_INFO .= ' <Id>'.$CrLf;
  1839. $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
  1840. $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
  1841. $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
  1842. $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
  1843. $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
  1844. $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
  1845. $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
  1846. $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
  1847. $XML_SEPA_INFO .= ' </Id>'.$CrLf;
  1848. $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;
  1849. } else {
  1850. // SEPA Paiement Information of my company for Credit Transfer
  1851. $XML_SEPA_INFO = '';
  1852. $XML_SEPA_INFO .= ' <PmtInf>'.$CrLf;
  1853. $XML_SEPA_INFO .= ' <PmtInfId>'.('TRF/'.$dateTime_YMD.'/ID'.$IdBon.'-'.$RefBon).'</PmtInfId>'.$CrLf;
  1854. $XML_SEPA_INFO .= ' <PmtMtd>TRF</PmtMtd>'.$CrLf;
  1855. //$XML_SEPA_INFO .= ' <BtchBookg>False</BtchBookg>'.$CrLf;
  1856. $XML_SEPA_INFO .= ' <NbOfTxs>'.$nombre.'</NbOfTxs>'.$CrLf;
  1857. $XML_SEPA_INFO .= ' <CtrlSum>'.$total.'</CtrlSum>'.$CrLf;
  1858. if (!empty($this->sepa_xml_pti_in_ctti) && !empty($format)) { // @TODO Using $format (FRST ou RCUR) in a section for a Credit Transfer looks strange.
  1859. $XML_SEPA_INFO .= ' <PmtTpInf>' . $CrLf;
  1860. $XML_SEPA_INFO .= ' <SvcLvl>' . $CrLf;
  1861. $XML_SEPA_INFO .= ' <Cd>SEPA</Cd>' . $CrLf;
  1862. $XML_SEPA_INFO .= ' </SvcLvl>' . $CrLf;
  1863. $XML_SEPA_INFO .= ' <LclInstrm>' . $CrLf;
  1864. $XML_SEPA_INFO .= ' <Cd>CORE</Cd>' . $CrLf;
  1865. $XML_SEPA_INFO .= ' </LclInstrm>' . $CrLf;
  1866. $XML_SEPA_INFO .= ' <SeqTp>' . $format . '</SeqTp>' . $CrLf;
  1867. $XML_SEPA_INFO .= ' </PmtTpInf>' . $CrLf;
  1868. }
  1869. $XML_SEPA_INFO .= ' <ReqdExctnDt>'.dol_print_date($dateTime_ETAD, 'dayrfc').'</ReqdExctnDt>'.$CrLf;
  1870. $XML_SEPA_INFO .= ' <Dbtr>'.$CrLf;
  1871. $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf;
  1872. $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
  1873. $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
  1874. $addressline1 = strtr($configuration->global->MAIN_INFO_SOCIETE_ADDRESS, array(CHR(13) => ", ", CHR(10) => ""));
  1875. $addressline2 = strtr($configuration->global->MAIN_INFO_SOCIETE_ZIP.(($configuration->global->MAIN_INFO_SOCIETE_ZIP || ' '.$configuration->global->MAIN_INFO_SOCIETE_TOWN) ? ' ' : '').$configuration->global->MAIN_INFO_SOCIETE_TOWN, array(CHR(13) => ", ", CHR(10) => ""));
  1876. if ($addressline1) {
  1877. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline1), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1878. }
  1879. if ($addressline2) {
  1880. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_trunc(dol_string_unaccent($addressline2), 70, 'right', 'UTF-8', 1)).'</AdrLine>'.$CrLf;
  1881. }
  1882. $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
  1883. $XML_SEPA_INFO .= ' </Dbtr>'.$CrLf;
  1884. $XML_SEPA_INFO .= ' <DbtrAcct>'.$CrLf;
  1885. $XML_SEPA_INFO .= ' <Id>'.$CrLf;
  1886. $XML_SEPA_INFO .= ' <IBAN>'.preg_replace('/\s/', '', $this->emetteur_iban).'</IBAN>'.$CrLf;
  1887. $XML_SEPA_INFO .= ' </Id>'.$CrLf;
  1888. $XML_SEPA_INFO .= ' </DbtrAcct>'.$CrLf;
  1889. $XML_SEPA_INFO .= ' <DbtrAgt>'.$CrLf;
  1890. $XML_SEPA_INFO .= ' <FinInstnId>'.$CrLf;
  1891. $XML_SEPA_INFO .= ' <BIC>'.$this->emetteur_bic.'</BIC>'.$CrLf;
  1892. $XML_SEPA_INFO .= ' </FinInstnId>'.$CrLf;
  1893. $XML_SEPA_INFO .= ' </DbtrAgt>'.$CrLf;
  1894. /* $XML_SEPA_INFO .= ' <UltmtCdtr>'.$CrLf;
  1895. $XML_SEPA_INFO .= ' <Nm>'.dolEscapeXML(strtoupper(dol_string_unaccent($this->raison_sociale))).'</Nm>'.$CrLf;
  1896. $XML_SEPA_INFO .= ' <PstlAdr>'.$CrLf;
  1897. $XML_SEPA_INFO .= ' <Ctry>'.$country[1].'</Ctry>'.$CrLf;
  1898. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ADDRESS).'</AdrLine>'.$CrLf;
  1899. $XML_SEPA_INFO .= ' <AdrLine>'.dolEscapeXML(dol_string_unaccent($conf->global->MAIN_INFO_SOCIETE_ZIP.' '.$conf->global->MAIN_INFO_SOCIETE_TOWN).'</AdrLine>'.$CrLf;
  1900. $XML_SEPA_INFO .= ' </PstlAdr>'.$CrLf;
  1901. $XML_SEPA_INFO .= ' </UltmtCdtr>'.$CrLf;*/
  1902. $XML_SEPA_INFO .= ' <ChrgBr>SLEV</ChrgBr>'.$CrLf; // Field "Responsible of fees". Must be SLEV
  1903. /*$XML_SEPA_INFO .= ' <CdtrSchmeId>'.$CrLf;
  1904. $XML_SEPA_INFO .= ' <Id>'.$CrLf;
  1905. $XML_SEPA_INFO .= ' <PrvtId>'.$CrLf;
  1906. $XML_SEPA_INFO .= ' <Othr>'.$CrLf;
  1907. $XML_SEPA_INFO .= ' <Id>'.$this->emetteur_ics.'</Id>'.$CrLf;
  1908. $XML_SEPA_INFO .= ' <SchmeNm>'.$CrLf;
  1909. $XML_SEPA_INFO .= ' <Prtry>SEPA</Prtry>'.$CrLf;
  1910. $XML_SEPA_INFO .= ' </SchmeNm>'.$CrLf;
  1911. $XML_SEPA_INFO .= ' </Othr>'.$CrLf;
  1912. $XML_SEPA_INFO .= ' </PrvtId>'.$CrLf;
  1913. $XML_SEPA_INFO .= ' </Id>'.$CrLf;
  1914. $XML_SEPA_INFO .= ' </CdtrSchmeId>'.$CrLf;*/
  1915. }
  1916. } else {
  1917. fputs($this->file, 'INCORRECT EMETTEUR '.$XML_SEPA_INFO.$CrLf);
  1918. }
  1919. return $XML_SEPA_INFO;
  1920. }
  1921. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1922. /**
  1923. * Write end
  1924. *
  1925. * @param int $total total amount
  1926. * @return void
  1927. */
  1928. public function EnregTotal($total)
  1929. {
  1930. // phpcs:enable
  1931. fputs($this->file, "08");
  1932. fputs($this->file, "08"); // Prelevement ordinaire
  1933. fputs($this->file, " "); // Zone Reservee B2
  1934. fputs($this->file, $this->emetteur_ics); // ICS
  1935. // Reserve C1
  1936. fputs($this->file, substr(" ", 0, 12));
  1937. // Raison Sociale C2
  1938. fputs($this->file, substr(" ", 0, 24));
  1939. // D1
  1940. fputs($this->file, substr(" ", 0, 24));
  1941. // Zone Reservee D2
  1942. fputs($this->file, substr(" ", 0, 8));
  1943. // Code Guichet D3
  1944. fputs($this->file, substr(" ", 0, 5));
  1945. // Numero de compte D4
  1946. fputs($this->file, substr(" ", 0, 11));
  1947. // Zone E Montant
  1948. $montant = ($total * 100);
  1949. fputs($this->file, substr("000000000000000".$montant, -16));
  1950. // Zone Reservee F
  1951. fputs($this->file, substr(" ", 0, 31));
  1952. // Code etablissement
  1953. fputs($this->file, substr(" ", 0, 5));
  1954. // Zone Reservee F
  1955. fputs($this->file, substr(" ", 0, 5));
  1956. fputs($this->file, "\n");
  1957. }
  1958. /**
  1959. * Return status label of object
  1960. *
  1961. * @param int $mode 0=Label, 1=Picto + label, 2=Picto, 3=Label + Picto
  1962. * @return string Label
  1963. */
  1964. public function getLibStatut($mode = 0)
  1965. {
  1966. return $this->LibStatut($this->statut, $mode);
  1967. }
  1968. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1969. /**
  1970. * Return status label for a status
  1971. *
  1972. * @param int $status Id status
  1973. * @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
  1974. * @return string Label
  1975. */
  1976. public function LibStatut($status, $mode = 0)
  1977. {
  1978. // phpcs:enable
  1979. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  1980. global $langs;
  1981. //$langs->load("mymodule");
  1982. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
  1983. $this->labelStatus[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
  1984. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('StatusWaiting');
  1985. $this->labelStatusShort[self::STATUS_TRANSFERED] = $langs->transnoentitiesnoconv('StatusTrans');
  1986. if ($this->type == 'bank-transfer') {
  1987. $this->labelStatus[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
  1988. $this->labelStatusShort[self::STATUS_DEBITED] = $langs->transnoentitiesnoconv('StatusDebited');
  1989. } else {
  1990. $this->labelStatus[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
  1991. $this->labelStatusShort[self::STATUS_CREDITED] = $langs->transnoentitiesnoconv('StatusCredited');
  1992. }
  1993. }
  1994. $statusType = 'status1';
  1995. if ($status == self::STATUS_TRANSFERED) {
  1996. $statusType = 'status3';
  1997. }
  1998. if ($status == self::STATUS_CREDITED || $status == self::STATUS_DEBITED) {
  1999. $statusType = 'status6';
  2000. }
  2001. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  2002. }
  2003. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2004. /**
  2005. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2006. *
  2007. * @param User $user Objet user
  2008. * @param string $mode Mode 'direct_debit' or 'credit_transfer'
  2009. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  2010. */
  2011. public function load_board($user, $mode)
  2012. {
  2013. // phpcs:enable
  2014. global $conf, $langs;
  2015. if ($user->socid) {
  2016. return -1; // protection pour eviter appel par utilisateur externe
  2017. }
  2018. /*
  2019. if ($mode == 'direct_debit') {
  2020. $sql = "SELECT b.rowid, f.datedue as datefin";
  2021. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  2022. $sql .= " WHERE f.entity IN (".getEntity('facture').")";
  2023. $sql .= " AND f.total_ttc > 0";
  2024. } else {
  2025. $sql = "SELECT b.rowid, f.datedue as datefin";
  2026. $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
  2027. $sql .= " WHERE f.entity IN (".getEntity('facture_fourn').")";
  2028. $sql .= " AND f.total_ttc > 0";
  2029. }
  2030. $resql = $this->db->query($sql);
  2031. if ($resql) {
  2032. $langs->load("banks");
  2033. $now = dol_now();
  2034. $response = new WorkboardResponse();
  2035. if ($mode == 'direct_debit') {
  2036. $response->warning_delay = $conf->prelevement->warning_delay / 60 / 60 / 24;
  2037. $response->label = $langs->trans("PendingDirectDebitToComplete");
  2038. $response->labelShort = $langs->trans("PendingDirectDebitToCompleteShort");
  2039. $response->url = DOL_URL_ROOT.'/compta/prelevement/index.php?leftmenu=checks&mainmenu=bank';
  2040. } else {
  2041. $response->warning_delay = $conf->paymentbybanktransfer->warning_delay / 60 / 60 / 24;
  2042. $response->label = $langs->trans("PendingCreditTransferToComplete");
  2043. $response->labelShort = $langs->trans("PendingCreditTransferToCompleteShort");
  2044. $response->url = DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php?leftmenu=checks&mainmenu=bank';
  2045. }
  2046. $response->img = img_object('', "payment");
  2047. while ($obj = $this->db->fetch_object($resql)) {
  2048. $response->nbtodo++;
  2049. if ($this->db->jdate($obj->datefin) < ($now - $conf->withdraw->warning_delay)) {
  2050. $response->nbtodolate++;
  2051. }
  2052. }
  2053. $response->nbtodo = 0;
  2054. $response->nbtodolate = 0;
  2055. // Return workboard only if quantity is not 0
  2056. if ($response->nbtodo) {
  2057. return $response;
  2058. } else {
  2059. return 0;
  2060. }
  2061. } else {
  2062. dol_print_error($this->db);
  2063. $this->error = $this->db->error();
  2064. return -1;
  2065. }
  2066. */
  2067. return 0;
  2068. }
  2069. }