bonprelevement.class.php 83 KB

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