commoninvoice.class.php 76 KB

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