commoninvoice.class.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  1. <?php
  2. /* Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
  3. * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
  4. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file htdocs/core/class/commoninvoice.class.php
  21. * \ingroup core
  22. * \brief File of the superclass of invoices classes (customer and supplier)
  23. */
  24. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  25. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  26. /**
  27. * Superclass for invoices classes
  28. */
  29. abstract class CommonInvoice extends CommonObject
  30. {
  31. use CommonIncoterm;
  32. /**
  33. * Standard invoice
  34. */
  35. const TYPE_STANDARD = 0;
  36. /**
  37. * Replacement invoice
  38. */
  39. const TYPE_REPLACEMENT = 1;
  40. /**
  41. * Credit note invoice
  42. */
  43. const TYPE_CREDIT_NOTE = 2;
  44. /**
  45. * Deposit invoice
  46. */
  47. const TYPE_DEPOSIT = 3;
  48. /**
  49. * Proforma invoice.
  50. * @deprectad Remove this. A "proforma invoice" is an order with a look of invoice, not an invoice !
  51. */
  52. const TYPE_PROFORMA = 4;
  53. /**
  54. * Situation invoice
  55. */
  56. const TYPE_SITUATION = 5;
  57. /**
  58. * Draft status
  59. */
  60. const STATUS_DRAFT = 0;
  61. /**
  62. * Validated (need to be paid)
  63. */
  64. const STATUS_VALIDATED = 1;
  65. /**
  66. * Classified paid.
  67. * If paid partially, $this->close_code can be:
  68. * - CLOSECODE_DISCOUNTVAT
  69. * - CLOSECODE_BADDEBT
  70. * If paid completelly, this->close_code will be null
  71. */
  72. const STATUS_CLOSED = 2;
  73. /**
  74. * Classified abandoned and no payment done.
  75. * $this->close_code can be:
  76. * - CLOSECODE_BADDEBT
  77. * - CLOSECODE_ABANDONED
  78. * - CLOSECODE_REPLACED
  79. */
  80. const STATUS_ABANDONED = 3;
  81. public $totalpaid; // duplicate with sumpayed
  82. public $totaldeposits; // duplicate with sumdeposit
  83. public $totalcreditnotes; // duplicate with sumcreditnote
  84. public $sumpayed;
  85. public $sumpayed_multicurrency;
  86. public $sumdeposit;
  87. public $sumdeposit_multicurrency;
  88. public $sumcreditnote;
  89. public $sumcreditnote_multicurrency;
  90. public $remaintopay;
  91. /**
  92. * Return remain amount to pay. Property ->id and ->total_ttc must be set.
  93. * This does not include open direct debit requests.
  94. *
  95. * @param int $multicurrency Return multicurrency_amount instead of amount
  96. * @return float Remain of amount to pay
  97. */
  98. public function getRemainToPay($multicurrency = 0)
  99. {
  100. $alreadypaid = 0.0;
  101. $alreadypaid += $this->getSommePaiement($multicurrency);
  102. $alreadypaid += $this->getSumDepositsUsed($multicurrency);
  103. $alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
  104. $remaintopay = price2num($this->total_ttc - $alreadypaid, 'MT');
  105. if ($this->statut == self::STATUS_CLOSED && $this->close_code == 'discount_vat') { // If invoice closed with discount for anticipated payment
  106. $remaintopay = 0.0;
  107. }
  108. return $remaintopay;
  109. }
  110. /**
  111. * Return amount of payments already done. This must include ONLY the record into the payment table.
  112. * Payments dones using discounts, credit notes, etc are not included.
  113. *
  114. * @param int $multicurrency Return multicurrency_amount instead of amount
  115. * @return float|int Amount of payment already done, <0 and set ->error if KO
  116. */
  117. public function getSommePaiement($multicurrency = 0)
  118. {
  119. $table = 'paiement_facture';
  120. $field = 'fk_facture';
  121. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  122. $table = 'paiementfourn_facturefourn';
  123. $field = 'fk_facturefourn';
  124. }
  125. $sql = "SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount";
  126. $sql .= " FROM ".$this->db->prefix().$table;
  127. $sql .= " WHERE ".$field." = ".((int) $this->id);
  128. dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG);
  129. $resql = $this->db->query($sql);
  130. if ($resql) {
  131. $obj = $this->db->fetch_object($resql);
  132. $this->db->free($resql);
  133. if ($obj) {
  134. if ($multicurrency) {
  135. $this->sumpayed_multicurrency = $obj->multicurrency_amount;
  136. return (float) $obj->multicurrency_amount;
  137. } else {
  138. $this->sumpayed = $obj->amount;
  139. return (float) $obj->amount;
  140. }
  141. } else {
  142. return 0;
  143. }
  144. } else {
  145. $this->error = $this->db->lasterror();
  146. return -1;
  147. }
  148. }
  149. /**
  150. * Return amount (with tax) of all deposits invoices used by invoice.
  151. * Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on for sale invoices (not recommended),
  152. * of FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS is on for purchase invoices (not recommended).
  153. *
  154. * @param int $multicurrency Return multicurrency_amount instead of amount
  155. * @return float <0 and set ->error if KO, Sum of deposits amount otherwise
  156. */
  157. public function getSumDepositsUsed($multicurrency = 0)
  158. {
  159. /*if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  160. // FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS was never supported for purchase invoice, so we can return 0 with no need of SQL for this case.
  161. return 0.0;
  162. }*/
  163. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  164. $discountstatic = new DiscountAbsolute($this->db);
  165. $result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
  166. if ($result >= 0) {
  167. if ($multicurrency) {
  168. $this->sumdeposit_multicurrency = $result;
  169. } else {
  170. $this->sumdeposit = $result;
  171. }
  172. return $result;
  173. } else {
  174. $this->error = $discountstatic->error;
  175. return -1;
  176. }
  177. }
  178. /**
  179. * Return amount (with tax) of all credit notes invoices + excess received used by invoice
  180. *
  181. * @param int $multicurrency Return multicurrency_amount instead of amount
  182. * @return float <0 and set ->error if KO, Sum of credit notes and deposits amount otherwise
  183. */
  184. public function getSumCreditNotesUsed($multicurrency = 0)
  185. {
  186. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  187. $discountstatic = new DiscountAbsolute($this->db);
  188. $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
  189. if ($result >= 0) {
  190. if ($multicurrency) {
  191. $this->sumcreditnote_multicurrency = $result;
  192. } else {
  193. $this->sumcreditnote = $result;
  194. }
  195. return $result;
  196. } else {
  197. $this->error = $discountstatic->error;
  198. return -1;
  199. }
  200. }
  201. /**
  202. * Return amount (with tax) of all converted amount for this credit note
  203. *
  204. * @param int $multicurrency Return multicurrency_amount instead of amount
  205. * @return float <0 if KO, Sum of credit notes and deposits amount otherwise
  206. */
  207. public function getSumFromThisCreditNotesNotUsed($multicurrency = 0)
  208. {
  209. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  210. $discountstatic = new DiscountAbsolute($this->db);
  211. $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
  212. if ($result >= 0) {
  213. return $result;
  214. } else {
  215. $this->error = $discountstatic->error;
  216. return -1;
  217. }
  218. }
  219. /**
  220. * Returns array of credit note ids from the invoice
  221. *
  222. * @return array Array of credit note ids
  223. */
  224. public function getListIdAvoirFromInvoice()
  225. {
  226. $idarray = array();
  227. $sql = "SELECT rowid";
  228. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  229. $sql .= " WHERE fk_facture_source = ".((int) $this->id);
  230. $sql .= " AND type = 2";
  231. $resql = $this->db->query($sql);
  232. if ($resql) {
  233. $num = $this->db->num_rows($resql);
  234. $i = 0;
  235. while ($i < $num) {
  236. $row = $this->db->fetch_row($resql);
  237. $idarray[] = $row[0];
  238. $i++;
  239. }
  240. } else {
  241. dol_print_error($this->db);
  242. }
  243. return $idarray;
  244. }
  245. /**
  246. * Returns the id of the invoice that replaces it
  247. *
  248. * @param string $option status filter ('', 'validated', ...)
  249. * @return int <0 si KO, 0 if no invoice replaces it, id of invoice otherwise
  250. */
  251. public function getIdReplacingInvoice($option = '')
  252. {
  253. $sql = "SELECT rowid";
  254. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  255. $sql .= " WHERE fk_facture_source = ".((int) $this->id);
  256. $sql .= " AND type < 2";
  257. if ($option == 'validated') {
  258. $sql .= ' AND fk_statut = 1';
  259. }
  260. // PROTECTION BAD DATA
  261. // In case the database is corrupted and there is a valid replectement invoice
  262. // and another no, priority is given to the valid one.
  263. // Should not happen (unless concurrent access and 2 people have created a
  264. // replacement invoice for the same invoice at the same time)
  265. $sql .= " ORDER BY fk_statut DESC";
  266. $resql = $this->db->query($sql);
  267. if ($resql) {
  268. $obj = $this->db->fetch_object($resql);
  269. if ($obj) {
  270. // If there is any
  271. return $obj->rowid;
  272. } else {
  273. // If no invoice replaces it
  274. return 0;
  275. }
  276. } else {
  277. return -1;
  278. }
  279. }
  280. /**
  281. * Return list of payments
  282. *
  283. * @param string $filtertype 1 to filter on type of payment == 'PRE'
  284. * @return array Array with list of payments
  285. */
  286. public function getListOfPayments($filtertype = '')
  287. {
  288. $retarray = array();
  289. $table = 'paiement_facture';
  290. $table2 = 'paiement';
  291. $field = 'fk_facture';
  292. $field2 = 'fk_paiement';
  293. $field3 = ', p.ref_ext';
  294. $sharedentity = 'facture';
  295. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  296. $table = 'paiementfourn_facturefourn';
  297. $table2 = 'paiementfourn';
  298. $field = 'fk_facturefourn';
  299. $field2 = 'fk_paiementfourn';
  300. $field3 = '';
  301. $sharedentity = 'facture_fourn';
  302. }
  303. $sql = "SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code".$field3;
  304. $sql .= " FROM ".$this->db->prefix().$table." as pf, ".$this->db->prefix().$table2." as p, ".$this->db->prefix()."c_paiement as t";
  305. $sql .= " WHERE pf.".$field." = ".((int) $this->id);
  306. $sql .= " AND pf.".$field2." = p.rowid";
  307. $sql .= ' AND p.fk_paiement = t.id';
  308. $sql .= ' AND p.entity IN ('.getEntity($sharedentity).')';
  309. if ($filtertype) {
  310. $sql .= " AND t.code='PRE'";
  311. }
  312. dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
  313. $resql = $this->db->query($sql);
  314. if ($resql) {
  315. $num = $this->db->num_rows($resql);
  316. $i = 0;
  317. while ($i < $num) {
  318. $obj = $this->db->fetch_object($resql);
  319. $tmp = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
  320. if (!empty($field3)) {
  321. $tmp['ref_ext'] = $obj->ref_ext;
  322. }
  323. $retarray[] = $tmp;
  324. $i++;
  325. }
  326. $this->db->free($resql);
  327. //look for credit notes and discounts and deposits
  328. $sql = '';
  329. if ($this->element == 'facture' || $this->element == 'invoice') {
  330. $sql = "SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type";
  331. $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture as f';
  332. $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.((int) $this->id);
  333. $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is set)
  334. } elseif ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  335. $sql = "SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type";
  336. $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture_fourn as f';
  337. $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.((int) $this->id);
  338. $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS is set)
  339. }
  340. if ($sql) {
  341. $resql = $this->db->query($sql);
  342. if ($resql) {
  343. $num = $this->db->num_rows($resql);
  344. $i = 0;
  345. while ($i < $num) {
  346. $obj = $this->db->fetch_object($resql);
  347. if ($multicurrency) {
  348. $retarray[] = array('amount'=>$obj->multicurrency_amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'0', 'ref'=>$obj->ref);
  349. } else {
  350. $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'', 'ref'=>$obj->ref);
  351. }
  352. $i++;
  353. }
  354. } else {
  355. $this->error = $this->db->lasterror();
  356. dol_print_error($this->db);
  357. return array();
  358. }
  359. $this->db->free($resql);
  360. }
  361. return $retarray;
  362. } else {
  363. $this->error = $this->db->lasterror();
  364. dol_print_error($this->db);
  365. return array();
  366. }
  367. }
  368. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  369. /**
  370. * Return if an invoice can be deleted
  371. * Rule is:
  372. * If invoice is draft and has a temporary ref -> yes (1)
  373. * If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on -> no (0)
  374. * If invoice is dispatched in bookkeeping -> no (-1)
  375. * If invoice has a definitive ref, is not last and INVOICE_CAN_ALWAYS_BE_REMOVED off -> no (-2)
  376. * If invoice not last in a cycle -> no (-3)
  377. * If there is payment -> no (-4)
  378. * Otherwise -> yes (2)
  379. *
  380. * @return int <=0 if no, >0 if yes
  381. */
  382. public function is_erasable()
  383. {
  384. // phpcs:enable
  385. global $conf;
  386. // We check if invoice is a temporary number (PROVxxxx)
  387. $tmppart = substr($this->ref, 1, 4);
  388. if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') { // If draft invoice and ref not yet defined
  389. return 1;
  390. }
  391. if (!empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) {
  392. return 0;
  393. }
  394. // If not a draft invoice and not temporary invoice
  395. if ($tmppart !== 'PROV') {
  396. $ventilExportCompta = $this->getVentilExportCompta();
  397. if ($ventilExportCompta != 0) {
  398. return -1;
  399. }
  400. // Get last number of validated invoice
  401. if ($this->element != 'invoice_supplier') {
  402. if (empty($this->thirdparty)) {
  403. $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
  404. }
  405. $maxref = $this->getNextNumRef($this->thirdparty, 'last');
  406. // If there is no invoice into the reset range and not already dispatched, we can delete
  407. // If invoice to delete is last one and not already dispatched, we can delete
  408. if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) {
  409. return -2;
  410. }
  411. // TODO If there is payment in bookkeeping, check payment is not dispatched in accounting
  412. // ...
  413. if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) {
  414. $last = $this->is_last_in_cycle();
  415. if (!$last) {
  416. return -3;
  417. }
  418. }
  419. }
  420. }
  421. // Test if there is at least one payment. If yes, refuse to delete.
  422. if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) {
  423. return -4;
  424. }
  425. return 2;
  426. }
  427. /**
  428. * Return if an invoice was dispatched into bookkeeping
  429. *
  430. * @return int <0 if KO, 0=no, 1=yes
  431. */
  432. public function getVentilExportCompta()
  433. {
  434. $alreadydispatched = 0;
  435. $type = 'customer_invoice';
  436. if ($this->element == 'invoice_supplier') {
  437. $type = 'supplier_invoice';
  438. }
  439. $sql = " SELECT COUNT(ab.rowid) as nb FROM ".$this->db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
  440. $resql = $this->db->query($sql);
  441. if ($resql) {
  442. $obj = $this->db->fetch_object($resql);
  443. if ($obj) {
  444. $alreadydispatched = $obj->nb;
  445. }
  446. } else {
  447. $this->error = $this->db->lasterror();
  448. return -1;
  449. }
  450. if ($alreadydispatched) {
  451. return 1;
  452. }
  453. return 0;
  454. }
  455. /**
  456. * Return label of type of invoice
  457. *
  458. * @param int $withbadge 1=Add span for badge css, 2=Add span and show short label
  459. * @return string Label of type of invoice
  460. */
  461. public function getLibType($withbadge = 0)
  462. {
  463. global $langs;
  464. $labellong = "Unknown";
  465. if ($this->type == CommonInvoice::TYPE_STANDARD) {
  466. $labellong = "InvoiceStandard";
  467. $labelshort = "InvoiceStandardShort";
  468. } elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) {
  469. $labellong = "InvoiceReplacement";
  470. $labelshort = "InvoiceReplacementShort";
  471. } elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) {
  472. $labellong = "InvoiceAvoir";
  473. $labelshort = "CreditNote";
  474. } elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) {
  475. $labellong = "InvoiceDeposit";
  476. $labelshort = "Deposit";
  477. } elseif ($this->type == CommonInvoice::TYPE_PROFORMA) {
  478. $labellong = "InvoiceProForma"; // Not used.
  479. $labelshort = "ProForma";
  480. } elseif ($this->type == CommonInvoice::TYPE_SITUATION) {
  481. $labellong = "InvoiceSituation";
  482. $labelshort = "Situation";
  483. }
  484. $out = '';
  485. if ($withbadge) {
  486. $out .= '<span class="badgeneutral" title="'.dol_escape_htmltag($langs->trans($labellong)).'">';
  487. }
  488. $out .= $langs->trans($withbadge == 2 ? $labelshort : $labellong);
  489. if ($withbadge) {
  490. $out .= '</span>';
  491. }
  492. return $out;
  493. }
  494. /**
  495. * Return label of object status
  496. *
  497. * @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
  498. * @param integer $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise)
  499. * @return string Label of status
  500. */
  501. public function getLibStatut($mode = 0, $alreadypaid = -1)
  502. {
  503. return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
  504. }
  505. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  506. /**
  507. * Return label of a status
  508. *
  509. * @param int $paye Status field paye
  510. * @param int $status Id status
  511. * @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
  512. * @param integer $alreadypaid 0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, -1 otherwise)
  513. * @param int $type Type invoice. If -1, we use $this->type
  514. * @return string Label of status
  515. */
  516. public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1)
  517. {
  518. // phpcs:enable
  519. global $langs, $hookmanager;
  520. $langs->load('bills');
  521. if ($type == -1) {
  522. $type = $this->type;
  523. }
  524. $statusType = 'status0';
  525. $prefix = 'Short';
  526. if (!$paye) {
  527. if ($status == 0) {
  528. $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
  529. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
  530. } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
  531. if ($status == 3) {
  532. $labelStatus = $langs->transnoentitiesnoconv('BillStatusCanceled');
  533. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusCanceled');
  534. } else {
  535. $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
  536. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
  537. }
  538. $statusType = 'status5';
  539. } elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
  540. $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
  541. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
  542. $statusType = 'status9';
  543. } elseif ($alreadypaid == 0) {
  544. $labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
  545. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
  546. $statusType = 'status1';
  547. } else {
  548. $labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
  549. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
  550. $statusType = 'status3';
  551. }
  552. } else {
  553. $statusType = 'status6';
  554. if ($type == self::TYPE_CREDIT_NOTE) {
  555. $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
  556. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
  557. } elseif ($type == self::TYPE_DEPOSIT) {
  558. $labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
  559. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
  560. } else {
  561. $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
  562. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
  563. }
  564. }
  565. $parameters = array(
  566. 'status' => $status,
  567. 'mode' => $mode,
  568. 'paye' => $paye,
  569. 'alreadypaid' => $alreadypaid,
  570. 'type' => $type
  571. );
  572. $reshook = $hookmanager->executeHooks('LibStatut', $parameters, $this); // Note that $action and $object may have been modified by hook
  573. if ($reshook > 0) {
  574. return $hookmanager->resPrint;
  575. }
  576. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  577. }
  578. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  579. /**
  580. * Returns an invoice payment deadline based on the invoice settlement
  581. * conditions and billing date.
  582. *
  583. * @param integer $cond_reglement Condition of payment (code or id) to use. If 0, we use current condition.
  584. * @return integer Date limite de reglement si ok, <0 si ko
  585. */
  586. public function calculate_date_lim_reglement($cond_reglement = 0)
  587. {
  588. // phpcs:enable
  589. if (!$cond_reglement) {
  590. $cond_reglement = $this->cond_reglement_code;
  591. }
  592. if (!$cond_reglement) {
  593. $cond_reglement = $this->cond_reglement_id;
  594. }
  595. $cdr_nbjour = 0;
  596. $cdr_type = 0;
  597. $cdr_decalage = 0;
  598. $sqltemp = "SELECT c.type_cdr, c.nbjour, c.decalage";
  599. $sqltemp .= " FROM ".$this->db->prefix()."c_payment_term as c";
  600. if (is_numeric($cond_reglement)) {
  601. $sqltemp .= " WHERE c.rowid=".((int) $cond_reglement);
  602. } else {
  603. $sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
  604. $sqltemp .= " AND c.code = '".$this->db->escape($cond_reglement)."'";
  605. }
  606. dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
  607. $resqltemp = $this->db->query($sqltemp);
  608. if ($resqltemp) {
  609. if ($this->db->num_rows($resqltemp)) {
  610. $obj = $this->db->fetch_object($resqltemp);
  611. $cdr_nbjour = $obj->nbjour;
  612. $cdr_type = $obj->type_cdr;
  613. $cdr_decalage = $obj->decalage;
  614. }
  615. } else {
  616. $this->error = $this->db->error();
  617. return -1;
  618. }
  619. $this->db->free($resqltemp);
  620. /* Definition de la date limite */
  621. // 0 : adding the number of days
  622. if ($cdr_type == 0) {
  623. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  624. $datelim += ($cdr_decalage * 3600 * 24);
  625. } elseif ($cdr_type == 1) {
  626. // 1 : application of the "end of the month" rule
  627. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  628. $mois = date('m', $datelim);
  629. $annee = date('Y', $datelim);
  630. if ($mois == 12) {
  631. $mois = 1;
  632. $annee += 1;
  633. } else {
  634. $mois += 1;
  635. }
  636. // We move at the beginning of the next month, and we take a day off
  637. $datelim = dol_mktime(12, 0, 0, $mois, 1, $annee);
  638. $datelim -= (3600 * 24);
  639. $datelim += ($cdr_decalage * 3600 * 24);
  640. } elseif ($cdr_type == 2 && !empty($cdr_decalage)) {
  641. // 2 : application of the rule, the N of the current or next month
  642. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  643. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  644. $date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes
  645. $date_lim_current = dol_mktime(0, 0, 0, date('m', $datelim), $cdr_decalage, date('Y', $datelim)); // Sans les heures minutes et secondes
  646. $date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm'); // Add 1 month
  647. $diff = $date_piece - $date_lim_current;
  648. if ($diff < 0) {
  649. $datelim = $date_lim_current;
  650. } else {
  651. $datelim = $date_lim_next;
  652. }
  653. } else {
  654. return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
  655. }
  656. return $datelim;
  657. }
  658. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  659. /**
  660. * Create a withdrawal request for a direct debit order or a credit transfer order.
  661. * Use the remain to pay excluding all existing open direct debit requests.
  662. *
  663. * @param User $fuser User asking the direct debit transfer
  664. * @param float $amount Amount we request direct debit for
  665. * @param string $type 'direct-debit' or 'bank-transfer'
  666. * @param string $sourcetype Source ('facture' or 'supplier_invoice')
  667. * @return int <0 if KO, >0 if OK
  668. */
  669. public function demande_prelevement($fuser, $amount = 0, $type = 'direct-debit', $sourcetype = 'facture')
  670. {
  671. // phpcs:enable
  672. global $conf;
  673. $error = 0;
  674. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  675. if ($this->statut > self::STATUS_DRAFT && $this->paye == 0) {
  676. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  677. $bac = new CompanyBankAccount($this->db);
  678. $bac->fetch(0, $this->socid);
  679. $sql = "SELECT count(*)";
  680. $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
  681. if ($type == 'bank-transfer') {
  682. $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
  683. } else {
  684. $sql .= " WHERE fk_facture = ".((int) $this->id);
  685. }
  686. $sql .= " AND ext_payment_id IS NULL"; // To exclude record done for some online payments
  687. $sql .= " AND traite = 0";
  688. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  689. $resql = $this->db->query($sql);
  690. if ($resql) {
  691. $row = $this->db->fetch_row($resql);
  692. if ($row[0] == 0) {
  693. $now = dol_now();
  694. $totalpaid = $this->getSommePaiement();
  695. $totalcreditnotes = $this->getSumCreditNotesUsed();
  696. $totaldeposits = $this->getSumDepositsUsed();
  697. //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
  698. // We can also use bcadd to avoid pb with floating points
  699. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  700. //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
  701. //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  702. if (empty($amount)) {
  703. $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  704. }
  705. if (is_numeric($amount) && $amount != 0) {
  706. $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_demande(';
  707. if ($type == 'bank-transfer') {
  708. $sql .= 'fk_facture_fourn, ';
  709. } else {
  710. $sql .= 'fk_facture, ';
  711. }
  712. $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, entity)';
  713. $sql .= " VALUES (".((int) $this->id);
  714. $sql .= ", ".((float) price2num($amount));
  715. $sql .= ", '".$this->db->idate($now)."'";
  716. $sql .= ", ".((int) $fuser->id);
  717. $sql .= ", '".$this->db->escape($bac->code_banque)."'";
  718. $sql .= ", '".$this->db->escape($bac->code_guichet)."'";
  719. $sql .= ", '".$this->db->escape($bac->number)."'";
  720. $sql .= ", '".$this->db->escape($bac->cle_rib)."'";
  721. $sql .= ", '".$this->db->escape($sourcetype)."'";
  722. $sql .= ", ".((int) $conf->entity);
  723. $sql .= ")";
  724. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  725. $resql = $this->db->query($sql);
  726. if (!$resql) {
  727. $this->error = $this->db->lasterror();
  728. dol_syslog(get_class($this).'::demandeprelevement Erreur');
  729. $error++;
  730. }
  731. } else {
  732. $this->error = 'WithdrawRequestErrorNilAmount';
  733. dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
  734. $error++;
  735. }
  736. if (!$error) {
  737. // Force payment mode of invoice to withdraw
  738. $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
  739. if ($payment_mode_id > 0) {
  740. $result = $this->setPaymentMethods($payment_mode_id);
  741. }
  742. }
  743. if ($error) {
  744. return -1;
  745. }
  746. return 1;
  747. } else {
  748. $this->error = "A request already exists";
  749. dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
  750. return 0;
  751. }
  752. } else {
  753. $this->error = $this->db->error();
  754. dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
  755. return -2;
  756. }
  757. } else {
  758. $this->error = "Status of invoice does not allow this";
  759. dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
  760. return -3;
  761. }
  762. }
  763. /**
  764. * Create a withdrawal request for a direct debit order or a credit transfer order.
  765. * Use the remain to pay excluding all existing open direct debit requests.
  766. *
  767. * @param User $fuser User asking the direct debit transfer
  768. * @param int $did ID of payment request
  769. * @param string $type 'direct-debit' or 'bank-transfer'
  770. * @param string $sourcetype Source ('facture' or 'supplier_invoice')
  771. * @return int <0 if KO, >0 if OK
  772. */
  773. public function makeStripeSepaRequest($fuser, $did = 0, $type = 'direct-debit', $sourcetype = 'facture')
  774. {
  775. global $conf, $mysoc, $user, $langs;
  776. if (empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) {
  777. //exit
  778. return 0;
  779. }
  780. $error = 0;
  781. dol_syslog(get_class($this)."::makeStripeSepaRequest 0", LOG_DEBUG);
  782. if ($this->statut > self::STATUS_DRAFT && $this->paye == 0) {
  783. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  784. $bac = new CompanyBankAccount($this->db);
  785. $result = $bac->fetch(0, $this->socid, 1, 'ban');
  786. if ($result <= 0 || empty($bac->id)) {
  787. $this->error = $langs->trans("ThirdpartyHasNoDefaultBanAccount");
  788. $this->errors[] = $this->error;
  789. dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error);
  790. return -1;
  791. }
  792. $sql = "SELECT rowid, date_demande, amount, fk_facture, fk_facture_fourn";
  793. $sql .= " FROM ".$this->db->prefix()."prelevement_demande";
  794. $sql .= " WHERE rowid = ".((int) $did);
  795. dol_syslog(get_class($this)."::makeStripeSepaRequest 1", LOG_DEBUG);
  796. $resql = $this->db->query($sql);
  797. if ($resql) {
  798. $obj = $this->db->fetch_object($resql);
  799. if (!$obj) {
  800. dol_print_error($this->db, 'CantFindRequestWithId');
  801. return -2;
  802. }
  803. //
  804. $amount = $obj->amount;
  805. $now = dol_now();
  806. $totalpaye = $this->getSommePaiement();
  807. $totalcreditnotes = $this->getSumCreditNotesUsed();
  808. $totaldeposits = $this->getSumDepositsUsed();
  809. //print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
  810. // We can also use bcadd to avoid pb with floating points
  811. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  812. //$resteapayer=bcadd($this->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  813. //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  814. $amounttocheck = price2num($this->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  815. // TODO We can compare $amount and $amounttocheck
  816. if (is_numeric($amount) && $amount != 0) {
  817. require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
  818. $companypaymentmode = new CompanyPaymentMode($this->db);
  819. $companypaymentmode->fetch($bac->id);
  820. // Start code for Stripe
  821. $service = 'StripeTest';
  822. $servicestatus = 0;
  823. if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
  824. $service = 'StripeLive';
  825. $servicestatus = 1;
  826. }
  827. dol_syslog("makeStripeSepaRequest amount = ".$amount." service=" . $service . " servicestatus=" . $servicestatus . " thirdparty_id=" . $this->socid . " companypaymentmode=" . $companypaymentmode->id);
  828. $this->stripechargedone = 0;
  829. $this->stripechargeerror = 0;
  830. $now = dol_now();
  831. $currency = $conf->currency;
  832. global $stripearrayofkeysbyenv;
  833. global $savstripearrayofkeysbyenv;
  834. $errorforinvoice = 0; // We reset the $errorforinvoice at each invoice loop
  835. $this->fetch_thirdparty();
  836. dol_syslog("--- Process invoice thirdparty_id=" . $this->id . ", thirdparty_name=" . $this->thirdparty->name . " id=" . $this->id . ", ref=" . $this->ref . ", datef=" . dol_print_date($this->date, 'dayhourlog'), LOG_DEBUG);
  837. $alreadypayed = $this->getSommePaiement();
  838. $amount_credit_notes_included = $this->getSumCreditNotesUsed();
  839. $amounttopay = $this->total_ttc - $alreadypayed - $amount_credit_notes_included;
  840. // Correct the amount according to unit of currency
  841. // See https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
  842. $arrayzerounitcurrency = ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF'];
  843. $amountstripe = $amounttopay;
  844. if (!in_array($currency, $arrayzerounitcurrency)) {
  845. $amountstripe = $amountstripe * 100;
  846. }
  847. if ($amountstripe > 0) {
  848. try {
  849. //var_dump($companypaymentmode);
  850. dol_syslog("We will try to pay with companypaymentmodeid=" . $companypaymentmode->id . " stripe_card_ref=" . $companypaymentmode->stripe_card_ref . " mode=" . $companypaymentmode->status, LOG_DEBUG);
  851. $thirdparty = new Societe($this->db);
  852. $resultthirdparty = $thirdparty->fetch($this->socid);
  853. include_once DOL_DOCUMENT_ROOT . '/stripe/class/stripe.class.php'; // This include the include of htdocs/stripe/config.php
  854. // So it inits or erases the $stripearrayofkeysbyenv
  855. $stripe = new Stripe($this->db);
  856. if (empty($savstripearrayofkeysbyenv)) {
  857. $savstripearrayofkeysbyenv = $stripearrayofkeysbyenv;
  858. }
  859. dol_syslog("makeStripeSepaRequest Current Stripe environment is " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key']);
  860. dol_syslog("makeStripeSepaRequest Current Saved Stripe environment is " . $savstripearrayofkeysbyenv[$servicestatus]['publishable_key']);
  861. $foundalternativestripeaccount = '';
  862. // Force stripe to another value (by default this value is empty)
  863. if (!empty($thirdparty->array_options['options_stripeaccount'])) {
  864. dol_syslog("makeStripeSepaRequest The thirdparty id=" . $thirdparty->id . " has a dedicated Stripe Account, so we switch to it.");
  865. $tmparray = explode('@', $thirdparty->array_options['options_stripeaccount']);
  866. if (!empty($tmparray[1])) {
  867. $tmparray2 = explode(':', $tmparray[1]);
  868. if (!empty($tmparray2[3])) {
  869. $stripearrayofkeysbyenv = [
  870. 0 => [
  871. "publishable_key" => $tmparray2[0],
  872. "secret_key" => $tmparray2[1]
  873. ],
  874. 1 => [
  875. "publishable_key" => $tmparray2[2],
  876. "secret_key" => $tmparray2[3]
  877. ]
  878. ];
  879. $stripearrayofkeys = $stripearrayofkeysbyenv[$servicestatus];
  880. \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
  881. $foundalternativestripeaccount = $tmparray[0]; // Store the customer id
  882. dol_syslog("We use now customer=" . $foundalternativestripeaccount . " publishable_key=" . $stripearrayofkeys['publishable_key'], LOG_DEBUG);
  883. }
  884. }
  885. if (!$foundalternativestripeaccount) {
  886. $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv;
  887. $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus];
  888. \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
  889. dol_syslog("We found a bad value for Stripe Account for thirdparty id=" . $thirdparty->id . ", so we ignore it and keep using the global one, so " . $stripearrayofkeys['publishable_key'], LOG_WARNING);
  890. }
  891. } else {
  892. $stripearrayofkeysbyenv = $savstripearrayofkeysbyenv;
  893. $stripearrayofkeys = $savstripearrayofkeysbyenv[$servicestatus];
  894. \Stripe\Stripe::setApiKey($stripearrayofkeys['secret_key']);
  895. dol_syslog("The thirdparty id=" . $thirdparty->id . " has no dedicated Stripe Account, so we use global one, so " . json_encode($stripearrayofkeys), LOG_DEBUG);
  896. }
  897. dol_syslog("makeStripeSepaRequest get stripe account", LOG_DEBUG);
  898. $stripeacc = $stripe->getStripeAccount($service, $this->socid); // Get Stripe OAuth connect account if it exists (no network access here)
  899. dol_syslog("makeStripeSepaRequest get stripe account return " . json_encode($stripeacc), LOG_DEBUG);
  900. if ($foundalternativestripeaccount) {
  901. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  902. $customer = \Stripe\Customer::retrieve(['id' => "$foundalternativestripeaccount", 'expand[]' => 'sources']);
  903. } else {
  904. $customer = \Stripe\Customer::retrieve(['id' => "$foundalternativestripeaccount", 'expand[]' => 'sources'], ["stripe_account" => $stripeacc]);
  905. }
  906. } else {
  907. $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
  908. if (empty($customer) && !empty($stripe->error)) {
  909. $this->errors[] = $stripe->error;
  910. }
  911. /*if (!empty($customer) && empty($customer->sources)) {
  912. $customer = null;
  913. $this->errors[] = '\Stripe\Customer::retrieve did not returned the sources';
  914. }*/
  915. }
  916. // $nbhoursbetweentries = (empty($conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES) ? 49 : $conf->global->SELLYOURSAAS_NBHOURSBETWEENTRIES); // Must have more that 48 hours + 1 between each try (so 1 try every 3 daily batch)
  917. // $nbdaysbeforeendoftries = (empty($conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES) ? 35 : $conf->global->SELLYOURSAAS_NBDAYSBEFOREENDOFTRIES);
  918. $labeltouse = '';
  919. $postactionmessages = [];
  920. if ($resultthirdparty > 0 && !empty($customer)) {
  921. if (!$error && !empty($this->array_options['options_delayautopayment']) && $this->array_options['options_delayautopayment'] > $now && empty($calledinmyaccountcontext)) {
  922. $errmsg = 'Payment try was canceled (invoice qualified by the automatic payment was delayed after the ' . dol_print_date($this->array_options['options_delayautopayment'], 'day') . ')';
  923. dol_syslog($errmsg, LOG_DEBUG);
  924. $error++;
  925. $errorforinvoice++;
  926. $this->errors[] = $errmsg;
  927. }
  928. if (!$error) { // Payment was not canceled
  929. //erics card or sepa ?
  930. $sepaMode = false;
  931. if ($companypaymentmode->type == 'ban') {
  932. $sepaMode = true;
  933. $stripecard = $stripe->sepaStripe($customer, $companypaymentmode, $stripeacc, $servicestatus, 0);
  934. } else {
  935. $stripecard = $stripe->cardStripe($customer, $companypaymentmode, $stripeacc, $servicestatus, 0);
  936. }
  937. if ($stripecard) { // Can be card_... (old mode) or pm_... (new mode)
  938. $FULLTAG = 'INV=' . $this->id . '-CUS=' . $thirdparty->id;
  939. $description = 'Stripe payment from doTakePaymentStripeForThirdparty: ' . $FULLTAG . ' ref=' . $this->ref;
  940. $stripefailurecode = '';
  941. $stripefailuremessage = '';
  942. $stripefailuredeclinecode = '';
  943. if (preg_match('/^card_/', $stripecard->id)) { // Using old method
  944. dol_syslog("* Create charge on card " . $stripecard->id . ", amountstripe=" . $amountstripe . ", FULLTAG=" . $FULLTAG, LOG_DEBUG);
  945. $ipaddress = getUserRemoteIP();
  946. $charge = null; // Force reset of $charge, so, if already set from a previous fetch, it will be empty even if there is an exception at next step
  947. try {
  948. $charge = \Stripe\Charge::create([
  949. 'amount' => price2num($amountstripe, 'MU'),
  950. 'currency' => $currency,
  951. 'capture' => true, // Charge immediatly
  952. 'description' => $description,
  953. 'metadata' => ["FULLTAG" => $FULLTAG, 'Recipient' => $mysoc->name, 'dol_version' => DOL_VERSION, 'dol_entity' => $conf->entity, 'ipaddress' => $ipaddress],
  954. 'customer' => $customer->id,
  955. //'customer' => 'bidon_to_force_error', // To use to force a stripe error
  956. 'source' => $stripecard,
  957. 'statement_descriptor' => dol_trunc('INV=' . $this->id, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
  958. ]);
  959. } catch (\Stripe\Error\Card $e) {
  960. // Since it's a decline, Stripe_CardError will be caught
  961. $body = $e->getJsonBody();
  962. $err = $body['error'];
  963. $stripefailurecode = $err['code'];
  964. $stripefailuremessage = $err['message'];
  965. $stripefailuredeclinecode = $err['decline_code'];
  966. } catch (Exception $e) {
  967. $stripefailurecode = 'UnknownChargeError';
  968. $stripefailuremessage = $e->getMessage();
  969. }
  970. } else { // Using new SCA method
  971. if ($sepaMode) {
  972. dol_syslog("* Create payment on SEPA " . $stripecard->id . ", amounttopay=" . $amounttopay . ", amountstripe=" . $amountstripe . ", FULLTAG=" . $FULLTAG, LOG_DEBUG);
  973. } else {
  974. dol_syslog("* Create payment on card " . $stripecard->id . ", amounttopay=" . $amounttopay . ", amountstripe=" . $amountstripe . ", FULLTAG=" . $FULLTAG, LOG_DEBUG);
  975. }
  976. // Create payment intent and charge payment (confirmnow = true)
  977. $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $invoice, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1);
  978. $charge = new stdClass();
  979. //erics add processing sepa is like success ?
  980. if ($paymentintent->status === 'succeeded' || $paymentintent->status === 'processing') {
  981. $charge->status = 'ok';
  982. $charge->id = $paymentintent->id;
  983. $charge->customer = $customer->id;
  984. } elseif ($paymentintent->status === 'requires_action') {
  985. //paymentintent->status may be => 'requires_action' (no error in such a case)
  986. dol_syslog(var_export($paymentintent, true), LOG_DEBUG);
  987. $charge->status = 'failed';
  988. $charge->customer = $customer->id;
  989. $charge->failure_code = $stripe->code;
  990. $charge->failure_message = $stripe->error;
  991. $charge->failure_declinecode = $stripe->declinecode;
  992. $stripefailurecode = $stripe->code;
  993. $stripefailuremessage = 'Action required. Contact the support at ';// . $conf->global->SELLYOURSAAS_MAIN_EMAIL;
  994. $stripefailuredeclinecode = $stripe->declinecode;
  995. } else {
  996. dol_syslog(var_export($paymentintent, true), LOG_DEBUG);
  997. $charge->status = 'failed';
  998. $charge->customer = $customer->id;
  999. $charge->failure_code = $stripe->code;
  1000. $charge->failure_message = $stripe->error;
  1001. $charge->failure_declinecode = $stripe->declinecode;
  1002. $stripefailurecode = $stripe->code;
  1003. $stripefailuremessage = $stripe->error;
  1004. $stripefailuredeclinecode = $stripe->declinecode;
  1005. }
  1006. //var_dump("stripefailurecode=".$stripefailurecode." stripefailuremessage=".$stripefailuremessage." stripefailuredeclinecode=".$stripefailuredeclinecode);
  1007. //exit;
  1008. }
  1009. // Return $charge = array('id'=>'ch_XXXX', 'status'=>'succeeded|pending|failed', 'failure_code'=>, 'failure_message'=>...)
  1010. if (empty($charge) || $charge->status == 'failed') {
  1011. dol_syslog('Failed to charge card or payment mode ' . $stripecard->id . ' stripefailurecode=' . $stripefailurecode . ' stripefailuremessage=' . $stripefailuremessage . ' stripefailuredeclinecode=' . $stripefailuredeclinecode, LOG_WARNING);
  1012. // Save a stripe payment was in error
  1013. $this->stripechargeerror++;
  1014. $error++;
  1015. $errorforinvoice++;
  1016. $errmsg = $langs->trans("FailedToChargeCard");
  1017. if (!empty($charge)) {
  1018. if ($stripefailuredeclinecode == 'authentication_required') {
  1019. $errauthenticationmessage = $langs->trans("ErrSCAAuthentication");
  1020. $errmsg = $errauthenticationmessage;
  1021. } elseif (in_array($stripefailuredeclinecode, ['insufficient_funds', 'generic_decline'])) {
  1022. $errmsg .= ': ' . $charge->failure_code;
  1023. $errmsg .= ($charge->failure_message ? ' - ' : '') . ' ' . $charge->failure_message;
  1024. if (empty($stripefailurecode)) {
  1025. $stripefailurecode = $charge->failure_code;
  1026. }
  1027. if (empty($stripefailuremessage)) {
  1028. $stripefailuremessage = $charge->failure_message;
  1029. }
  1030. } else {
  1031. $errmsg .= ': failure_code=' . $charge->failure_code;
  1032. $errmsg .= ($charge->failure_message ? ' - ' : '') . ' failure_message=' . $charge->failure_message;
  1033. if (empty($stripefailurecode)) {
  1034. $stripefailurecode = $charge->failure_code;
  1035. }
  1036. if (empty($stripefailuremessage)) {
  1037. $stripefailuremessage = $charge->failure_message;
  1038. }
  1039. }
  1040. } else {
  1041. $errmsg .= ': ' . $stripefailurecode . ' - ' . $stripefailuremessage;
  1042. $errmsg .= ($stripefailuredeclinecode ? ' - ' . $stripefailuredeclinecode : '');
  1043. }
  1044. $description = 'Stripe payment ERROR from doTakePaymentStripeForThirdparty: ' . $FULLTAG;
  1045. $postactionmessages[] = $errmsg . ' (' . $stripearrayofkeys['publishable_key'] . ')';
  1046. $this->errors[] = $errmsg;
  1047. } else {
  1048. dol_syslog('Successfuly charge card ' . $stripecard->id);
  1049. $postactionmessages[] = 'Success to charge card (' . $charge->id . ' with ' . $stripearrayofkeys['publishable_key'] . ')';
  1050. // Save a stripe payment was done in realy life so later we will be able to force a commit on recorded payments
  1051. // even if in batch mode (method doTakePaymentStripe), we will always make all action in one transaction with a forced commit.
  1052. $this->stripechargedone++;
  1053. // Default description used for label of event. Will be overwrite by another value later.
  1054. $description = 'Stripe payment OK (' . $charge->id . ') from doTakePaymentStripeForThirdparty: ' . $FULLTAG;
  1055. $db = $this->db;
  1056. $ipaddress = getUserRemoteIP();
  1057. $TRANSACTIONID = $charge->id;
  1058. $currency = $conf->currency;
  1059. $paymentmethod = 'stripe';
  1060. $emetteur_name = $charge->customer;
  1061. // Same code than into paymentok.php...
  1062. $paymentTypeId = 0;
  1063. if ($paymentmethod == 'paybox') {
  1064. $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
  1065. }
  1066. if ($paymentmethod == 'paypal') {
  1067. $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
  1068. }
  1069. if ($paymentmethod == 'stripe') {
  1070. $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
  1071. }
  1072. if (empty($paymentTypeId)) {
  1073. //erics
  1074. if ($sepaMode) {
  1075. $paymentType = 'PRE';
  1076. } else {
  1077. $paymentType = $_SESSION["paymentType"];
  1078. if (empty($paymentType)) {
  1079. $paymentType = 'CB';
  1080. }
  1081. }
  1082. $paymentTypeId = dol_getIdFromCode($this->db, $paymentType, 'c_paiement', 'code', 'id', 1);
  1083. }
  1084. $currencyCodeType = $currency;
  1085. $ispostactionok = 1;
  1086. // Creation of payment line
  1087. include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
  1088. $paiement = new Paiement($this->db);
  1089. $paiement->datepaye = $now;
  1090. $paiement->date = $now;
  1091. if ($currencyCodeType == $conf->currency) {
  1092. $paiement->amounts = [$this->id => $amounttopay]; // Array with all payments dispatching with invoice id
  1093. } else {
  1094. $paiement->multicurrency_amounts = [$this->id => $amounttopay]; // Array with all payments dispatching
  1095. $postactionmessages[] = 'Payment was done in a different currency than currency expected of company';
  1096. $ispostactionok = -1;
  1097. // Not yet supported, so error
  1098. $error++;
  1099. $errorforinvoice++;
  1100. }
  1101. $paiement->paiementid = $paymentTypeId;
  1102. $paiement->num_paiement = '';
  1103. $paiement->num_payment = '';
  1104. // Add a comment with keyword 'SellYourSaas' in text. Used by trigger.
  1105. $paiement->note_public = 'StripeSepa payment ' . dol_print_date($now, 'standard') . ' using ' . $paymentmethod . ($ipaddress ? ' from ip ' . $ipaddress : '') . ' - Transaction ID = ' . $TRANSACTIONID;
  1106. $paiement->note_private = 'StripeSepa payment ' . dol_print_date($now, 'standard') . ' using ' . $paymentmethod . ($ipaddress ? ' from ip ' . $ipaddress : '') . ' - Transaction ID = ' . $TRANSACTIONID;
  1107. $paiement->ext_payment_id = $charge->id . ':' . $customer->id . '@' . $stripearrayofkeys['publishable_key'];
  1108. $paiement->ext_payment_site = 'stripe';
  1109. if (!$errorforinvoice) {
  1110. dol_syslog('* Record payment for invoice id ' . $this->id . '. It includes closing of invoice and regenerating document');
  1111. // This include closing invoices to 'paid' (and trigger including unsuspending) and regenerating document
  1112. $paiement_id = $paiement->create($user, 1);
  1113. if ($paiement_id < 0) {
  1114. $postactionmessages[] = $paiement->error . ($paiement->error ? ' ' : '') . join("<br>\n", $paiement->errors);
  1115. $ispostactionok = -1;
  1116. $error++;
  1117. $errorforinvoice++;
  1118. } else {
  1119. $postactionmessages[] = 'Payment created';
  1120. }
  1121. dol_syslog("The payment has been created for invoice id " . $this->id);
  1122. }
  1123. if (!$errorforinvoice && isModEnabled('banque')) {
  1124. dol_syslog('* Add payment to bank');
  1125. $bankaccountid = 0;
  1126. if ($paymentmethod == 'paybox') {
  1127. $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
  1128. }
  1129. if ($paymentmethod == 'paypal') {
  1130. $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
  1131. }
  1132. if ($paymentmethod == 'stripe') {
  1133. $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
  1134. }
  1135. if ($bankaccountid > 0) {
  1136. $label = '(CustomerInvoicePayment)';
  1137. if ($this->type == Facture::TYPE_CREDIT_NOTE) {
  1138. $label = '(CustomerInvoicePaymentBack)';
  1139. } // Refund of a credit note
  1140. $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, $emetteur_name, '');
  1141. if ($result < 0) {
  1142. $postactionmessages[] = $paiement->error . ($paiement->error ? ' ' : '') . join("<br>\n", $paiement->errors);
  1143. $ispostactionok = -1;
  1144. $error++;
  1145. $errorforinvoice++;
  1146. } else {
  1147. $postactionmessages[] = 'Bank transaction of payment created (by doTakePaymentStripeForThirdparty)';
  1148. }
  1149. } else {
  1150. $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
  1151. $ispostactionok = -1;
  1152. $error++;
  1153. $errorforinvoice++;
  1154. }
  1155. }
  1156. if ($ispostactionok < 1) {
  1157. $description = 'Stripe payment OK (' . $charge->id . ' - ' . $amounttopay . ' ' . $conf->currency . ') but post action KO from doTakePaymentStripeForThirdparty: ' . $FULLTAG;
  1158. } else {
  1159. $description = 'Stripe payment+post action OK (' . $charge->id . ' - ' . $amounttopay . ' ' . $conf->currency . ') from doTakePaymentStripeForThirdparty: ' . $FULLTAG;
  1160. }
  1161. }
  1162. $object = $invoice;
  1163. // Send emails
  1164. $labeltouse = 'InvoicePaymentSuccess';
  1165. $sendemailtocustomer = 1;
  1166. if (empty($charge) || $charge->status == 'failed') {
  1167. $labeltouse = 'InvoicePaymentFailure';
  1168. if ($noemailtocustomeriferror) {
  1169. $sendemailtocustomer = 0;
  1170. } // $noemailtocustomeriferror is set when error already reported on myaccount screen
  1171. }
  1172. // Track an event
  1173. if (empty($charge) || $charge->status == 'failed') {
  1174. $actioncode = 'PAYMENT_STRIPE_KO';
  1175. $extraparams = $stripefailurecode;
  1176. $extraparams .= (($extraparams && $stripefailuremessage) ? ' - ' : '') . $stripefailuremessage;
  1177. $extraparams .= (($extraparams && $stripefailuredeclinecode) ? ' - ' : '') . $stripefailuredeclinecode;
  1178. } else {
  1179. $actioncode = 'PAYMENT_STRIPE_OK';
  1180. $extraparams = '';
  1181. }
  1182. } else {
  1183. $error++;
  1184. $errorforinvoice++;
  1185. dol_syslog("No card or payment method found for this stripe customer " . $customer->id, LOG_WARNING);
  1186. $this->errors[] = 'Failed to get card | payment method for stripe customer = ' . $customer->id;
  1187. $labeltouse = 'InvoicePaymentFailure';
  1188. $sendemailtocustomer = 1;
  1189. if ($noemailtocustomeriferror) {
  1190. $sendemailtocustomer = 0;
  1191. } // $noemailtocustomeriferror is set when error already reported on myaccount screen
  1192. $description = 'Failed to find or use the payment mode - no credit card defined for the customer account';
  1193. $stripefailurecode = 'BADPAYMENTMODE';
  1194. $stripefailuremessage = 'Failed to find or use the payment mode - no credit card defined for the customer account';
  1195. $postactionmessages[] = $description . ' (' . $stripearrayofkeys['publishable_key'] . ')';
  1196. $object = $invoice;
  1197. $actioncode = 'PAYMENT_STRIPE_KO';
  1198. $extraparams = '';
  1199. }
  1200. } else {
  1201. // If error because payment was canceled for a logical reason, we do nothing (no email and no event added)
  1202. $labeltouse = '';
  1203. $sendemailtocustomer = 0;
  1204. $description = '';
  1205. $stripefailurecode = '';
  1206. $stripefailuremessage = '';
  1207. $object = $invoice;
  1208. $actioncode = '';
  1209. $extraparams = '';
  1210. }
  1211. } else { // Else of the if ($resultthirdparty > 0 && ! empty($customer)) {
  1212. if ($resultthirdparty <= 0) {
  1213. dol_syslog('SellYourSaasUtils Failed to load customer for thirdparty_id = ' . $thirdparty->id, LOG_WARNING);
  1214. $this->errors[] = 'Failed to load customer for thirdparty_id = ' . $thirdparty->id;
  1215. } else { // $customer stripe not found
  1216. dol_syslog('SellYourSaasUtils Failed to get Stripe customer id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'], LOG_WARNING);
  1217. $this->errors[] = 'Failed to get Stripe customer id for thirdparty_id = ' . $thirdparty->id . " in mode " . $servicestatus . " in Stripe env " . $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];
  1218. }
  1219. $error++;
  1220. $errorforinvoice++;
  1221. $labeltouse = 'InvoicePaymentFailure';
  1222. $sendemailtocustomer = 1;
  1223. if ($noemailtocustomeriferror) {
  1224. $sendemailtocustomer = 0;
  1225. } // $noemailtocustomeriferror is set when error already reported on myaccount screen
  1226. $description = 'Failed to find or use your payment mode (no payment mode for this customer id)';
  1227. $stripefailurecode = 'BADPAYMENTMODE';
  1228. $stripefailuremessage = 'Failed to find or use your payment mode (no payment mode for this customer id)';
  1229. $postactionmessages = [];
  1230. $object = $invoice;
  1231. $actioncode = 'PAYMENT_STRIPE_KO';
  1232. $extraparams = '';
  1233. }
  1234. // Send email + create action after
  1235. if ($sendemailtocustomer && $labeltouse) {
  1236. dol_syslog("* Send email with result of payment - " . $labeltouse);
  1237. // Set output language
  1238. $outputlangs = new Translate('', $conf);
  1239. $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
  1240. $outputlangs->loadLangs(["main", "members", "bills"]);
  1241. // Get email content from templae
  1242. $arraydefaultmessage = null;
  1243. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  1244. $formmail = new FormMail($this->db);
  1245. if (!empty($labeltouse)) {
  1246. $arraydefaultmessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, 0, 1, $labeltouse);
  1247. }
  1248. if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  1249. $subject = $arraydefaultmessage->topic;
  1250. $msg = $arraydefaultmessage->content;
  1251. }
  1252. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  1253. //$substitutionarray['__SELLYOURSAAS_PAYMENT_ERROR_DESC__'] = $stripefailurecode . ' ' . $stripefailuremessage;
  1254. complete_substitutions_array($substitutionarray, $outputlangs, $object);
  1255. // Set the property ->ref_customer with ref_customer of contract so __REF_CLIENT__ will be replaced in email content
  1256. // Search contract linked to invoice
  1257. $foundcontract = null;
  1258. $this->fetchObjectLinked();
  1259. if (is_array($this->linkedObjects['contrat']) && count($this->linkedObjects['contrat']) > 0) {
  1260. //dol_sort_array($object->linkedObjects['facture'], 'date');
  1261. foreach ($this->linkedObjects['contrat'] as $idcontract => $contract) {
  1262. $substitutionarray['__CONTRACT_REF__'] = $contract->ref_customer;
  1263. $substitutionarray['__REFCLIENT__'] = $contract->ref_customer; // For backward compatibility
  1264. $substitutionarray['__REF_CLIENT__'] = $contract->ref_customer;
  1265. $foundcontract = $contract;
  1266. break;
  1267. }
  1268. }
  1269. dol_syslog('__DIRECTDOWNLOAD_URL_INVOICE__=' . $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__']);
  1270. //erics - erreur de réécriture de l'url de téléchargement direct de la facture ... le lien de base est le bon
  1271. //on cherche donc d'ou vien le pb ...
  1272. //$urlforsellyoursaasaccount = getRootUrlForAccount($foundcontract);
  1273. // if ($urlforsellyoursaasaccount) {
  1274. // $tmpforurl = preg_replace('/.*document.php/', '', $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__']);
  1275. // if ($tmpforurl) {
  1276. // dol_syslog('__DIRECTDOWNLOAD_URL_INVOICE__ cas 1, urlforsellyoursaasaccount=' . $urlforsellyoursaasaccount);
  1277. // // $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $urlforsellyoursaasaccount . '/source/document.php' . $tmpforurl;
  1278. // } else {
  1279. // dol_syslog('__DIRECTDOWNLOAD_URL_INVOICE__ cas 2, urlforsellyoursaasaccount=' . $urlforsellyoursaasaccount);
  1280. // // $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $urlforsellyoursaasaccount;
  1281. // }
  1282. // }
  1283. $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
  1284. $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
  1285. // Attach a file ?
  1286. $file = '';
  1287. $listofpaths = [];
  1288. $listofnames = [];
  1289. $listofmimes = [];
  1290. if (is_object($invoice)) {
  1291. $invoicediroutput = $conf->facture->dir_output;
  1292. //erics - choix du PDF a joindre aux mails
  1293. $fileparams = dol_most_recent_file($invoicediroutput . '/' . $this->ref, preg_quote($this->ref, '/') . '[^\-]+*.pdf');
  1294. $file = $fileparams['fullname'];
  1295. //$file = $invoicediroutput . '/' . $this->ref . '/' . $this->ref . '.pdf';
  1296. // $file = ''; // Disable attachment of invoice in emails
  1297. if ($file) {
  1298. $listofpaths = [$file];
  1299. $listofnames = [basename($file)];
  1300. $listofmimes = [dol_mimetype($file)];
  1301. }
  1302. }
  1303. $from = "";//$conf->global->SELLYOURSAAS_NOREPLY_EMAIL;
  1304. $trackid = 'inv' . $this->id;
  1305. $moreinheader = 'X-Dolibarr-Info: makeStripeSepaRequest' . "\r\n";
  1306. // Send email (substitutionarray must be done just before this)
  1307. include_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
  1308. $mailfile = new CMailFile($subjecttosend, $this->thirdparty->email, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, '', '', 0, -1, '', '', $trackid, $moreinheader);
  1309. if ($mailfile->sendfile()) {
  1310. $result = 1;
  1311. } else {
  1312. $this->error = $langs->trans("ErrorFailedToSendMail", $from, $this->thirdparty->email) . '. ' . $mailfile->error;
  1313. $result = -1;
  1314. }
  1315. if ($result < 0) {
  1316. $errmsg = $this->error;
  1317. $postactionmessages[] = $errmsg;
  1318. $ispostactionok = -1;
  1319. } else {
  1320. if ($file) {
  1321. $postactionmessages[] = 'Email sent to thirdparty (to ' . $this->thirdparty->email . ' with invoice document attached: ' . $file . ', language = ' . $outputlangs->defaultlang . ')';
  1322. } else {
  1323. $postactionmessages[] = 'Email sent to thirdparty (to ' . $this->thirdparty->email . ' without any attached document, language = ' . $outputlangs->defaultlang . ')';
  1324. }
  1325. }
  1326. }
  1327. if ($description) {
  1328. dol_syslog("* Record event for payment result - " . $description);
  1329. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  1330. // Insert record of payment (success or error)
  1331. $actioncomm = new ActionComm($this->db);
  1332. $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
  1333. $actioncomm->code = 'AC_' . $actioncode;
  1334. $actioncomm->label = $description;
  1335. $actioncomm->note_private = join(",\n", $postactionmessages);
  1336. $actioncomm->fk_project = $this->fk_project;
  1337. $actioncomm->datep = $now;
  1338. $actioncomm->datef = $now;
  1339. $actioncomm->percentage = -1; // Not applicable
  1340. $actioncomm->socid = $thirdparty->id;
  1341. $actioncomm->contactid = 0;
  1342. $actioncomm->authorid = $user->id; // User saving action
  1343. $actioncomm->userownerid = $user->id; // Owner of action
  1344. // Fields when action is a real email (content is already into note)
  1345. /*$actioncomm->email_msgid = $object->email_msgid;
  1346. $actioncomm->email_from = $object->email_from;
  1347. $actioncomm->email_sender= $object->email_sender;
  1348. $actioncomm->email_to = $object->email_to;
  1349. $actioncomm->email_tocc = $object->email_tocc;
  1350. $actioncomm->email_tobcc = $object->email_tobcc;
  1351. $actioncomm->email_subject = $object->email_subject;
  1352. $actioncomm->errors_to = $object->errors_to;*/
  1353. $actioncomm->fk_element = $this->id;
  1354. $actioncomm->elementtype = $this->element;
  1355. $actioncomm->extraparams = dol_trunc($extraparams, 250);
  1356. $actioncomm->create($user);
  1357. }
  1358. $this->description = $description;
  1359. $this->postactionmessages = $postactionmessages;
  1360. } catch (Exception $e) {
  1361. $error++;
  1362. $errorforinvoice++;
  1363. dol_syslog('Error ' . $e->getMessage(), LOG_ERR);
  1364. $this->errors[] = 'Error ' . $e->getMessage();
  1365. }
  1366. } else { // If remain to pay is null
  1367. $error++;
  1368. $errorforinvoice++;
  1369. dol_syslog("Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?", LOG_WARNING);
  1370. $this->errors[] = "Remain to pay is null for the invoice " . $this->id . " " . $this->ref . ". Why is the invoice not classified 'Paid' ?";
  1371. }
  1372. $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_demande(";
  1373. $sql .= "fk_facture, ";
  1374. $sql .= " amount, date_demande, fk_user_demande, ext_payment_id, ext_payment_site, sourcetype, entity)";
  1375. $sql .= " VALUES (".$this->id;
  1376. $sql .= ",".((float) price2num($amount));
  1377. $sql .= ",'".$this->db->idate($now)."'";
  1378. $sql .= ",".((int) $fuser->id);
  1379. $sql .= ",'".$this->db->escape($stripe_id)."'";
  1380. $sql .= ",'".$this->db->escape($stripe_uri)."'";
  1381. $sql .= ",'".$this->db->escape($sourcetype)."'";
  1382. $sql .= ",".$conf->entity;
  1383. $sql .= ")";
  1384. dol_syslog(get_class($this)."::makeStripeSepaRequest", LOG_DEBUG);
  1385. $resql = $this->db->query($sql);
  1386. if (!$resql) {
  1387. $this->error = $this->db->lasterror();
  1388. dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur');
  1389. $error++;
  1390. }
  1391. } else {
  1392. $this->error = 'WithdrawRequestErrorNilAmount';
  1393. dol_syslog(get_class($this).'::makeStripeSepaRequest WithdrawRequestErrorNilAmount');
  1394. $error++;
  1395. }
  1396. if (!$error) {
  1397. // Force payment mode of invoice to withdraw
  1398. $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
  1399. if ($payment_mode_id > 0) {
  1400. $result = $this->setPaymentMethods($payment_mode_id);
  1401. }
  1402. }
  1403. if ($error) {
  1404. return -1;
  1405. }
  1406. return 1;
  1407. } else {
  1408. $this->error = $this->db->error();
  1409. dol_syslog(get_class($this).'::makeStripeSepaRequest Erreur -2');
  1410. return -2;
  1411. }
  1412. } else {
  1413. $this->error = "Status of invoice does not allow this";
  1414. dol_syslog(get_class($this)."::makeStripeSepaRequest ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
  1415. return -3;
  1416. }
  1417. }
  1418. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1419. /**
  1420. * Remove a direct debit request or a credit transfer request
  1421. *
  1422. * @param User $fuser User making delete
  1423. * @param int $did ID of request to delete
  1424. * @return int <0 if OK, >0 if KO
  1425. */
  1426. public function demande_prelevement_delete($fuser, $did)
  1427. {
  1428. // phpcs:enable
  1429. $sql = 'DELETE FROM '.$this->db->prefix().'prelevement_demande';
  1430. $sql .= ' WHERE rowid = '.((int) $did);
  1431. $sql .= ' AND traite = 0';
  1432. if ($this->db->query($sql)) {
  1433. return 0;
  1434. } else {
  1435. $this->error = $this->db->lasterror();
  1436. dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
  1437. return -1;
  1438. }
  1439. }
  1440. /**
  1441. * Build string for ZATCA QR Code (Arabi Saudia)
  1442. *
  1443. * @return string String for ZATCA QR Code
  1444. */
  1445. public function buildZATCAQRString()
  1446. {
  1447. global $conf, $mysoc;
  1448. $tmplang = new Translate('', $conf);
  1449. $tmplang->setDefaultLang('en_US');
  1450. $tmplang->load("main");
  1451. $datestring = dol_print_date($this->date, 'dayhourrfc');
  1452. //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2);
  1453. //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2);
  1454. $pricewithtaxstring = price2num($this->total_ttc, 2, 1);
  1455. $pricetaxstring = price2num($this->total_tva, 2, 1);
  1456. /*
  1457. $name = implode(unpack("H*", $this->thirdparty->name));
  1458. $vatnumber = implode(unpack("H*", $this->thirdparty->tva_intra));
  1459. $date = implode(unpack("H*", $datestring));
  1460. $pricewithtax = implode(unpack("H*", price2num($pricewithtaxstring, 2)));
  1461. $pricetax = implode(unpack("H*", $pricetaxstring));
  1462. //var_dump(strlen($this->thirdparty->name));
  1463. //var_dump(str_pad(dechex('9'), 2, '0', STR_PAD_LEFT));
  1464. //var_dump($this->thirdparty->name);
  1465. //var_dump(implode(unpack("H*", $this->thirdparty->name)));
  1466. //var_dump(price($this->total_tva, 0, $tmplang, 0, -1, 2));
  1467. $s = '01'.str_pad(dechex(strlen($this->thirdparty->name)), 2, '0', STR_PAD_LEFT).$name;
  1468. $s .= '02'.str_pad(dechex(strlen($this->thirdparty->tva_intra)), 2, '0', STR_PAD_LEFT).$vatnumber;
  1469. $s .= '03'.str_pad(dechex(strlen($datestring)), 2, '0', STR_PAD_LEFT).$date;
  1470. $s .= '04'.str_pad(dechex(strlen($pricewithtaxstring)), 2, '0', STR_PAD_LEFT).$pricewithtax;
  1471. $s .= '05'.str_pad(dechex(strlen($pricetaxstring)), 2, '0', STR_PAD_LEFT).$pricetax;
  1472. $s .= ''; // Hash of xml invoice
  1473. $s .= ''; // ecda signature
  1474. $s .= ''; // ecda public key
  1475. $s .= ''; // ecda signature of public key stamp
  1476. */
  1477. // Using TLV format
  1478. $s = pack('C1', 1).pack('C1', strlen($mysoc->name)).$mysoc->name;
  1479. $s .= pack('C1', 2).pack('C1', strlen($mysoc->tva_intra)).$mysoc->tva_intra;
  1480. $s .= pack('C1', 3).pack('C1', strlen($datestring)).$datestring;
  1481. $s .= pack('C1', 4).pack('C1', strlen($pricewithtaxstring)).$pricewithtaxstring;
  1482. $s .= pack('C1', 5).pack('C1', strlen($pricetaxstring)).$pricetaxstring;
  1483. $s .= ''; // Hash of xml invoice
  1484. $s .= ''; // ecda signature
  1485. $s .= ''; // ecda public key
  1486. $s .= ''; // ecda signature of public key stamp
  1487. $s = base64_encode($s);
  1488. return $s;
  1489. }
  1490. /**
  1491. * Build string for QR-Bill (Switzerland)
  1492. *
  1493. * @return string String for Switzerland QR Code if QR-Bill
  1494. */
  1495. public function buildSwitzerlandQRString()
  1496. {
  1497. global $conf, $mysoc;
  1498. $tmplang = new Translate('', $conf);
  1499. $tmplang->setDefaultLang('en_US');
  1500. $tmplang->load("main");
  1501. $pricewithtaxstring = price2num($this->total_ttc, 2, 1);
  1502. $pricetaxstring = price2num($this->total_tva, 2, 1);
  1503. $complementaryinfo = '';
  1504. /*
  1505. Example: //S1/10/10201409/11/190512/20/1400.000-53/30/106017086/31/180508/32/7.7/40/2:10;0:30
  1506. /10/ Numéro de facture – 10201409
  1507. /11/ Date de facture – 12.05.2019
  1508. /20/ Référence client – 1400.000-53
  1509. /30/ Numéro IDE pour la TVA – CHE-106.017.086 TVA
  1510. /31/ Date de la prestation pour la comptabilisation de la TVA – 08.05.2018
  1511. /32/ Taux de TVA sur le montant total de la facture – 7.7%
  1512. /40/ Conditions – 2% d’escompte à 10 jours, paiement net à 30 jours
  1513. */
  1514. $datestring = dol_print_date($this->date, '%y%m%d');
  1515. //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2);
  1516. //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2);
  1517. $complementaryinfo = '//S1/10/'.str_replace('/', '', $this->ref).'/11/'.$datestring;
  1518. if ($this->ref_client) {
  1519. $complementaryinfo .= '/20/'.$this->ref_client;
  1520. }
  1521. if ($this->thirdparty->tva_intra) {
  1522. $complementaryinfo .= '/30/'.$this->thirdparty->tva_intra;
  1523. }
  1524. // Header
  1525. $s = '';
  1526. $s .= "SPC\n";
  1527. $s .= "0200\n";
  1528. $s .= "1\n";
  1529. if ($this->fk_account > 0) {
  1530. // Bank BAN if country is LI or CH
  1531. // TODO Add
  1532. $bankaccount = new Account($this->db);
  1533. $bankaccount->fetch($this->fk_account);
  1534. $s .= $bankaccount->iban."\n";
  1535. } else {
  1536. $s .= "\n";
  1537. }
  1538. // Seller
  1539. $s .= "S\n";
  1540. $s .= dol_trunc($mysoc->name, 70, 'right', 'UTF-8', 1)."\n";
  1541. $addresslinearray = explode("\n", $mysoc->address);
  1542. $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 1
  1543. $s .= dol_trunc(empty($addresslinearray[2]) ? '' : $addresslinearray[2], 70, 'right', 'UTF-8', 1)."\n"; // address line 2
  1544. $s .= dol_trunc($mysoc->zip, 16, 'right', 'UTF-8', 1)."\n";
  1545. $s .= dol_trunc($mysoc->town, 35, 'right', 'UTF-8', 1)."\n";
  1546. $s .= dol_trunc($mysoc->country_code, 2, 'right', 'UTF-8', 1)."\n";
  1547. // Final seller
  1548. $s .= "\n";
  1549. $s .= "\n";
  1550. $s .= "\n";
  1551. $s .= "\n";
  1552. $s .= "\n";
  1553. $s .= "\n";
  1554. $s .= "\n";
  1555. // Amount of payment (to do?)
  1556. $s .= price($pricewithtaxstring, 0, 'none', 0, 0, 2)."\n";
  1557. $s .= ($this->multicurrency_code ? $this->multicurrency_code : $conf->currency)."\n";
  1558. // Buyer
  1559. $s .= "S\n";
  1560. $s .= dol_trunc($this->thirdparty->name, 70, 'right', 'UTF-8', 1)."\n";
  1561. $addresslinearray = explode("\n", $this->thirdparty->address);
  1562. $s .= dol_trunc(empty($addresslinearray[1]) ? '' : $addresslinearray[1], 70, 'right', 'UTF-8', 1)."\n"; // address line 1
  1563. $s .= dol_trunc(empty($addresslinearray[2]) ? '' : $addresslinearray[2], 70, 'right', 'UTF-8', 1)."\n"; // address line 2
  1564. $s .= dol_trunc($this->thirdparty->zip, 16, 'right', 'UTF-8', 1)."\n";
  1565. $s .= dol_trunc($this->thirdparty->town, 35, 'right', 'UTF-8', 1)."\n";
  1566. $s .= dol_trunc($this->thirdparty->country_code, 2, 'right', 'UTF-8', 1)."\n";
  1567. // ID of payment
  1568. $s .= "NON\n"; // NON or QRR
  1569. $s .= "\n"; // QR Code if previous field is QRR
  1570. if ($complementaryinfo) {
  1571. $s .= $complementaryinfo."\n";
  1572. } else {
  1573. $s .= "\n";
  1574. }
  1575. $s .= "EPD\n";
  1576. $s .= "\n";
  1577. //var_dump($s);exit;
  1578. return $s;
  1579. }
  1580. }
  1581. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  1582. /**
  1583. * Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...)
  1584. */
  1585. abstract class CommonInvoiceLine extends CommonObjectLine
  1586. {
  1587. /**
  1588. * Custom label of line. Not used by default.
  1589. * @deprecated
  1590. */
  1591. public $label;
  1592. /**
  1593. * @deprecated
  1594. * @see $product_ref
  1595. */
  1596. public $ref; // Product ref (deprecated)
  1597. /**
  1598. * @deprecated
  1599. * @see $product_label
  1600. */
  1601. public $libelle; // Product label (deprecated)
  1602. /**
  1603. * Type of the product. 0 for product 1 for service
  1604. * @var int
  1605. */
  1606. public $product_type = 0;
  1607. /**
  1608. * Product ref
  1609. * @var string
  1610. */
  1611. public $product_ref;
  1612. /**
  1613. * Product label
  1614. * @var string
  1615. */
  1616. public $product_label;
  1617. /**
  1618. * Product description
  1619. * @var string
  1620. */
  1621. public $product_desc;
  1622. /**
  1623. * Quantity
  1624. * @var double
  1625. */
  1626. public $qty;
  1627. /**
  1628. * Unit price before taxes
  1629. * @var float
  1630. */
  1631. public $subprice;
  1632. /**
  1633. * Unit price before taxes
  1634. * @var float
  1635. * @deprecated
  1636. */
  1637. public $price;
  1638. /**
  1639. * Id of corresponding product
  1640. * @var int
  1641. */
  1642. public $fk_product;
  1643. /**
  1644. * VAT code
  1645. * @var string
  1646. */
  1647. public $vat_src_code;
  1648. /**
  1649. * VAT %
  1650. * @var float
  1651. */
  1652. public $tva_tx;
  1653. /**
  1654. * Local tax 1 %
  1655. * @var float
  1656. */
  1657. public $localtax1_tx;
  1658. /**
  1659. * Local tax 2 %
  1660. * @var float
  1661. */
  1662. public $localtax2_tx;
  1663. /**
  1664. * Local tax 1 type
  1665. * @var string
  1666. */
  1667. public $localtax1_type;
  1668. /**
  1669. * Local tax 2 type
  1670. * @var string
  1671. */
  1672. public $localtax2_type;
  1673. /**
  1674. * Percent of discount
  1675. * @var float
  1676. */
  1677. public $remise_percent;
  1678. /**
  1679. * Fixed discount
  1680. * @var float
  1681. * @deprecated
  1682. */
  1683. public $remise;
  1684. /**
  1685. * Total amount before taxes
  1686. * @var float
  1687. */
  1688. public $total_ht;
  1689. /**
  1690. * Total VAT amount
  1691. * @var float
  1692. */
  1693. public $total_tva;
  1694. /**
  1695. * Total local tax 1 amount
  1696. * @var float
  1697. */
  1698. public $total_localtax1;
  1699. /**
  1700. * Total local tax 2 amount
  1701. * @var float
  1702. */
  1703. public $total_localtax2;
  1704. /**
  1705. * Total amount with taxes
  1706. * @var float
  1707. */
  1708. public $total_ttc;
  1709. public $date_start_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_start at creation
  1710. public $date_end_fill; // If set to 1, when invoice is created from a template invoice, it will also auto set the field date_end at creation
  1711. public $buy_price_ht;
  1712. public $buyprice; // For backward compatibility
  1713. public $pa_ht; // For backward compatibility
  1714. public $marge_tx;
  1715. public $marque_tx;
  1716. /**
  1717. * List of cumulative options:
  1718. * Bit 0: 0 for common VAT - 1 if VAT french NPR
  1719. * Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
  1720. * @var int
  1721. */
  1722. public $info_bits = 0;
  1723. public $special_code = 0;
  1724. public $fk_multicurrency;
  1725. public $multicurrency_code;
  1726. public $multicurrency_subprice;
  1727. public $multicurrency_total_ht;
  1728. public $multicurrency_total_tva;
  1729. public $multicurrency_total_ttc;
  1730. public $fk_user_author;
  1731. public $fk_user_modif;
  1732. public $fk_accounting_account;
  1733. }