commoninvoice.class.php 33 KB

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