commoninvoice.class.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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 (not recommended).
  148. *
  149. * @param int $multicurrency Return multicurrency_amount instead of amount
  150. * @return float <0 and set ->error if KO, Sum of deposits amount otherwise
  151. */
  152. public function getSumDepositsUsed($multicurrency = 0)
  153. {
  154. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  155. // FACTURE_DEPOSITS_ARE_JUST_PAYMENTS was never supported for purchase invoice, so we can return 0 with no need of SQL for this case.
  156. return 0.0;
  157. }
  158. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  159. $discountstatic = new DiscountAbsolute($this->db);
  160. $result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
  161. if ($result >= 0) {
  162. if ($multicurrency) {
  163. $this->sumdeposit_multicurrency = $result;
  164. } else {
  165. $this->sumdeposit = $result;
  166. }
  167. return $result;
  168. } else {
  169. $this->error = $discountstatic->error;
  170. return -1;
  171. }
  172. }
  173. /**
  174. * Return amount (with tax) of all credit notes invoices + excess received used by invoice
  175. *
  176. * @param int $multicurrency Return multicurrency_amount instead of amount
  177. * @return float <0 and set ->error if KO, Sum of credit notes and deposits amount otherwise
  178. */
  179. public function getSumCreditNotesUsed($multicurrency = 0)
  180. {
  181. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  182. $discountstatic = new DiscountAbsolute($this->db);
  183. $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
  184. if ($result >= 0) {
  185. if ($multicurrency) {
  186. $this->sumcreditnote_multicurrency = $result;
  187. } else {
  188. $this->sumcreditnote = $result;
  189. }
  190. return $result;
  191. } else {
  192. $this->error = $discountstatic->error;
  193. return -1;
  194. }
  195. }
  196. /**
  197. * Return amount (with tax) of all converted amount for this credit note
  198. *
  199. * @param int $multicurrency Return multicurrency_amount instead of amount
  200. * @return float <0 if KO, Sum of credit notes and deposits amount otherwise
  201. */
  202. public function getSumFromThisCreditNotesNotUsed($multicurrency = 0)
  203. {
  204. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  205. $discountstatic = new DiscountAbsolute($this->db);
  206. $result = $discountstatic->getSumFromThisCreditNotesNotUsed($this, $multicurrency);
  207. if ($result >= 0) {
  208. return $result;
  209. } else {
  210. $this->error = $discountstatic->error;
  211. return -1;
  212. }
  213. }
  214. /**
  215. * Returns array of credit note ids from the invoice
  216. *
  217. * @return array Array of credit note ids
  218. */
  219. public function getListIdAvoirFromInvoice()
  220. {
  221. $idarray = array();
  222. $sql = "SELECT rowid";
  223. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  224. $sql .= " WHERE fk_facture_source = ".((int) $this->id);
  225. $sql .= " AND type = 2";
  226. $resql = $this->db->query($sql);
  227. if ($resql) {
  228. $num = $this->db->num_rows($resql);
  229. $i = 0;
  230. while ($i < $num) {
  231. $row = $this->db->fetch_row($resql);
  232. $idarray[] = $row[0];
  233. $i++;
  234. }
  235. } else {
  236. dol_print_error($this->db);
  237. }
  238. return $idarray;
  239. }
  240. /**
  241. * Returns the id of the invoice that replaces it
  242. *
  243. * @param string $option status filter ('', 'validated', ...)
  244. * @return int <0 si KO, 0 if no invoice replaces it, id of invoice otherwise
  245. */
  246. public function getIdReplacingInvoice($option = '')
  247. {
  248. $sql = "SELECT rowid";
  249. $sql .= " FROM ".$this->db->prefix().$this->table_element;
  250. $sql .= " WHERE fk_facture_source = ".((int) $this->id);
  251. $sql .= " AND type < 2";
  252. if ($option == 'validated') {
  253. $sql .= ' AND fk_statut = 1';
  254. }
  255. // PROTECTION BAD DATA
  256. // In case the database is corrupted and there is a valid replectement invoice
  257. // and another no, priority is given to the valid one.
  258. // Should not happen (unless concurrent access and 2 people have created a
  259. // replacement invoice for the same invoice at the same time)
  260. $sql .= " ORDER BY fk_statut DESC";
  261. $resql = $this->db->query($sql);
  262. if ($resql) {
  263. $obj = $this->db->fetch_object($resql);
  264. if ($obj) {
  265. // If there is any
  266. return $obj->rowid;
  267. } else {
  268. // If no invoice replaces it
  269. return 0;
  270. }
  271. } else {
  272. return -1;
  273. }
  274. }
  275. /**
  276. * Return list of payments
  277. *
  278. * @param string $filtertype 1 to filter on type of payment == 'PRE'
  279. * @return array Array with list of payments
  280. */
  281. public function getListOfPayments($filtertype = '')
  282. {
  283. $retarray = array();
  284. $table = 'paiement_facture';
  285. $table2 = 'paiement';
  286. $field = 'fk_facture';
  287. $field2 = 'fk_paiement';
  288. $field3 = ', p.ref_ext';
  289. $sharedentity = 'facture';
  290. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  291. $table = 'paiementfourn_facturefourn';
  292. $table2 = 'paiementfourn';
  293. $field = 'fk_facturefourn';
  294. $field2 = 'fk_paiementfourn';
  295. $field3 = '';
  296. $sharedentity = 'facture_fourn';
  297. }
  298. $sql = "SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code".$field3;
  299. $sql .= " FROM ".$this->db->prefix().$table." as pf, ".$this->db->prefix().$table2." as p, ".$this->db->prefix()."c_paiement as t";
  300. $sql .= " WHERE pf.".$field." = ".((int) $this->id);
  301. $sql .= " AND pf.".$field2." = p.rowid";
  302. $sql .= ' AND p.fk_paiement = t.id';
  303. $sql .= ' AND p.entity IN ('.getEntity($sharedentity).')';
  304. if ($filtertype) {
  305. $sql .= " AND t.code='PRE'";
  306. }
  307. dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
  308. $resql = $this->db->query($sql);
  309. if ($resql) {
  310. $num = $this->db->num_rows($resql);
  311. $i = 0;
  312. while ($i < $num) {
  313. $obj = $this->db->fetch_object($resql);
  314. $tmp = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
  315. if (!empty($field3)) {
  316. $tmp['ref_ext'] = $obj->ref_ext;
  317. }
  318. $retarray[] = $tmp;
  319. $i++;
  320. }
  321. $this->db->free($resql);
  322. //look for credit notes and discounts and deposits
  323. $sql = '';
  324. if ($this->element == 'facture' || $this->element == 'invoice') {
  325. $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";
  326. $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture as f';
  327. $sql .= ' WHERE rc.fk_facture_source=f.rowid AND rc.fk_facture = '.((int) $this->id);
  328. $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)
  329. } elseif ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
  330. $sql = "SELECT rc.amount_ttc as amount, rc.multicurrency_amount_ttc as multicurrency_amount, rc.datec as date, f.ref as ref, rc.description as type";
  331. $sql .= ' FROM '.$this->db->prefix().'societe_remise_except as rc, '.$this->db->prefix().'facture_fourn as f';
  332. $sql .= ' WHERE rc.fk_invoice_supplier_source=f.rowid AND rc.fk_invoice_supplier = '.((int) $this->id);
  333. $sql .= ' AND (f.type = 2 OR f.type = 0 OR f.type = 3)'; // Find discount coming from credit note or excess received or deposits (payments from deposits are always null except if FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is set)
  334. }
  335. if ($sql) {
  336. $resql = $this->db->query($sql);
  337. if ($resql) {
  338. $num = $this->db->num_rows($resql);
  339. $i = 0;
  340. while ($i < $num) {
  341. $obj = $this->db->fetch_object($resql);
  342. if ($multicurrency) {
  343. $retarray[] = array('amount'=>$obj->multicurrency_amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'0', 'ref'=>$obj->ref);
  344. } else {
  345. $retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->type, 'date'=>$obj->date, 'num'=>'', 'ref'=>$obj->ref);
  346. }
  347. $i++;
  348. }
  349. } else {
  350. $this->error = $this->db->lasterror();
  351. dol_print_error($this->db);
  352. return array();
  353. }
  354. $this->db->free($resql);
  355. }
  356. return $retarray;
  357. } else {
  358. $this->error = $this->db->lasterror();
  359. dol_print_error($this->db);
  360. return array();
  361. }
  362. }
  363. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  364. /**
  365. * Return if an invoice can be deleted
  366. * Rule is:
  367. * If invoice is draft and has a temporary ref -> yes (1)
  368. * If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on -> no (0)
  369. * If invoice is dispatched in bookkeeping -> no (-1)
  370. * If invoice has a definitive ref, is not last and INVOICE_CAN_ALWAYS_BE_REMOVED off -> no (-2)
  371. * If invoice not last in a cycle -> no (-3)
  372. * If there is payment -> no (-4)
  373. * Otherwise -> yes (2)
  374. *
  375. * @return int <=0 if no, >0 if yes
  376. */
  377. public function is_erasable()
  378. {
  379. // phpcs:enable
  380. global $conf;
  381. // We check if invoice is a temporary number (PROVxxxx)
  382. $tmppart = substr($this->ref, 1, 4);
  383. if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') { // If draft invoice and ref not yet defined
  384. return 1;
  385. }
  386. if (!empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) {
  387. return 0;
  388. }
  389. // If not a draft invoice and not temporary invoice
  390. if ($tmppart !== 'PROV') {
  391. $ventilExportCompta = $this->getVentilExportCompta();
  392. if ($ventilExportCompta != 0) {
  393. return -1;
  394. }
  395. // Get last number of validated invoice
  396. if ($this->element != 'invoice_supplier') {
  397. if (empty($this->thirdparty)) {
  398. $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
  399. }
  400. $maxref = $this->getNextNumRef($this->thirdparty, 'last');
  401. // If there is no invoice into the reset range and not already dispatched, we can delete
  402. // If invoice to delete is last one and not already dispatched, we can delete
  403. if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) {
  404. return -2;
  405. }
  406. // TODO If there is payment in bookkeeping, check payment is not dispatched in accounting
  407. // ...
  408. if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle')) {
  409. $last = $this->is_last_in_cycle();
  410. if (!$last) {
  411. return -3;
  412. }
  413. }
  414. }
  415. }
  416. // Test if there is at least one payment. If yes, refuse to delete.
  417. if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) {
  418. return -4;
  419. }
  420. return 2;
  421. }
  422. /**
  423. * Return if an invoice was dispatched into bookkeeping
  424. *
  425. * @return int <0 if KO, 0=no, 1=yes
  426. */
  427. public function getVentilExportCompta()
  428. {
  429. $alreadydispatched = 0;
  430. $type = 'customer_invoice';
  431. if ($this->element == 'invoice_supplier') {
  432. $type = 'supplier_invoice';
  433. }
  434. $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);
  435. $resql = $this->db->query($sql);
  436. if ($resql) {
  437. $obj = $this->db->fetch_object($resql);
  438. if ($obj) {
  439. $alreadydispatched = $obj->nb;
  440. }
  441. } else {
  442. $this->error = $this->db->lasterror();
  443. return -1;
  444. }
  445. if ($alreadydispatched) {
  446. return 1;
  447. }
  448. return 0;
  449. }
  450. /**
  451. * Return label of type of invoice
  452. *
  453. * @return string Label of type of invoice
  454. */
  455. public function getLibType()
  456. {
  457. global $langs;
  458. if ($this->type == CommonInvoice::TYPE_STANDARD) {
  459. return $langs->trans("InvoiceStandard");
  460. } elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) {
  461. return $langs->trans("InvoiceReplacement");
  462. } elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) {
  463. return $langs->trans("InvoiceAvoir");
  464. } elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) {
  465. return $langs->trans("InvoiceDeposit");
  466. } elseif ($this->type == CommonInvoice::TYPE_PROFORMA) {
  467. return $langs->trans("InvoiceProForma"); // Not used.
  468. } elseif ($this->type == CommonInvoice::TYPE_SITUATION) {
  469. return $langs->trans("InvoiceSituation");
  470. }
  471. return $langs->trans("Unknown");
  472. }
  473. /**
  474. * Return label of object status
  475. *
  476. * @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
  477. * @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)
  478. * @return string Label of status
  479. */
  480. public function getLibStatut($mode = 0, $alreadypaid = -1)
  481. {
  482. return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
  483. }
  484. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  485. /**
  486. * Return label of a status
  487. *
  488. * @param int $paye Status field paye
  489. * @param int $status Id status
  490. * @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
  491. * @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)
  492. * @param int $type Type invoice. If -1, we use $this->type
  493. * @return string Label of status
  494. */
  495. public function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = -1)
  496. {
  497. // phpcs:enable
  498. global $langs;
  499. $langs->load('bills');
  500. if ($type == -1) {
  501. $type = $this->type;
  502. }
  503. $statusType = 'status0';
  504. $prefix = 'Short';
  505. if (!$paye) {
  506. if ($status == 0) {
  507. $labelStatus = $langs->transnoentitiesnoconv('BillStatusDraft');
  508. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusDraft');
  509. } elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
  510. $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedUnpaid');
  511. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedUnpaid');
  512. $statusType = 'status5';
  513. } elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
  514. $labelStatus = $langs->transnoentitiesnoconv('BillStatusClosedPaidPartially');
  515. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusClosedPaidPartially');
  516. $statusType = 'status9';
  517. } elseif ($alreadypaid == 0) {
  518. $labelStatus = $langs->transnoentitiesnoconv('BillStatusNotPaid');
  519. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusNotPaid');
  520. $statusType = 'status1';
  521. } else {
  522. $labelStatus = $langs->transnoentitiesnoconv('BillStatusStarted');
  523. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusStarted');
  524. $statusType = 'status3';
  525. }
  526. } else {
  527. $statusType = 'status6';
  528. if ($type == self::TYPE_CREDIT_NOTE) {
  529. $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaidBackOrConverted'); // credit note
  530. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
  531. } elseif ($type == self::TYPE_DEPOSIT) {
  532. $labelStatus = $langs->transnoentitiesnoconv('BillStatusConverted'); // deposit invoice
  533. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusConverted'); // deposit invoice
  534. } else {
  535. $labelStatus = $langs->transnoentitiesnoconv('BillStatusPaid');
  536. $labelStatusShort = $langs->transnoentitiesnoconv('Bill'.$prefix.'StatusPaid');
  537. }
  538. }
  539. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  540. }
  541. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  542. /**
  543. * Returns an invoice payment deadline based on the invoice settlement
  544. * conditions and billing date.
  545. *
  546. * @param integer $cond_reglement Condition of payment (code or id) to use. If 0, we use current condition.
  547. * @return integer Date limite de reglement si ok, <0 si ko
  548. */
  549. public function calculate_date_lim_reglement($cond_reglement = 0)
  550. {
  551. // phpcs:enable
  552. if (!$cond_reglement) {
  553. $cond_reglement = $this->cond_reglement_code;
  554. }
  555. if (!$cond_reglement) {
  556. $cond_reglement = $this->cond_reglement_id;
  557. }
  558. $cdr_nbjour = 0;
  559. $cdr_type = 0;
  560. $cdr_decalage = 0;
  561. $sqltemp = "SELECT c.type_cdr, c.nbjour, c.decalage";
  562. $sqltemp .= " FROM ".$this->db->prefix()."c_payment_term as c";
  563. if (is_numeric($cond_reglement)) {
  564. $sqltemp .= " WHERE c.rowid=".((int) $cond_reglement);
  565. } else {
  566. $sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
  567. $sqltemp .= " AND c.code = '".$this->db->escape($cond_reglement)."'";
  568. }
  569. dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
  570. $resqltemp = $this->db->query($sqltemp);
  571. if ($resqltemp) {
  572. if ($this->db->num_rows($resqltemp)) {
  573. $obj = $this->db->fetch_object($resqltemp);
  574. $cdr_nbjour = $obj->nbjour;
  575. $cdr_type = $obj->type_cdr;
  576. $cdr_decalage = $obj->decalage;
  577. }
  578. } else {
  579. $this->error = $this->db->error();
  580. return -1;
  581. }
  582. $this->db->free($resqltemp);
  583. /* Definition de la date limite */
  584. // 0 : adding the number of days
  585. if ($cdr_type == 0) {
  586. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  587. $datelim += ($cdr_decalage * 3600 * 24);
  588. } elseif ($cdr_type == 1) {
  589. // 1 : application of the "end of the month" rule
  590. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  591. $mois = date('m', $datelim);
  592. $annee = date('Y', $datelim);
  593. if ($mois == 12) {
  594. $mois = 1;
  595. $annee += 1;
  596. } else {
  597. $mois += 1;
  598. }
  599. // We move at the beginning of the next month, and we take a day off
  600. $datelim = dol_mktime(12, 0, 0, $mois, 1, $annee);
  601. $datelim -= (3600 * 24);
  602. $datelim += ($cdr_decalage * 3600 * 24);
  603. } elseif ($cdr_type == 2 && !empty($cdr_decalage)) {
  604. // 2 : application of the rule, the N of the current or next month
  605. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  606. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  607. $date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes
  608. $date_lim_current = dol_mktime(0, 0, 0, date('m', $datelim), $cdr_decalage, date('Y', $datelim)); // Sans les heures minutes et secondes
  609. $date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm'); // Add 1 month
  610. $diff = $date_piece - $date_lim_current;
  611. if ($diff < 0) {
  612. $datelim = $date_lim_current;
  613. } else {
  614. $datelim = $date_lim_next;
  615. }
  616. } else {
  617. return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
  618. }
  619. return $datelim;
  620. }
  621. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  622. /**
  623. * Create a withdrawal request for a direct debit order or a credit transfer order.
  624. * Use the remain to pay excluding all existing open direct debit requests.
  625. *
  626. * @param User $fuser User asking the direct debit transfer
  627. * @param float $amount Amount we request direct debit for
  628. * @param string $type 'direct-debit' or 'bank-transfer'
  629. * @param string $sourcetype Source ('facture' or 'supplier_invoice')
  630. * @return int <0 if KO, >0 if OK
  631. */
  632. public function demande_prelevement($fuser, $amount = 0, $type = 'direct-debit', $sourcetype = 'facture')
  633. {
  634. // phpcs:enable
  635. global $conf;
  636. $error = 0;
  637. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  638. if ($this->statut > self::STATUS_DRAFT && $this->paye == 0) {
  639. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  640. $bac = new CompanyBankAccount($this->db);
  641. $bac->fetch(0, $this->socid);
  642. $sql = "SELECT count(*)";
  643. $sql .= " FROM ".$this->db->prefix()."prelevement_facture_demande";
  644. if ($type == 'bank-transfer') {
  645. $sql .= " WHERE fk_facture_fourn = ".((int) $this->id);
  646. } else {
  647. $sql .= " WHERE fk_facture = ".((int) $this->id);
  648. }
  649. $sql .= " AND ext_payment_id IS NULL"; // To exclude record done for some online payments
  650. $sql .= " AND traite = 0";
  651. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  652. $resql = $this->db->query($sql);
  653. if ($resql) {
  654. $row = $this->db->fetch_row($resql);
  655. if ($row[0] == 0) {
  656. $now = dol_now();
  657. $totalpaid = $this->getSommePaiement();
  658. $totalcreditnotes = $this->getSumCreditNotesUsed();
  659. $totaldeposits = $this->getSumDepositsUsed();
  660. //print "totalpaid=".$totalpaid." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits;
  661. // We can also use bcadd to avoid pb with floating points
  662. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  663. //$resteapayer=bcadd($this->total_ttc,$totalpaid,$conf->global->MAIN_MAX_DECIMALS_TOT);
  664. //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  665. if (empty($amount)) {
  666. $amount = price2num($this->total_ttc - $totalpaid - $totalcreditnotes - $totaldeposits, 'MT');
  667. }
  668. if (is_numeric($amount) && $amount != 0) {
  669. $sql = 'INSERT INTO '.$this->db->prefix().'prelevement_facture_demande(';
  670. if ($type == 'bank-transfer') {
  671. $sql .= 'fk_facture_fourn, ';
  672. } else {
  673. $sql .= 'fk_facture, ';
  674. }
  675. $sql .= ' amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib, sourcetype, entity)';
  676. $sql .= " VALUES (".((int) $this->id);
  677. $sql .= ", ".((float) price2num($amount));
  678. $sql .= ", '".$this->db->idate($now)."'";
  679. $sql .= ", ".((int) $fuser->id);
  680. $sql .= ", '".$this->db->escape($bac->code_banque)."'";
  681. $sql .= ", '".$this->db->escape($bac->code_guichet)."'";
  682. $sql .= ", '".$this->db->escape($bac->number)."'";
  683. $sql .= ", '".$this->db->escape($bac->cle_rib)."'";
  684. $sql .= ", '".$this->db->escape($sourcetype)."'";
  685. $sql .= ", ".((int) $conf->entity);
  686. $sql .= ")";
  687. dol_syslog(get_class($this)."::demande_prelevement", LOG_DEBUG);
  688. $resql = $this->db->query($sql);
  689. if (!$resql) {
  690. $this->error = $this->db->lasterror();
  691. dol_syslog(get_class($this).'::demandeprelevement Erreur');
  692. $error++;
  693. }
  694. } else {
  695. $this->error = 'WithdrawRequestErrorNilAmount';
  696. dol_syslog(get_class($this).'::demandeprelevement WithdrawRequestErrorNilAmount');
  697. $error++;
  698. }
  699. if (!$error) {
  700. // Force payment mode of invoice to withdraw
  701. $payment_mode_id = dol_getIdFromCode($this->db, ($type == 'bank-transfer' ? 'VIR' : 'PRE'), 'c_paiement', 'code', 'id', 1);
  702. if ($payment_mode_id > 0) {
  703. $result = $this->setPaymentMethods($payment_mode_id);
  704. }
  705. }
  706. if ($error) {
  707. return -1;
  708. }
  709. return 1;
  710. } else {
  711. $this->error = "A request already exists";
  712. dol_syslog(get_class($this).'::demandeprelevement Impossible de creer une demande, demande deja en cours');
  713. return 0;
  714. }
  715. } else {
  716. $this->error = $this->db->error();
  717. dol_syslog(get_class($this).'::demandeprelevement Erreur -2');
  718. return -2;
  719. }
  720. } else {
  721. $this->error = "Status of invoice does not allow this";
  722. dol_syslog(get_class($this)."::demandeprelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
  723. return -3;
  724. }
  725. }
  726. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  727. /**
  728. * Remove a direct debit request or a credit transfer request
  729. *
  730. * @param User $fuser User making delete
  731. * @param int $did ID of request to delete
  732. * @return int <0 if OK, >0 if KO
  733. */
  734. public function demande_prelevement_delete($fuser, $did)
  735. {
  736. // phpcs:enable
  737. $sql = 'DELETE FROM '.$this->db->prefix().'prelevement_facture_demande';
  738. $sql .= ' WHERE rowid = '.((int) $did);
  739. $sql .= ' AND traite = 0';
  740. if ($this->db->query($sql)) {
  741. return 0;
  742. } else {
  743. $this->error = $this->db->lasterror();
  744. dol_syslog(get_class($this).'::demande_prelevement_delete Error '.$this->error);
  745. return -1;
  746. }
  747. }
  748. /**
  749. * Build string for ZATCA QR Code (Arabi Saudia)
  750. *
  751. * @return string String for ZATCA QR Code
  752. */
  753. public function buildZATCAQRString()
  754. {
  755. global $conf, $mysoc;
  756. $tmplang = new Translate('', $conf);
  757. $tmplang->setDefaultLang('en_US');
  758. $tmplang->load("main");
  759. $datestring = dol_print_date($this->date, 'dayhourrfc');
  760. //$pricewithtaxstring = price($this->total_ttc, 0, $tmplang, 0, -1, 2);
  761. //$pricetaxstring = price($this->total_tva, 0, $tmplang, 0, -1, 2);
  762. $pricewithtaxstring = price2num($this->total_ttc, 2, 1);
  763. $pricetaxstring = price2num($this->total_tva, 2, 1);
  764. /*
  765. $name = implode(unpack("H*", $this->thirdparty->name));
  766. $vatnumber = implode(unpack("H*", $this->thirdparty->tva_intra));
  767. $date = implode(unpack("H*", $datestring));
  768. $pricewithtax = implode(unpack("H*", price2num($pricewithtaxstring, 2)));
  769. $pricetax = implode(unpack("H*", $pricetaxstring));
  770. //var_dump(strlen($this->thirdparty->name));
  771. //var_dump(str_pad(dechex('9'), 2, '0', STR_PAD_LEFT));
  772. //var_dump($this->thirdparty->name);
  773. //var_dump(implode(unpack("H*", $this->thirdparty->name)));
  774. //var_dump(price($this->total_tva, 0, $tmplang, 0, -1, 2));
  775. $s = '01'.str_pad(dechex(strlen($this->thirdparty->name)), 2, '0', STR_PAD_LEFT).$name;
  776. $s .= '02'.str_pad(dechex(strlen($this->thirdparty->tva_intra)), 2, '0', STR_PAD_LEFT).$vatnumber;
  777. $s .= '03'.str_pad(dechex(strlen($datestring)), 2, '0', STR_PAD_LEFT).$date;
  778. $s .= '04'.str_pad(dechex(strlen($pricewithtaxstring)), 2, '0', STR_PAD_LEFT).$pricewithtax;
  779. $s .= '05'.str_pad(dechex(strlen($pricetaxstring)), 2, '0', STR_PAD_LEFT).$pricetax;
  780. $s .= ''; // Hash of xml invoice
  781. $s .= ''; // ecda signature
  782. $s .= ''; // ecda public key
  783. $s .= ''; // ecda signature of public key stamp
  784. */
  785. // Using TLV format
  786. $s = pack('C1', 1).pack('C1', strlen($mysoc->name)).$mysoc->name;
  787. $s .= pack('C1', 2).pack('C1', strlen($mysoc->tva_intra)).$mysoc->tva_intra;
  788. $s .= pack('C1', 3).pack('C1', strlen($datestring)).$datestring;
  789. $s .= pack('C1', 4).pack('C1', strlen($pricewithtaxstring)).$pricewithtaxstring;
  790. $s .= pack('C1', 5).pack('C1', strlen($pricetaxstring)).$pricetaxstring;
  791. $s .= ''; // Hash of xml invoice
  792. $s .= ''; // ecda signature
  793. $s .= ''; // ecda public key
  794. $s .= ''; // ecda signature of public key stamp
  795. $s = base64_encode($s);
  796. return $s;
  797. }
  798. }
  799. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  800. /**
  801. * Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...)
  802. */
  803. abstract class CommonInvoiceLine extends CommonObjectLine
  804. {
  805. /**
  806. * Custom label of line. Not used by default.
  807. * @deprecated
  808. */
  809. public $label;
  810. /**
  811. * @deprecated
  812. * @see $product_ref
  813. */
  814. public $ref; // Product ref (deprecated)
  815. /**
  816. * @deprecated
  817. * @see $product_label
  818. */
  819. public $libelle; // Product label (deprecated)
  820. /**
  821. * Type of the product. 0 for product 1 for service
  822. * @var int
  823. */
  824. public $product_type = 0;
  825. /**
  826. * Product ref
  827. * @var string
  828. */
  829. public $product_ref;
  830. /**
  831. * Product label
  832. * @var string
  833. */
  834. public $product_label;
  835. /**
  836. * Product description
  837. * @var string
  838. */
  839. public $product_desc;
  840. /**
  841. * Quantity
  842. * @var double
  843. */
  844. public $qty;
  845. /**
  846. * Unit price before taxes
  847. * @var float
  848. */
  849. public $subprice;
  850. /**
  851. * Unit price before taxes
  852. * @var float
  853. * @deprecated
  854. */
  855. public $price;
  856. /**
  857. * Id of corresponding product
  858. * @var int
  859. */
  860. public $fk_product;
  861. /**
  862. * VAT code
  863. * @var string
  864. */
  865. public $vat_src_code;
  866. /**
  867. * VAT %
  868. * @var float
  869. */
  870. public $tva_tx;
  871. /**
  872. * Local tax 1 %
  873. * @var float
  874. */
  875. public $localtax1_tx;
  876. /**
  877. * Local tax 2 %
  878. * @var float
  879. */
  880. public $localtax2_tx;
  881. /**
  882. * Local tax 1 type
  883. * @var string
  884. */
  885. public $localtax1_type;
  886. /**
  887. * Local tax 2 type
  888. * @var string
  889. */
  890. public $localtax2_type;
  891. /**
  892. * Percent of discount
  893. * @var float
  894. */
  895. public $remise_percent;
  896. /**
  897. * Fixed discount
  898. * @var float
  899. * @deprecated
  900. */
  901. public $remise;
  902. /**
  903. * Total amount before taxes
  904. * @var float
  905. */
  906. public $total_ht;
  907. /**
  908. * Total VAT amount
  909. * @var float
  910. */
  911. public $total_tva;
  912. /**
  913. * Total local tax 1 amount
  914. * @var float
  915. */
  916. public $total_localtax1;
  917. /**
  918. * Total local tax 2 amount
  919. * @var float
  920. */
  921. public $total_localtax2;
  922. /**
  923. * Total amount with taxes
  924. * @var float
  925. */
  926. public $total_ttc;
  927. 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
  928. 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
  929. public $buy_price_ht;
  930. public $buyprice; // For backward compatibility
  931. public $pa_ht; // For backward compatibility
  932. public $marge_tx;
  933. public $marque_tx;
  934. /**
  935. * List of cumulative options:
  936. * Bit 0: 0 for common VAT - 1 if VAT french NPR
  937. * Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
  938. * @var int
  939. */
  940. public $info_bits = 0;
  941. public $special_code = 0;
  942. public $fk_multicurrency;
  943. public $multicurrency_code;
  944. public $multicurrency_subprice;
  945. public $multicurrency_total_ht;
  946. public $multicurrency_total_tva;
  947. public $multicurrency_total_ttc;
  948. public $fk_user_author;
  949. public $fk_user_modif;
  950. }