commoninvoice.class.php 76 KB

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