PageRenderTime 96ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/htdocs/compta/facture/class/facture.class.php

https://github.com/asterix14/dolibarr
PHP | 3728 lines | 2749 code | 389 blank | 590 comment | 551 complexity | 760d6de4a516384bb404a5d802953648 MD5 | raw file
Possible License(s): LGPL-2.0
  1. <?php
  2. /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  5. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  6. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  7. * Copyright (C) 2005-2011 Regis Houssin <regis@dolibarr.fr>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  10. * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/compta/facture/class/facture.class.php
  27. * \ingroup facture
  28. * \brief File of class to manage invoices
  29. */
  30. require_once(DOL_DOCUMENT_ROOT ."/core/class/commonobject.class.php");
  31. require_once(DOL_DOCUMENT_ROOT ."/product/class/product.class.php");
  32. require_once(DOL_DOCUMENT_ROOT ."/societe/class/client.class.php");
  33. /**
  34. * \class Facture
  35. * \brief Class to manage invoices
  36. */
  37. class Facture extends CommonObject
  38. {
  39. public $element='facture';
  40. public $table_element='facture';
  41. public $table_element_line = 'facturedet';
  42. public $fk_element = 'fk_facture';
  43. protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  44. var $id;
  45. //! Id client
  46. var $socid;
  47. //! Objet societe client (to load with fetch_client method)
  48. var $client;
  49. var $author;
  50. var $fk_user_author;
  51. var $fk_user_valid;
  52. //! Invoice date
  53. var $date; // Invoice date
  54. var $date_creation; // Creation date
  55. var $date_validation; // Validation date
  56. var $datem;
  57. var $ref;
  58. var $ref_client;
  59. var $ref_ext;
  60. var $ref_int;
  61. //! 0=Standard invoice, 1=Replacement invoice, 2=Credit note invoice, 3=Deposit invoice, 4=Proforma invoice
  62. var $type;
  63. var $amount;
  64. var $remise;
  65. var $total_ht;
  66. var $total_tva;
  67. var $total_ttc;
  68. var $note;
  69. var $note_public;
  70. //! 0=draft,
  71. //! 1=validated (need to be paid),
  72. //! 2=classified paid partially (close_code='discount_vat','badcustomer') or completely (close_code=null),
  73. //! 3=classified abandoned and no payment done (close_code='badcustomer','abandon' ou 'replaced')
  74. var $statut;
  75. //! Fermeture apres paiement partiel: discount_vat, badcustomer, abandon
  76. //! Fermeture alors que aucun paiement: replaced (si remplace), abandon
  77. var $close_code;
  78. //! Commentaire si mis a paye sans paiement complet
  79. var $close_note;
  80. //! 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code
  81. var $paye;
  82. //! id of source invoice if replacement invoice or credit note
  83. var $fk_facture_source;
  84. var $origin;
  85. var $origin_id;
  86. var $fk_project;
  87. var $date_lim_reglement;
  88. var $cond_reglement_id; // Id in llx_c_paiement
  89. var $cond_reglement_code; // Code in llx_c_paiement
  90. var $mode_reglement_id; // Id in llx_c_paiement
  91. var $mode_reglement_code; // Code in llx_c_paiement
  92. var $modelpdf;
  93. var $products=array(); // TODO deprecated
  94. var $lines=array();
  95. var $line;
  96. //! Pour board
  97. var $nbtodo;
  98. var $nbtodolate;
  99. var $specimen;
  100. //! Numero d'erreur de 512 a 1023
  101. var $errno = 0;
  102. /**
  103. * Constructor
  104. *
  105. * @param DoliDB $DB Database handler
  106. */
  107. function Facture($DB)
  108. {
  109. $this->db = $DB;
  110. $this->amount = 0;
  111. $this->remise = 0;
  112. $this->remise_percent = 0;
  113. $this->total_ht = 0;
  114. $this->total_tva = 0;
  115. $this->total_ttc = 0;
  116. $this->propalid = 0;
  117. $this->fk_project = 0;
  118. $this->remise_exceptionnelle = 0;
  119. }
  120. /**
  121. * Create invoice in database
  122. * Note: this->ref can be set or empty. If empty, we will use "(PROV)"
  123. *
  124. * @param User $user Object user that create
  125. * @param int $notrigger 1=Does not execute triggers, 0 otherwise
  126. * @param int $forceduedate 1=Do not recalculate due date from payment condition but force it with value
  127. * @return int <0 if KO, >0 if OK
  128. */
  129. function create($user,$notrigger=0,$forceduedate=0)
  130. {
  131. global $langs,$conf,$mysoc;
  132. $error=0;
  133. // Clean parameters
  134. if (! $this->type) $this->type = 0;
  135. $this->ref_client=trim($this->ref_client);
  136. $this->note=trim($this->note);
  137. $this->note_public=trim($this->note_public);
  138. if (! $this->remise) $this->remise = 0;
  139. if (! $this->cond_reglement_id) $this->cond_reglement_id = 0;
  140. if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
  141. $this->brouillon = 1;
  142. dol_syslog("Facture::Create user=".$user->id);
  143. // Check parameters
  144. if (empty($this->date) || empty($user->id))
  145. {
  146. $this->error="ErrorBadParameter";
  147. dol_syslog("Facture::create Try to create an invoice with an empty parameter (user, date, ...)", LOG_ERR);
  148. return -3;
  149. }
  150. $soc = new Societe($this->db);
  151. $result=$soc->fetch($this->socid);
  152. if ($result < 0)
  153. {
  154. $this->error="Failed to fetch company";
  155. dol_syslog("Facture::create ".$this->error, LOG_ERR);
  156. return -2;
  157. }
  158. $now=dol_now();
  159. $this->db->begin();
  160. // Create invoice from a predefined invoice
  161. if ($this->fac_rec > 0)
  162. {
  163. require_once(DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php');
  164. $_facrec = new FactureRec($this->db);
  165. $result=$_facrec->fetch($this->fac_rec);
  166. $this->fk_project = $_facrec->fk_project;
  167. $this->cond_reglement = $_facrec->cond_reglement_id;
  168. $this->cond_reglement_id = $_facrec->cond_reglement_id;
  169. $this->mode_reglement = $_facrec->mode_reglement_id;
  170. $this->mode_reglement_id = $_facrec->mode_reglement_id;
  171. $this->amount = $_facrec->amount;
  172. $this->remise_absolue = $_facrec->remise_absolue;
  173. $this->remise_percent = $_facrec->remise_percent;
  174. $this->remise = $_facrec->remise;
  175. // Clean parametres
  176. if (! $this->type) $this->type = 0;
  177. $this->ref_client=trim($this->ref_client);
  178. $this->note=trim($this->note);
  179. $this->note_public=trim($this->note_public);
  180. if (! $this->remise) $this->remise = 0;
  181. if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
  182. $this->brouillon = 1;
  183. }
  184. // Define due date if not already defined
  185. $datelim=(empty($forceduedate)?$this->calculate_date_lim_reglement():$forceduedate);
  186. // Insert into database
  187. $socid = $this->socid;
  188. $amount = $this->amount;
  189. $remise = $this->remise;
  190. $totalht = ($amount - $remise);
  191. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
  192. $sql.= " facnumber";
  193. $sql.= ", entity";
  194. $sql.= ", type";
  195. $sql.= ", fk_soc";
  196. $sql.= ", datec";
  197. $sql.= ", amount";
  198. $sql.= ", remise_absolue";
  199. $sql.= ", remise_percent";
  200. $sql.= ", datef";
  201. $sql.= ", note";
  202. $sql.= ", note_public";
  203. $sql.= ", ref_client, ref_int";
  204. $sql.= ", fk_facture_source, fk_user_author, fk_projet";
  205. $sql.= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
  206. $sql.= ")";
  207. $sql.= " VALUES (";
  208. $sql.= "'(PROV)'";
  209. $sql.= ", ".$conf->entity;
  210. $sql.= ", '".$this->type."'";
  211. $sql.= ", '".$socid."'";
  212. $sql.= ", '".$this->db->idate($now)."'";
  213. $sql.= ", '".$totalht."'";
  214. $sql.= ",".($this->remise_absolue>0?$this->remise_absolue:'NULL');
  215. $sql.= ",".($this->remise_percent>0?$this->remise_percent:'NULL');
  216. $sql.= ", '".$this->db->idate($this->date)."'";
  217. $sql.= ",".($this->note?"'".$this->db->escape($this->note)."'":"null");
  218. $sql.= ",".($this->note_public?"'".$this->db->escape($this->note_public)."'":"null");
  219. $sql.= ",".($this->ref_client?"'".$this->db->escape($this->ref_client)."'":"null");
  220. $sql.= ",".($this->ref_int?"'".$this->db->escape($this->ref_int)."'":"null");
  221. $sql.= ",".($this->fk_facture_source?"'".$this->db->escape($this->fk_facture_source)."'":"null");
  222. $sql.= ",".($user->id > 0 ? "'".$user->id."'":"null");
  223. $sql.= ",".($this->fk_project?$this->fk_project:"null");
  224. $sql.= ','.$this->cond_reglement_id;
  225. $sql.= ",".$this->mode_reglement_id;
  226. $sql.= ", '".$this->db->idate($datelim)."', '".$this->modelpdf."')";
  227. dol_syslog("Facture::Create sql=".$sql);
  228. $resql=$this->db->query($sql);
  229. if ($resql)
  230. {
  231. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
  232. // Update ref with new one
  233. $this->ref='(PROV'.$this->id.')';
  234. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET facnumber='".$this->ref."' WHERE rowid=".$this->id;
  235. dol_syslog("Facture::create sql=".$sql);
  236. $resql=$this->db->query($sql);
  237. if (! $resql) $error++;
  238. // Add object linked
  239. if (! $error && $this->id && $this->origin && $this->origin_id)
  240. {
  241. $ret = $this->add_object_linked();
  242. if (! $ret)
  243. {
  244. dol_print_error($this->db);
  245. $error++;
  246. }
  247. }
  248. /*
  249. * Insert lines of invoices into database
  250. */
  251. if (count($this->lines) && is_object($this->lines[0]))
  252. {
  253. $fk_parent_line = 0;
  254. dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
  255. foreach ($this->lines as $i => $val)
  256. {
  257. $newinvoiceline=new FactureLigne($this->db);
  258. $newinvoiceline=$this->lines[$i];
  259. $newinvoiceline->fk_facture=$this->id;
  260. if ($result >= 0 && ($newinvoiceline->info_bits & 0x01) == 0) // We keep only lines with first bit = 0
  261. {
  262. // Reset fk_parent_line for no child products and special product
  263. if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
  264. $fk_parent_line = 0;
  265. }
  266. $newinvoiceline->fk_parent_line=$fk_parent_line;
  267. $result=$newinvoiceline->insert();
  268. // Defined the new fk_parent_line
  269. if ($result > 0 && $newinvoiceline->product_type == 9) {
  270. $fk_parent_line = $result;
  271. }
  272. }
  273. if ($result < 0)
  274. {
  275. $this->error=$newinvoiceline->error;
  276. $error++;
  277. break;
  278. }
  279. }
  280. }
  281. else
  282. {
  283. $fk_parent_line = 0;
  284. dol_syslog("There is ".count($this->lines)." lines that are array lines");
  285. foreach ($this->lines as $i => $val)
  286. {
  287. if (($this->lines[$i]->info_bits & 0x01) == 0) // We keep only lines with first bit = 0
  288. {
  289. // Reset fk_parent_line for no child products and special product
  290. if (($this->lines[$i]->product_type != 9 && empty($this->lines[$i]->fk_parent_line)) || $this->lines[$i]->product_type == 9) {
  291. $fk_parent_line = 0;
  292. }
  293. $result = $this->addline(
  294. $this->id,
  295. $this->lines[$i]->desc,
  296. $this->lines[$i]->subprice,
  297. $this->lines[$i]->qty,
  298. $this->lines[$i]->tva_tx,
  299. $this->lines[$i]->localtax1_tx,
  300. $this->lines[$i]->localtax2_tx,
  301. $this->lines[$i]->fk_product,
  302. $this->lines[$i]->remise_percent,
  303. $this->lines[$i]->date_start,
  304. $this->lines[$i]->date_end,
  305. $this->lines[$i]->fk_code_ventilation,
  306. $this->lines[$i]->info_bits,
  307. $this->lines[$i]->fk_remise_except,
  308. 'HT',
  309. 0,
  310. $this->lines[$i]->product_type,
  311. $this->lines[$i]->rang,
  312. $this->lines[$i]->special_code,
  313. '',
  314. 0,
  315. $fk_parent_line
  316. );
  317. if ($result < 0)
  318. {
  319. $this->error=$this->db->lasterror();
  320. dol_print_error($this->db);
  321. $this->db->rollback();
  322. return -1;
  323. }
  324. // Defined the new fk_parent_line
  325. if ($result > 0 && $this->lines[$i]->product_type == 9) {
  326. $fk_parent_line = $result;
  327. }
  328. }
  329. }
  330. }
  331. /*
  332. * Insert lines of predefined invoices
  333. */
  334. if (! $error && $this->fac_rec > 0)
  335. {
  336. foreach ($_facrec->lines as $i => $val)
  337. {
  338. if ($_facrec->lines[$i]->fk_product)
  339. {
  340. $prod = new Product($this->db);
  341. $res=$prod->fetch($_facrec->lines[$i]->fk_product);
  342. }
  343. $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
  344. $localtax1_tx=get_localtax($tva_tx,1,$soc);
  345. $localtax2_tx=get_localtax($tva_tx,2,$soc);
  346. $result_insert = $this->addline(
  347. $this->id,
  348. $_facrec->lines[$i]->desc,
  349. $_facrec->lines[$i]->subprice,
  350. $_facrec->lines[$i]->qty,
  351. $tva_tx,
  352. $localtax1_tx,
  353. $localtax2_tx,
  354. $_facrec->lines[$i]->fk_product,
  355. $_facrec->lines[$i]->remise_percent,
  356. '','',0,0,'','HT',0,
  357. $_facrec->lines[$i]->product_type,
  358. $_facrec->lines[$i]->rang,
  359. $_facrec->lines[$i]->special_code
  360. );
  361. if ( $result_insert < 0)
  362. {
  363. $error++;
  364. $this->error=$this->db->error();
  365. break;
  366. }
  367. }
  368. }
  369. if (! $error)
  370. {
  371. $result=$this->update_price(1);
  372. if ($result > 0)
  373. {
  374. // Appel des triggers
  375. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  376. $interface=new Interfaces($this->db);
  377. $result=$interface->run_triggers('BILL_CREATE',$this,$user,$langs,$conf);
  378. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  379. // Fin appel triggers
  380. if (! $error)
  381. {
  382. $this->db->commit();
  383. return $this->id;
  384. }
  385. else
  386. {
  387. $this->db->rollback();
  388. return -4;
  389. }
  390. }
  391. else
  392. {
  393. $this->error=$langs->trans('FailedToUpdatePrice');
  394. $this->db->rollback();
  395. return -3;
  396. }
  397. }
  398. else
  399. {
  400. dol_syslog("Facture::create error ".$this->error, LOG_ERR);
  401. $this->db->rollback();
  402. return -2;
  403. }
  404. }
  405. else
  406. {
  407. $this->error=$this->db->error();
  408. dol_syslog("Facture::create error ".$this->error." sql=".$sql, LOG_ERR);
  409. $this->db->rollback();
  410. return -1;
  411. }
  412. }
  413. /**
  414. * Create a new invoice in database from current invoice
  415. *
  416. * @param user Object user that ask creation
  417. * @param invertdetail Reverse sign of amounts for lines
  418. * @return int <0 if KO, >0 if OK
  419. */
  420. function createFromCurrent($user,$invertdetail=0)
  421. {
  422. // Charge facture source
  423. $facture=new Facture($this->db);
  424. $facture->fk_facture_source = $this->fk_facture_source;
  425. $facture->type = $this->type;
  426. $facture->socid = $this->socid;
  427. $facture->date = $this->date;
  428. $facture->note_public = $this->note_public;
  429. $facture->note = $this->note;
  430. $facture->ref_client = $this->ref_client;
  431. $facture->modelpdf = $this->modelpdf;
  432. $facture->fk_project = $this->fk_project;
  433. $facture->cond_reglement_id = $this->cond_reglement_id;
  434. $facture->mode_reglement_id = $this->mode_reglement_id;
  435. $facture->amount = $this->amount;
  436. $facture->remise_absolue = $this->remise_absolue;
  437. $facture->remise_percent = $this->remise_percent;
  438. $facture->lines = $this->lines; // Tableau des lignes de factures
  439. $facture->products = $this->lines; // Tant que products encore utilise
  440. // Loop on each line of new invoice
  441. foreach($facture->lines as $i => $line)
  442. {
  443. if ($invertdetail)
  444. {
  445. $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
  446. $facture->lines[$i]->price = -$facture->lines[$i]->price;
  447. $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
  448. $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
  449. $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
  450. $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
  451. $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
  452. }
  453. }
  454. dol_syslog("Facture::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
  455. $facid = $facture->create($user);
  456. if ($facid <= 0)
  457. {
  458. $this->error=$facture->error;
  459. $this->errors=$facture->errors;
  460. }
  461. return $facid;
  462. }
  463. /**
  464. * Load an object from its id and create a new one in database
  465. *
  466. * @param int $fromid Id of object to clone
  467. * @param int $invertdetail Reverse sign of amounts for lines
  468. * @param HookManager $hookmanager Hook manager instance
  469. * @return int New id of clone
  470. */
  471. function createFromClone($fromid,$invertdetail=0,$hookmanager=false)
  472. {
  473. global $conf,$user,$langs;
  474. $error=0;
  475. // Load source object
  476. $objFrom=new Facture($this->db);
  477. $objFrom->fetch($fromid);
  478. // Load new object
  479. $object=new Facture($this->db);
  480. $object->fetch($fromid);
  481. $this->db->begin();
  482. $object->id=0;
  483. $object->statut=0;
  484. // Clear fields
  485. $object->user_author = $user->id;
  486. $object->user_valid = '';
  487. $object->fk_facture_source = 0;
  488. $object->date_creation = '';
  489. $object->date_validation = '';
  490. $object->ref_client = '';
  491. $object->close_code = '';
  492. $object->close_note = '';
  493. $object->products = $object->lines; // Tant que products encore utilise
  494. // Loop on each line of new invoice
  495. foreach($object->lines as $i => $line)
  496. {
  497. if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts
  498. {
  499. unset($object->lines[$i]);
  500. unset($object->products[$i]); // Tant que products encore utilise
  501. }
  502. }
  503. // Create clone
  504. $result=$object->create($user);
  505. // Other options
  506. if ($result < 0)
  507. {
  508. $this->error=$object->error;
  509. $error++;
  510. }
  511. if (! $error)
  512. {
  513. // Hook of thirdparty module
  514. if (is_object($hookmanager))
  515. {
  516. $parameters=array('objFrom'=>$objFrom);
  517. $action='';
  518. $reshook=$hookmanager->executeHooks('createfrom',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
  519. if ($reshook < 0) $error++;
  520. }
  521. // Appel des triggers
  522. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  523. $interface=new Interfaces($this->db);
  524. $result=$interface->run_triggers('BILL_CLONE',$object,$user,$langs,$conf);
  525. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  526. // Fin appel triggers
  527. }
  528. // End
  529. if (! $error)
  530. {
  531. $this->db->commit();
  532. return $object->id;
  533. }
  534. else
  535. {
  536. $this->db->rollback();
  537. return -1;
  538. }
  539. }
  540. /**
  541. * Load an object from an order and create a new invoice into database
  542. *
  543. * @param Object $object Object source
  544. * @return int <0 if KO, 0 if nothing done, 1 if OK
  545. */
  546. function createFromOrder($object)
  547. {
  548. global $conf,$user,$langs;
  549. $error=0;
  550. // Closed order
  551. $this->date = dol_now();
  552. $this->source = 0;
  553. $num=count($object->lines);
  554. for ($i = 0; $i < $num; $i++)
  555. {
  556. $line = new FactureLigne($this->db);
  557. $line->libelle = $object->lines[$i]->libelle;
  558. $line->desc = $object->lines[$i]->desc;
  559. $line->price = $object->lines[$i]->price;
  560. $line->subprice = $object->lines[$i]->subprice;
  561. $line->total_ht = $object->lines[$i]->total_ht;
  562. $line->total_tva = $object->lines[$i]->total_tva;
  563. $line->total_ttc = $object->lines[$i]->total_ttc;
  564. $line->tva_tx = $object->lines[$i]->tva_tx;
  565. $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
  566. $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
  567. $line->qty = $object->lines[$i]->qty;
  568. $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
  569. $line->remise_percent = $object->lines[$i]->remise_percent;
  570. $line->fk_product = $object->lines[$i]->fk_product;
  571. $line->info_bits = $object->lines[$i]->info_bits;
  572. $line->product_type = $object->lines[$i]->product_type;
  573. $line->rang = $object->lines[$i]->rang;
  574. $line->special_code = $object->lines[$i]->special_code;
  575. $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
  576. $this->lines[$i] = $line;
  577. }
  578. $this->socid = $object->socid;
  579. $this->fk_project = $object->fk_project;
  580. $this->cond_reglement_id = $object->cond_reglement_id;
  581. $this->mode_reglement_id = $object->mode_reglement_id;
  582. $this->availability_id = $object->availability_id;
  583. $this->demand_reason_id = $object->demand_reason_id;
  584. $this->date_livraison = $object->date_livraison;
  585. $this->fk_delivery_address = $object->fk_delivery_address;
  586. $this->contact_id = $object->contactid;
  587. $this->ref_client = $object->ref_client;
  588. $this->note = $object->note;
  589. $this->note_public = $object->note_public;
  590. $this->origin = $object->element;
  591. $this->origin_id = $object->id;
  592. $ret = $this->create($user);
  593. if ($ret > 0)
  594. {
  595. // Actions hooked (by external module)
  596. include_once(DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php');
  597. $hookmanager=new HookManager($this->db);
  598. $hookmanager->callHooks(array('invoicedao'));
  599. $parameters=array('objFrom'=>$object);
  600. $action='';
  601. $reshook=$hookmanager->executeHooks('createfrom',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  602. if ($reshook < 0) $error++;
  603. if (! $error)
  604. {
  605. return 1;
  606. }
  607. else return -1;
  608. }
  609. else return -1;
  610. }
  611. /**
  612. * Return clicable link of object (with eventually picto)
  613. *
  614. * @param withpicto Add picto into link
  615. * @param option Where point the link
  616. * @param max Maxlength of ref
  617. * @return string String with URL
  618. */
  619. function getNomUrl($withpicto=0,$option='',$max=0,$short=0)
  620. {
  621. global $langs;
  622. $result='';
  623. if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
  624. else $url = DOL_URL_ROOT.'/compta/facture.php?facid='.$this->id;
  625. if ($short) return $url;
  626. $linkstart='<a href="'.$url.'">';
  627. $linkend='</a>';
  628. $picto='bill';
  629. if ($this->type == 1) $picto.='r'; // Replacement invoice
  630. if ($this->type == 2) $picto.='a'; // Credit note
  631. if ($this->type == 3) $picto.='d'; // Deposit invoice
  632. $label=$langs->trans("ShowInvoice").': '.$this->ref;
  633. if ($this->type == 1) $label=$langs->trans("ShowInvoiceReplace").': '.$this->ref;
  634. if ($this->type == 2) $label=$langs->trans("ShowInvoiceAvoir").': '.$this->ref;
  635. if ($this->type == 3) $label=$langs->trans("ShowInvoiceDeposit").': '.$this->ref;
  636. if ($withpicto) $result.=($linkstart.img_object($label,$picto).$linkend);
  637. if ($withpicto && $withpicto != 2) $result.=' ';
  638. if ($withpicto != 2) $result.=$linkstart.($max?dol_trunc($this->ref,$max):$this->ref).$linkend;
  639. return $result;
  640. }
  641. /**
  642. * Get object and lines from database
  643. *
  644. * @param rowid Id of object to load
  645. * @param ref Reference of invoice
  646. * @param ref_ext External reference of invoice
  647. * @param ref_int Internal reference of other object
  648. * @return int >0 if OK, <0 if KO
  649. */
  650. function fetch($rowid, $ref='', $ref_ext='', $ref_int='')
  651. {
  652. global $conf;
  653. if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int)) return -1;
  654. $sql = 'SELECT f.rowid,f.facnumber,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc,f.amount,f.tva, f.localtax1, f.localtax2, f.total,f.total_ttc,f.remise_percent,f.remise_absolue,f.remise';
  655. $sql.= ', f.datef as df';
  656. $sql.= ', f.date_lim_reglement as dlr';
  657. $sql.= ', f.datec as datec';
  658. $sql.= ', f.date_valid as datev';
  659. $sql.= ', f.tms as datem';
  660. $sql.= ', f.note, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf';
  661. $sql.= ', f.fk_facture_source';
  662. $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet';
  663. $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  664. $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  665. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as f';
  666. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  667. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  668. $sql.= ' WHERE f.entity = '.$conf->entity;
  669. if ($rowid) $sql.= " AND f.rowid=".$rowid;
  670. if ($ref) $sql.= " AND f.facnumber='".$this->db->escape($ref)."'";
  671. if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  672. if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
  673. dol_syslog("Facture::Fetch sql=".$sql, LOG_DEBUG);
  674. $result = $this->db->query($sql);
  675. if ($result)
  676. {
  677. if ($this->db->num_rows($result))
  678. {
  679. $obj = $this->db->fetch_object($result);
  680. $this->id = $obj->rowid;
  681. $this->ref = $obj->facnumber;
  682. $this->ref_client = $obj->ref_client;
  683. $this->ref_ext = $obj->ref_ext;
  684. $this->ref_int = $obj->ref_int;
  685. $this->type = $obj->type;
  686. $this->date = $this->db->jdate($obj->df);
  687. $this->date_creation = $this->db->jdate($obj->datec);
  688. $this->date_validation = $this->db->jdate($obj->datev);
  689. $this->datem = $this->db->jdate($obj->datem);
  690. $this->amount = $obj->amount;
  691. $this->remise_percent = $obj->remise_percent;
  692. $this->remise_absolue = $obj->remise_absolue;
  693. $this->remise = $obj->remise;
  694. $this->total_ht = $obj->total;
  695. $this->total_tva = $obj->tva;
  696. $this->total_localtax1 = $obj->localtax1;
  697. $this->total_localtax2 = $obj->localtax2;
  698. $this->total_ttc = $obj->total_ttc;
  699. $this->paye = $obj->paye;
  700. $this->close_code = $obj->close_code;
  701. $this->close_note = $obj->close_note;
  702. $this->socid = $obj->fk_soc;
  703. $this->statut = $obj->fk_statut;
  704. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  705. $this->mode_reglement_id = $obj->fk_mode_reglement;
  706. $this->mode_reglement_code = $obj->mode_reglement_code;
  707. $this->mode_reglement = $obj->mode_reglement_libelle;
  708. $this->cond_reglement_id = $obj->fk_cond_reglement;
  709. $this->cond_reglement_code = $obj->cond_reglement_code;
  710. $this->cond_reglement = $obj->cond_reglement_libelle;
  711. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  712. $this->fk_project = $obj->fk_projet;
  713. $this->fk_facture_source = $obj->fk_facture_source;
  714. $this->note = $obj->note;
  715. $this->note_public = $obj->note_public;
  716. $this->user_author = $obj->fk_user_author;
  717. $this->user_valid = $obj->fk_user_valid;
  718. $this->modelpdf = $obj->model_pdf;
  719. if ($this->statut == 0) $this->brouillon = 1;
  720. /*
  721. * Lines
  722. */
  723. $this->lines = array();
  724. $result=$this->fetch_lines();
  725. if ($result < 0)
  726. {
  727. $this->error=$this->db->error();
  728. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  729. return -3;
  730. }
  731. return 1;
  732. }
  733. else
  734. {
  735. $this->error='Bill with id '.$rowid.' or ref '.$ref.' not found sql='.$sql;
  736. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  737. return -2;
  738. }
  739. }
  740. else
  741. {
  742. $this->error=$this->db->error();
  743. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  744. return -1;
  745. }
  746. }
  747. /**
  748. * Load all detailed lines into this->lines
  749. *
  750. * @return int 1 if OK, < 0 if KO
  751. */
  752. function fetch_lines()
  753. {
  754. $this->lines=array();
  755. $sql = 'SELECT l.rowid, l.fk_product, l.fk_parent_line, l.description, l.product_type, l.price, l.qty, l.tva_tx, ';
  756. $sql.= ' l.localtax1_tx, l.localtax2_tx, l.remise, l.remise_percent, l.fk_remise_except, l.subprice,';
  757. $sql.= ' l.rang, l.special_code,';
  758. $sql.= ' l.date_start as date_start, l.date_end as date_end,';
  759. $sql.= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_export_compta,';
  760. $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as label, p.description as product_desc';
  761. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
  762. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  763. $sql.= ' WHERE l.fk_facture = '.$this->id;
  764. $sql.= ' ORDER BY l.rang';
  765. dol_syslog(get_class($this).'::fetch_lines sql='.$sql, LOG_DEBUG);
  766. $result = $this->db->query($sql);
  767. if ($result)
  768. {
  769. $num = $this->db->num_rows($result);
  770. $i = 0;
  771. while ($i < $num)
  772. {
  773. $objp = $this->db->fetch_object($result);
  774. $line = new FactureLigne($this->db);
  775. $line->rowid = $objp->rowid;
  776. $line->desc = $objp->description; // Description line
  777. $line->product_type = $objp->product_type; // Type of line
  778. $line->product_ref = $objp->product_ref; // Ref product
  779. $line->libelle = $objp->label; // Label product
  780. $line->product_desc = $objp->product_desc; // Description product
  781. $line->fk_product_type = $objp->fk_product_type; // Type of product
  782. $line->qty = $objp->qty;
  783. $line->subprice = $objp->subprice;
  784. $line->tva_tx = $objp->tva_tx;
  785. $line->localtax1_tx = $objp->localtax1_tx;
  786. $line->localtax2_tx = $objp->localtax2_tx;
  787. $line->remise_percent = $objp->remise_percent;
  788. $line->fk_remise_except = $objp->fk_remise_except;
  789. $line->fk_product = $objp->fk_product;
  790. $line->date_start = $this->db->jdate($objp->date_start);
  791. $line->date_end = $this->db->jdate($objp->date_end);
  792. $line->date_start = $this->db->jdate($objp->date_start);
  793. $line->date_end = $this->db->jdate($objp->date_end);
  794. $line->info_bits = $objp->info_bits;
  795. $line->total_ht = $objp->total_ht;
  796. $line->total_tva = $objp->total_tva;
  797. $line->total_localtax1 = $objp->total_localtax1;
  798. $line->total_localtax2 = $objp->total_localtax2;
  799. $line->total_ttc = $objp->total_ttc;
  800. $line->export_compta = $objp->fk_export_compta;
  801. $line->code_ventilation = $objp->fk_code_ventilation;
  802. $line->rang = $objp->rang;
  803. $line->special_code = $objp->special_code;
  804. $line->fk_parent_line = $objp->fk_parent_line;
  805. // Ne plus utiliser
  806. $line->price = $objp->price;
  807. $line->remise = $objp->remise;
  808. $this->lines[$i] = $line;
  809. $i++;
  810. }
  811. $this->db->free($result);
  812. return 1;
  813. }
  814. else
  815. {
  816. $this->error=$this->db->error();
  817. dol_syslog(get_class($this).'::fetch_lines '.$this->error,LOG_ERR);
  818. return -3;
  819. }
  820. }
  821. /**
  822. * Update database
  823. *
  824. * @param user User that modify
  825. * @param notrigger 0=launch triggers after, 1=disable triggers
  826. * @return int <0 if KO, >0 if OK
  827. */
  828. function update($user=0, $notrigger=0)
  829. {
  830. global $conf, $langs;
  831. $error=0;
  832. // Clean parameters
  833. if (isset($this->facnumber)) $this->facnumber=trim($this->ref);
  834. if (isset($this->type)) $this->type=trim($this->type);
  835. if (isset($this->ref_client)) $this->ref_client=trim($this->ref_client);
  836. if (isset($this->increment)) $this->increment=trim($this->increment);
  837. if (isset($this->socid)) $this->socid=trim($this->socid);
  838. if (isset($this->paye)) $this->paye=trim($this->paye);
  839. if (isset($this->amount)) $this->amount=trim($this->amount);
  840. if (isset($this->remise_percent)) $this->remise_percent=trim($this->remise_percent);
  841. if (isset($this->remise_absolue)) $this->remise_absolue=trim($this->remise_absolue);
  842. if (isset($this->remise)) $this->remise=trim($this->remise);
  843. if (isset($this->close_code)) $this->close_code=trim($this->close_code);
  844. if (isset($this->close_note)) $this->close_note=trim($this->close_note);
  845. if (isset($this->total_tva)) $this->tva=trim($this->total_tva);
  846. if (isset($this->total_localtax1)) $this->tva=trim($this->total_localtax1);
  847. if (isset($this->total_localtax2)) $this->tva=trim($this->total_localtax2);
  848. if (isset($this->total_ht)) $this->total_ht=trim($this->total_ht);
  849. if (isset($this->total_ttc)) $this->total_ttc=trim($this->total_ttc);
  850. if (isset($this->statut)) $this->statut=trim($this->statut);
  851. if (isset($this->user_author)) $this->user_author=trim($this->user_author);
  852. if (isset($this->fk_user_valid)) $this->fk_user_valid=trim($this->fk_user_valid);
  853. if (isset($this->fk_facture_source)) $this->fk_facture_source=trim($this->fk_facture_source);
  854. if (isset($this->fk_project)) $this->fk_project=trim($this->fk_project);
  855. if (isset($this->cond_reglement_id)) $this->cond_reglement_id=trim($this->cond_reglement_id);
  856. if (isset($this->mode_reglement_id)) $this->mode_reglement_id=trim($this->mode_reglement_id);
  857. if (isset($this->note)) $this->note=trim($this->note);
  858. if (isset($this->note_public)) $this->note_public=trim($this->note_public);
  859. if (isset($this->modelpdf)) $this->modelpdf=trim($this->modelpdf);
  860. if (isset($this->import_key)) $this->import_key=trim($this->import_key);
  861. // Check parameters
  862. // Put here code to add control on parameters values
  863. // Update request
  864. $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
  865. $sql.= " facnumber=".(isset($this->ref)?"'".$this->db->escape($this->ref)."'":"null").",";
  866. $sql.= " type=".(isset($this->type)?$this->type:"null").",";
  867. $sql.= " ref_client=".(isset($this->ref_client)?"'".$this->db->escape($this->ref_client)."'":"null").",";
  868. $sql.= " increment=".(isset($this->increment)?"'".$this->db->escape($this->increment)."'":"null").",";
  869. $sql.= " fk_soc=".(isset($this->socid)?$this->socid:"null").",";
  870. $sql.= " datec=".(strval($this->date_creation)!='' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  871. $sql.= " datef=".(strval($this->date)!='' ? "'".$this->db->idate($this->date)."'" : 'null').",";
  872. $sql.= " date_valid=".(strval($this->date_validation)!='' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  873. $sql.= " paye=".(isset($this->paye)?$this->paye:"null").",";
  874. $sql.= " amount=".(isset($this->amount)?$this->amount:"null").",";
  875. $sql.= " remise_percent=".(isset($this->remise_percent)?$this->remise_percent:"null").",";
  876. $sql.= " remise_absolue=".(isset($this->remise_absolue)?$this->remise_absolue:"null").",";
  877. $sql.= " remise=".(isset($this->remise)?$this->remise:"null").",";
  878. $sql.= " close_code=".(isset($this->close_code)?"'".$this->db->escape($this->close_code)."'":"null").",";
  879. $sql.= " close_note=".(isset($this->close_note)?"'".$this->db->escape($this->close_note)."'":"null").",";
  880. $sql.= " tva=".(isset($this->total_tva)?$this->total_tva:"null").",";
  881. $sql.= " localtax1=".(isset($this->total_localtax1)?$this->total_localtax1:"null").",";
  882. $sql.= " localtax2=".(isset($this->total_localtax2)?$this->total_localtax2:"null").",";
  883. $sql.= " total=".(isset($this->total_ht)?$this->total_ht:"null").",";
  884. $sql.= " total_ttc=".(isset($this->total_ttc)?$this->total_ttc:"null").",";
  885. $sql.= " fk_statut=".(isset($this->statut)?$this->statut:"null").",";
  886. $sql.= " fk_user_author=".(isset($this->user_author)?$this->user_author:"null").",";
  887. $sql.= " fk_user_valid=".(isset($this->fk_user_valid)?$this->fk_user_valid:"null").",";
  888. $sql.= " fk_facture_source=".(isset($this->fk_facture_source)?$this->fk_facture_source:"null").",";
  889. $sql.= " fk_projet=".(isset($this->fk_project)?$this->fk_project:"null").",";
  890. $sql.= " fk_cond_reglement=".(isset($this->cond_reglement_id)?$this->cond_reglement_id:"null").",";
  891. $sql.= " fk_mode_reglement=".(isset($this->mode_reglement_id)?$this->mode_reglement_id:"null").",";
  892. $sql.= " date_lim_reglement=".(strval($this->date_lim_reglement)!='' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
  893. $sql.= " note=".(isset($this->note)?"'".$this->db->escape($this->note)."'":"null").",";
  894. $sql.= " note_public=".(isset($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null").",";
  895. $sql.= " model_pdf=".(isset($this->modelpdf)?"'".$this->db->escape($this->modelpdf)."'":"null").",";
  896. $sql.= " import_key=".(isset($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null")."";
  897. $sql.= " WHERE rowid=".$this->id;
  898. $this->db->begin();
  899. dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
  900. $resql = $this->db->query($sql);
  901. if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
  902. if (! $error)
  903. {
  904. if (! $notrigger)
  905. {
  906. // Call triggers
  907. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  908. $interface=new Interfaces($this->db);
  909. $result=$interface->run_triggers('BILL_MODIFY',$this,$user,$langs,$conf);
  910. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  911. // End call triggers
  912. }
  913. }
  914. // Commit or rollback
  915. if ($error)
  916. {
  917. foreach($this->errors as $errmsg)
  918. {
  919. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  920. $this->error.=($this->error?', '.$errmsg:$errmsg);
  921. }
  922. $this->db->rollback();
  923. return -1*$error;
  924. }
  925. else
  926. {
  927. $this->db->commit();
  928. return 1;
  929. }
  930. }
  931. /**
  932. * Add a discount line into invoice using an existing absolute discount
  933. *
  934. * @param int $idremise Id of absolute discount
  935. * @return int >0 if OK, <0 if KO
  936. */
  937. function insert_discount($idremise)
  938. {
  939. global $langs;
  940. include_once(DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php');
  941. include_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php');
  942. $this->db->begin();
  943. $remise=new DiscountAbsolute($this->db);
  944. $result=$remise->fetch($idremise);
  945. if ($result > 0)
  946. {
  947. if ($remise->fk_facture) // Protection against multiple submission
  948. {
  949. $this->error=$langs->trans("ErrorDiscountAlreadyUsed");
  950. $this->db->rollback();
  951. return -5;
  952. }
  953. $facligne=new FactureLigne($this->db);
  954. $facligne->fk_facture=$this->id;
  955. $facligne->fk_remise_except=$remise->id;
  956. $facligne->desc=$remise->description; // Description ligne
  957. $facligne->tva_tx=$remise->tva_tx;
  958. $facligne->subprice=-$remise->amount_ht;
  959. $facligne->fk_product=0; // Id produit predefini
  960. $facligne->qty=1;
  961. $facligne->remise_percent=0;
  962. $facligne->rang=-1;
  963. $facligne->info_bits=2;
  964. // Ne plus utiliser
  965. $facligne->price=-$remise->amount_ht;
  966. $facligne->remise=0;
  967. $facligne->total_ht = -$remise->amount_ht;
  968. $facligne->total_tva = -$remise->amount_tva;
  969. $facligne->total_ttc = -$remise->amount_ttc;
  970. $lineid=$facligne->insert();
  971. if ($lineid > 0)
  972. {
  973. $result=$this->update_price(1);
  974. if ($result > 0)
  975. {
  976. // Create linke between discount and invoice line
  977. $result=$remise->link_to_invoice($lineid,0);
  978. if ($result < 0)
  979. {
  980. $this->error=$remise->error;
  981. $this->db->rollback();
  982. return -4;
  983. }
  984. $this->db->commit();
  985. return 1;
  986. }
  987. else
  988. {
  989. $this->error=$facligne->error;
  990. $this->db->rollback();
  991. return -1;
  992. }
  993. }
  994. else
  995. {
  996. $this->error=$facligne->error;
  997. $this->db->rollback();
  998. return -2;
  999. }
  1000. }
  1001. else
  1002. {
  1003. $this->db->rollback();
  1004. return -3;
  1005. }
  1006. }
  1007. /**
  1008. * Set customer ref
  1009. *
  1010. * @param string $ref_client Customer ref
  1011. * @return int <0 if KO, >0 if OK
  1012. */
  1013. function set_ref_client($ref_client)
  1014. {
  1015. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1016. if (empty($ref_client))
  1017. $sql .= ' SET ref_client = NULL';
  1018. else
  1019. $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
  1020. $sql .= ' WHERE rowid = '.$this->id;
  1021. if ($this->db->query($sql))
  1022. {
  1023. $this->ref_client = $ref_client;
  1024. return 1;
  1025. }
  1026. else
  1027. {
  1028. dol_print_error($this->db);
  1029. return -1;
  1030. }
  1031. }
  1032. /**
  1033. * Delete invoice
  1034. *
  1035. * @param int $rowid Id of invoice to delete. If empty, we delete current instance of invoice
  1036. * @return int <0 if KO, >0 if OK
  1037. */
  1038. function delete($rowid=0)
  1039. {
  1040. global $user,$langs,$conf;
  1041. if (! $rowid) $rowid=$this->id;
  1042. dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG);
  1043. // TODO Test if there is at least on payment. If yes, refuse to delete.
  1044. $error=0;
  1045. $this->db->begin();
  1046. $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
  1047. $sql.= " WHERE fk_target = ".$rowid;
  1048. $sql.= " AND targettype = '".$this->element."'";
  1049. if ($this->db->query($sql))
  1050. {
  1051. // If invoice was converted into a discount not yet consumed, we remove discount
  1052. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
  1053. $sql.= ' WHERE fk_facture_source = '.$rowid;
  1054. $sql.= ' AND fk_facture_line IS NULL';
  1055. $resql=$this->db->query($sql);
  1056. // If invoice has consumned discounts
  1057. $this->fetch_lines();
  1058. $list_rowid_det=array();
  1059. foreach($this->lines as $key => $invoiceline)
  1060. {
  1061. $list_rowid_det[]=$invoiceline->rowid;
  1062. }
  1063. // Consumned discounts are freed
  1064. if (count($list_rowid_det))
  1065. {
  1066. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1067. $sql.= ' SET fk_facture = NULL, fk_facture_line = NULL';
  1068. $sql.= ' WHERE fk_facture_line IN ('.join(',',$list_rowid_det).')';
  1069. dol_syslog(get_class($this)."::delete sql=".$sql);
  1070. if (! $this->db->query($sql))
  1071. {
  1072. $this->error=$this->db->error()." sql=".$sql;
  1073. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  1074. $this->db->rollback();
  1075. return -5;
  1076. }
  1077. }
  1078. // Delete invoice line
  1079. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.$rowid;
  1080. if ($this->db->query($sql) && $this->delete_linked_contact())
  1081. {
  1082. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.$rowid;
  1083. $resql=$this->db->query($sql);
  1084. if ($resql)
  1085. {
  1086. // Appel des triggers
  1087. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1088. $interface=new Interfaces($this->db);
  1089. $result=$interface->run_triggers('BILL_DELETE',$this,$user,$langs,$conf);
  1090. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  1091. // Fin appel triggers
  1092. $this->db->commit();
  1093. return 1;
  1094. }
  1095. else
  1096. {
  1097. $this->error=$this->db->error()." sql=".$sql;
  1098. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  1099. $this->db->rollback();
  1100. return -6;
  1101. }
  1102. }
  1103. else
  1104. {
  1105. $this->error=$this->db->error()." sql=".$sql;
  1106. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  1107. $this->db->rollback();
  1108. return -4;
  1109. }
  1110. }
  1111. else
  1112. {
  1113. $this->error=$this->db->error()." sql=".$sql;
  1114. dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR);
  1115. $this->db->rollback();
  1116. return -2;
  1117. }
  1118. }
  1119. /**
  1120. * Renvoi une date limite de reglement de facture en fonction des
  1121. * conditions de reglements de la facture et date de facturation
  1122. *
  1123. * @param cond_reglement_id Condition de reglement a utiliser, 0=Condition actuelle de la facture
  1124. * @return date Date limite de reglement si ok, <0 si ko
  1125. */
  1126. function calculate_date_lim_reglement($cond_reglement_id=0)
  1127. {
  1128. if (! $cond_reglement_id)
  1129. $cond_reglement_id=$this->cond_reglement_id;
  1130. $sqltemp = 'SELECT c.fdm,c.nbjour,c.decalage';
  1131. $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
  1132. $sqltemp.= ' WHERE c.rowid='.$cond_reglement_id;
  1133. $resqltemp=$this->db->query($sqltemp);
  1134. if ($resqltemp)
  1135. {
  1136. if ($this->db->num_rows($resqltemp))
  1137. {
  1138. $obj = $this->db->fetch_object($resqltemp);
  1139. $cdr_nbjour = $obj->nbjour;
  1140. $cdr_fdm = $obj->fdm;
  1141. $cdr_decalage = $obj->decalage;
  1142. }
  1143. }
  1144. else
  1145. {
  1146. $this->error=$this->db->error();
  1147. return -1;
  1148. }
  1149. $this->db->free($resqltemp);
  1150. /* Definition de la date limite */
  1151. // 1 : ajout du nombre de jours
  1152. $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
  1153. // 2 : application de la regle "fin de mois"
  1154. if ($cdr_fdm)
  1155. {
  1156. $mois=date('m', $datelim);
  1157. $annee=date('Y', $datelim);
  1158. if ($mois == 12)
  1159. {
  1160. $mois = 1;
  1161. $annee += 1;
  1162. }
  1163. else
  1164. {
  1165. $mois += 1;
  1166. }
  1167. // On se deplace au debut du mois suivant, et on retire un jour
  1168. $datelim=dol_mktime(12,0,0,$mois,1,$annee);
  1169. $datelim -= (3600 * 24);
  1170. }
  1171. // 3 : application du decalage
  1172. $datelim += ($cdr_decalage * 3600 * 24);
  1173. return $datelim;
  1174. }
  1175. /**
  1176. * Tag la facture comme paye completement (close_code non renseigne) ou partiellement (close_code renseigne) + appel trigger BILL_PAYED
  1177. *
  1178. * @param User $user Objet utilisateur qui modifie
  1179. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  1180. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  1181. * @return int <0 if KO, >0 if OK
  1182. */
  1183. function set_paid($user,$close_code='',$close_note='')
  1184. {
  1185. global $conf,$langs;
  1186. $error=0;
  1187. if ($this->paye != 1)
  1188. {
  1189. $this->db->begin();
  1190. dol_syslog("Facture::set_paid rowid=".$this->id, LOG_DEBUG);
  1191. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  1192. $sql.= ' fk_statut=2';
  1193. if (! $close_code) $sql.= ', paye=1';
  1194. if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
  1195. if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
  1196. $sql.= ' WHERE rowid = '.$this->id;
  1197. $resql = $this->db->query($sql);
  1198. if ($resql)
  1199. {
  1200. // Appel des triggers
  1201. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1202. $interface=new Interfaces($this->db);
  1203. $result=$interface->run_triggers('BILL_PAYED',$this,$user,$langs,$conf);
  1204. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  1205. // Fin appel triggers
  1206. }
  1207. else
  1208. {
  1209. $error++;
  1210. $this->error=$this->db->error();
  1211. dol_print_error($this->db);
  1212. }
  1213. if (! $error)
  1214. {
  1215. $this->db->commit();
  1216. return 1;
  1217. }
  1218. else
  1219. {
  1220. $this->db->rollback();
  1221. return -1;
  1222. }
  1223. }
  1224. else
  1225. {
  1226. return 0;
  1227. }
  1228. }
  1229. /**
  1230. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  1231. * Fonction utilisee quand un paiement prelevement est refuse,
  1232. * ou quand une facture annulee et reouverte.
  1233. *
  1234. * @param User $user Object user that change status
  1235. * @return int <0 if KO, >0 if OK
  1236. */
  1237. function set_unpaid($user)
  1238. {
  1239. global $conf,$langs;
  1240. $error=0;
  1241. $this->db->begin();
  1242. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1243. $sql.= ' SET paye=0, fk_statut=1, close_code=null, close_note=null';
  1244. $sql.= ' WHERE rowid = '.$this->id;
  1245. dol_syslog("Facture::set_unpaid sql=".$sql);
  1246. $resql = $this->db->query($sql);
  1247. if ($resql)
  1248. {
  1249. // Appel des triggers
  1250. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1251. $interface=new Interfaces($this->db);
  1252. $result=$interface->run_triggers('BILL_UNPAYED',$this,$user,$langs,$conf);
  1253. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  1254. // Fin appel triggers
  1255. }
  1256. else
  1257. {
  1258. $error++;
  1259. $this->error=$this->db->error();
  1260. dol_print_error($this->db);
  1261. }
  1262. if (! $error)
  1263. {
  1264. $this->db->commit();
  1265. return 1;
  1266. }
  1267. else
  1268. {
  1269. $this->db->rollback();
  1270. return -1;
  1271. }
  1272. }
  1273. /**
  1274. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  1275. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  1276. * of no payment even if merchandises were sent).
  1277. *
  1278. * @param User $user Object user making change
  1279. * @param string $close_code Code de fermeture
  1280. * @param string $close_note Comment
  1281. * @return int <0 if KO, >0 if OK
  1282. */
  1283. function set_canceled($user,$close_code='',$close_note='')
  1284. {
  1285. global $conf,$langs;
  1286. dol_syslog(get_class($this)."::set_canceled rowid=".$this->id, LOG_DEBUG);
  1287. $this->db->begin();
  1288. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  1289. $sql.= ' fk_statut=3';
  1290. if ($close_code) $sql.= ", close_code='".$this->db->escape($close_code)."'";
  1291. if ($close_note) $sql.= ", close_note='".$this->db->escape($close_note)."'";
  1292. $sql.= ' WHERE rowid = '.$this->id;
  1293. $resql = $this->db->query($sql);
  1294. if ($resql)
  1295. {
  1296. // On desaffecte de la facture les remises liees
  1297. // car elles n'ont pas ete utilisees vu que la facture est abandonnee.
  1298. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1299. $sql.= ' SET fk_facture = NULL';
  1300. $sql.= ' WHERE fk_facture = '.$this->id;
  1301. $resql=$this->db->query($sql);
  1302. if ($resql)
  1303. {
  1304. // Appel des triggers
  1305. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1306. $interface=new Interfaces($this->db);
  1307. $result=$interface->run_triggers('BILL_CANCEL',$this,$user,$langs,$conf);
  1308. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  1309. // Fin appel triggers
  1310. $this->db->commit();
  1311. return 1;
  1312. }
  1313. else
  1314. {
  1315. $this->error=$this->db->error()." sql=".$sql;
  1316. $this->db->rollback();
  1317. return -1;
  1318. }
  1319. }
  1320. else
  1321. {
  1322. $this->error=$this->db->error()." sql=".$sql;
  1323. $this->db->rollback();
  1324. return -2;
  1325. }
  1326. }
  1327. /**
  1328. * Tag invoice as validated + call trigger BILL_VALIDATE
  1329. * Object must have lines loaded with fetch_lines
  1330. *
  1331. * @param User $user Object user that validate
  1332. * @param string $force_number Reference to force on invoice
  1333. * @param int $idwarehouse Id of warehouse to use for stock decrease
  1334. * @return int <0 if KO, >0 if OK
  1335. */
  1336. function validate($user, $force_number='', $idwarehouse=0)
  1337. {
  1338. global $conf,$langs;
  1339. require_once(DOL_DOCUMENT_ROOT."/core/lib/files.lib.php");
  1340. $error=0;
  1341. dol_syslog(get_class($this).'::validate force_number='.$force_number,' idwarehouse='.$idwarehouse, LOG_WARNING);
  1342. // Check parameters
  1343. if (! $this->brouillon)
  1344. {
  1345. dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING);
  1346. return 0;
  1347. }
  1348. if (! $user->rights->facture->valider)
  1349. {
  1350. $this->error='Permission denied';
  1351. dol_syslog(get_class($this)."::validate ".$this->error, LOG_ERR);
  1352. return -1;
  1353. }
  1354. $this->db->begin();
  1355. $this->fetch_thirdparty();
  1356. $this->fetch_lines();
  1357. // Check parameters
  1358. if ($this->type == 1) // si facture de remplacement
  1359. {
  1360. // Controle que facture source connue
  1361. if ($this->fk_facture_source <= 0)
  1362. {
  1363. $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("InvoiceReplacement"));
  1364. $this->db->rollback();
  1365. return -10;
  1366. }
  1367. // Charge la facture source a remplacer
  1368. $facreplaced=new Facture($this->db);
  1369. $result=$facreplaced->fetch($this->fk_facture_source);
  1370. if ($result <= 0)
  1371. {
  1372. $this->error=$langs->trans("ErrorBadInvoice");
  1373. $this->db->rollback();
  1374. return -11;
  1375. }
  1376. // Controle que facture source non deja remplacee par une autre
  1377. $idreplacement=$facreplaced->getIdReplacingInvoice('validated');
  1378. if ($idreplacement && $idreplacement != $this->id)
  1379. {
  1380. $facreplacement=new Facture($this->db);
  1381. $facreplacement->fetch($idreplacement);
  1382. $this->error=$langs->trans("ErrorInvoiceAlreadyReplaced",$facreplaced->ref,$facreplacement->ref);
  1383. $this->db->rollback();
  1384. return -12;
  1385. }
  1386. $result=$facreplaced->set_canceled($user,'replaced','');
  1387. if ($result < 0)
  1388. {
  1389. $this->error=$facreplaced->error." sql=".$sql;
  1390. $this->db->rollback();
  1391. return -13;
  1392. }
  1393. }
  1394. // Define new ref
  1395. if ($force_number)
  1396. {
  1397. $num = $force_number;
  1398. }
  1399. else if (preg_match('/^[\(]?PROV/i', $this->ref))
  1400. {
  1401. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
  1402. {
  1403. $this->date=dol_now();
  1404. $this->date_lim_reglement=$this->calculate_date_lim_reglement();
  1405. }
  1406. $num = $this->getNextNumRef($this->client);
  1407. }
  1408. else
  1409. {
  1410. $num = $this->ref;
  1411. }
  1412. if ($num)
  1413. {
  1414. $this->update_price(1);
  1415. // Validate
  1416. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1417. $sql.= " SET facnumber='".$num."', fk_statut = 1, fk_user_valid = ".$user->id;
  1418. if (! empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date
  1419. {
  1420. $sql.= ', datef='.$this->db->idate($this->date);
  1421. $sql.= ', date_lim_reglement='.$this->db->idate($this->date_lim_reglement);
  1422. }
  1423. $sql.= ' WHERE rowid = '.$this->id;
  1424. dol_syslog(get_class($this)."::validate sql=".$sql);
  1425. $resql=$this->db->query($sql);
  1426. if (! $resql)
  1427. {
  1428. dol_syslog(get_class($this)."::validate Echec update - 10 - sql=".$sql, LOG_ERR);
  1429. dol_print_error($this->db);
  1430. $error++;
  1431. }
  1432. // On verifie si la facture etait une provisoire
  1433. if (! $error && (preg_match('/^[\(]?PROV/i', $this->ref)))
  1434. {
  1435. // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
  1436. }
  1437. if (! $error)
  1438. {
  1439. // Define third party as a customer
  1440. $result=$this->client->set_as_client();
  1441. // Si active on decremente le produit principal et ses composants a la validation de facture
  1442. if ($this->type != 3 && $result >= 0 && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_BILL)
  1443. {
  1444. require_once(DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php");
  1445. $langs->load("agenda");
  1446. // Loop on each line
  1447. $cpt=count($this->lines);
  1448. for ($i = 0; $i < $cpt; $i++)
  1449. {
  1450. if ($this->lines[$i]->fk_product > 0)
  1451. {
  1452. $mouvP = new MouvementStock($this->db);
  1453. // We decrease stock for product
  1454. if ($this->type == 2) $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
  1455. else $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr",$num));
  1456. if ($result < 0) { $error++; }
  1457. }
  1458. }
  1459. }
  1460. }
  1461. if (! $error)
  1462. {
  1463. $this->oldref = '';
  1464. // Rename directory if dir was a temporary ref
  1465. if (preg_match('/^[\(]?PROV/i', $this->ref))
  1466. {
  1467. // On renomme repertoire facture ($this->ref = ancienne ref, $num = nouvelle ref)
  1468. // afin de ne pas perdre les fichiers attaches
  1469. $facref = dol_sanitizeFileName($this->ref);
  1470. $snumfa = dol_sanitizeFileName($num);
  1471. $dirsource = $conf->facture->dir_output.'/'.$facref;
  1472. $dirdest = $conf->facture->dir_output.'/'.$snumfa;
  1473. if (file_exists($dirsource))
  1474. {
  1475. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  1476. if (@rename($dirsource, $dirdest))
  1477. {
  1478. $this->oldref = $facref;
  1479. dol_syslog("Rename ok");
  1480. // Suppression ancien fichier PDF dans nouveau rep
  1481. dol_delete_file($conf->facture->dir_output.'/'.$snumfa.'/'.$facref.'.*');
  1482. }
  1483. }
  1484. }
  1485. }
  1486. // Set new ref and define current statut
  1487. if (! $error)
  1488. {
  1489. $this->ref = $num;
  1490. $this->facnumber=$num;
  1491. $this->statut=1;
  1492. }
  1493. // Trigger calls
  1494. if (! $error)
  1495. {
  1496. // Appel des triggers
  1497. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  1498. $interface=new Interfaces($this->db);
  1499. $result=$interface->run_triggers('BILL_VALIDATE',$this,$user,$langs,$conf);
  1500. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  1501. // Fin appel triggers
  1502. }
  1503. }
  1504. else
  1505. {
  1506. $error++;
  1507. }
  1508. if (! $error)
  1509. {
  1510. $this->db->commit();
  1511. return 1;
  1512. }
  1513. else
  1514. {
  1515. $this->db->rollback();
  1516. $this->error=$this->db->lasterror();
  1517. return -1;
  1518. }
  1519. }
  1520. /**
  1521. * Set draft status
  1522. *
  1523. * @param User $user Object user that modify
  1524. * @param int $idwarehouse Id warehouse to use for stock change.
  1525. * @return int <0 if KO, >0 if OK
  1526. */
  1527. function set_draft($user,$idwarehouse=-1)
  1528. {
  1529. global $conf,$langs;
  1530. $error=0;
  1531. if ($this->statut == 0)
  1532. {
  1533. dol_syslog(get_class($this)."::set_draft already draft status", LOG_WARNING);
  1534. return 0;
  1535. }
  1536. $this->db->begin();
  1537. $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
  1538. $sql.= " SET fk_statut = 0";
  1539. $sql.= " WHERE rowid = ".$this->id;
  1540. dol_syslog(get_class($this)."::set_draft sql=".$sql, LOG_DEBUG);
  1541. $result=$this->db->query($sql);
  1542. if ($result)
  1543. {
  1544. // Si on decremente le produit principal et ses composants a la validation de facture, on rĂŠincrement
  1545. if ($this->type != 3 && $result >= 0 && $conf->stock->enabled && $conf->global->STOCK_CALCULATE_ON_BILL)
  1546. {
  1547. require_once(DOL_DOCUMENT_ROOT."/product/stock/class/mouvementstock.class.php");
  1548. $langs->load("agenda");
  1549. $num=count($this->lines);
  1550. for ($i = 0; $i < $num; $i++)
  1551. {
  1552. if ($this->lines[$i]->fk_product > 0)
  1553. {
  1554. $mouvP = new MouvementStock($this->db);
  1555. // We decrease stock for product
  1556. if ($this->type == 2) $result=$mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
  1557. else $result=$mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr",$this->ref));
  1558. }
  1559. }
  1560. }
  1561. if ($error == 0)
  1562. {
  1563. $this->db->commit();
  1564. return 1;
  1565. }
  1566. else
  1567. {
  1568. $this->db->rollback();
  1569. return -1;
  1570. }
  1571. }
  1572. else
  1573. {
  1574. $this->error=$this->db->error();
  1575. $this->db->rollback();
  1576. return -1;
  1577. }
  1578. }
  1579. /**
  1580. * Add an invoice line into database (linked to product/service or not).
  1581. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  1582. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  1583. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
  1584. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  1585. *
  1586. * @param facid Id de la facture
  1587. * @param desc Description de la ligne
  1588. * @param pu_ht Prix unitaire HT (> 0 even for credit note)
  1589. * @param qty Quantite
  1590. * @param txtva Taux de tva force, sinon -1
  1591. * @param txlocaltax1 Local tax 1 rate
  1592. * @param txlocaltax2 Local tax 2 rate
  1593. * @param fk_product Id du produit/service predefini
  1594. * @param remise_percent Pourcentage de remise de la ligne
  1595. * @param date_start Date de debut de validite du service
  1596. * @param date_end Date de fin de validite du service
  1597. * @param ventil Code de ventilation comptable
  1598. * @param info_bits Bits de type de lignes
  1599. * @param fk_remise_except Id remise
  1600. * @param price_base_type HT or TTC
  1601. * @param pu_ttc Prix unitaire TTC (> 0 even for credit note)
  1602. * @param type Type of line (0=product, 1=service)
  1603. * @param rang Position of line
  1604. * @return int <0 if KO, Id of line if OK
  1605. */
  1606. function addline($facid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits=0, $fk_remise_except='', $price_base_type='HT', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $origin='', $origin_id=0, $fk_parent_line=0)
  1607. {
  1608. dol_syslog("Facture::Addline facid=$facid,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product,remise_percent=$remise_percent,date_start=$date_start,date_end=$date_end,ventil=$ventil,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type", LOG_DEBUG);
  1609. include_once(DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php');
  1610. // Clean parameters
  1611. if (empty($remise_percent)) $remise_percent=0;
  1612. if (empty($qty)) $qty=0;
  1613. if (empty($info_bits)) $info_bits=0;
  1614. if (empty($rang)) $rang=0;
  1615. if (empty($ventil)) $ventil=0;
  1616. if (empty($txtva)) $txtva=0;
  1617. if (empty($txlocaltax1)) $txlocaltax1=0;
  1618. if (empty($txlocaltax2)) $txlocaltax2=0;
  1619. if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
  1620. $remise_percent=price2num($remise_percent);
  1621. $qty=price2num($qty);
  1622. $pu_ht=price2num($pu_ht);
  1623. $pu_ttc=price2num($pu_ttc);
  1624. $txtva=price2num($txtva);
  1625. $txlocaltax1=price2num($txlocaltax1);
  1626. $txlocaltax2=price2num($txlocaltax2);
  1627. if ($price_base_type=='HT')
  1628. {
  1629. $pu=$pu_ht;
  1630. }
  1631. else
  1632. {
  1633. $pu=$pu_ttc;
  1634. }
  1635. // Check parameters
  1636. if ($type < 0) return -1;
  1637. if ($this->brouillon)
  1638. {
  1639. $this->db->begin();
  1640. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1641. // qty, pu, remise_percent et txtva
  1642. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1643. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1644. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits);
  1645. $total_ht = $tabprice[0];
  1646. $total_tva = $tabprice[1];
  1647. $total_ttc = $tabprice[2];
  1648. $total_localtax1 = $tabprice[9];
  1649. $total_localtax2 = $tabprice[10];
  1650. $pu_ht = $tabprice[3];
  1651. // Rang to use
  1652. $rangtouse = $rang;
  1653. if ($rangtouse == -1)
  1654. {
  1655. $rangmax = $this->line_max($fk_parent_line);
  1656. $rangtouse = $rangmax + 1;
  1657. }
  1658. // TODO A virer
  1659. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  1660. //$price = $pu;
  1661. //$remise = 0;
  1662. //if ($remise_percent > 0)
  1663. //{
  1664. // $remise = round(($pu * $remise_percent / 100),2);
  1665. // $price = ($pu - $remise);
  1666. //}
  1667. $product_type=$type;
  1668. if ($fk_product)
  1669. {
  1670. $product=new Product($this->db);
  1671. $result=$product->fetch($fk_product);
  1672. $product_type=$product->type;
  1673. }
  1674. // Insert line
  1675. $this->line=new FactureLigne($this->db);
  1676. $this->line->fk_facture=$facid;
  1677. $this->line->desc=$desc;
  1678. $this->line->qty= ($this->type==2?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative
  1679. $this->line->tva_tx=$txtva;
  1680. $this->line->localtax1_tx=$txlocaltax1;
  1681. $this->line->localtax2_tx=$txlocaltax2;
  1682. $this->line->fk_product=$fk_product;
  1683. $this->line->product_type=$product_type;
  1684. $this->line->remise_percent=$remise_percent;
  1685. $this->line->subprice= ($this->type==2?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
  1686. $this->line->date_start=$date_start;
  1687. $this->line->date_end=$date_end;
  1688. $this->line->ventil=$ventil;
  1689. $this->line->rang=$rangtouse;
  1690. $this->line->info_bits=$info_bits;
  1691. $this->line->fk_remise_except=$fk_remise_except;
  1692. $this->line->total_ht= (($this->type==2||$qty<0)?-abs($total_ht):$total_ht); // For credit note and if qty is negative, total is negative
  1693. $this->line->total_tva= (($this->type==2||$qty<0)?-abs($total_tva):$total_tva);
  1694. $this->line->total_localtax1=(($this->type==2||$qty<0)?-abs($total_localtax1):$total_localtax1);
  1695. $this->line->total_localtax2=(($this->type==2||$qty<0)?-abs($total_localtax2):$total_localtax2);
  1696. $this->line->total_ttc= (($this->type==2||$qty<0)?-abs($total_ttc):$total_ttc);
  1697. $this->line->special_code=$special_code;
  1698. $this->line->fk_parent_line=$fk_parent_line;
  1699. $this->line->origin=$origin;
  1700. $this->line->origin_id=$origin_id;
  1701. // TODO Ne plus utiliser
  1702. //$this->line->price=($this->type==2?-1:1)*abs($price);
  1703. //$this->line->remise=($this->type==2?-1:1)*abs($remise);
  1704. $result=$this->line->insert();
  1705. if ($result > 0)
  1706. {
  1707. // Reorder if child line
  1708. if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
  1709. // Mise a jour informations denormalisees au niveau de la facture meme
  1710. $this->id=$facid; // TODO To move this we must remove parameter facid into this function declaration
  1711. $result=$this->update_price(1);
  1712. if ($result > 0)
  1713. {
  1714. $this->db->commit();
  1715. return $this->line->rowid;
  1716. }
  1717. else
  1718. {
  1719. $this->error=$this->db->error();
  1720. dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR);
  1721. $this->db->rollback();
  1722. return -1;
  1723. }
  1724. }
  1725. else
  1726. {
  1727. $this->error=$this->line->error;
  1728. $this->db->rollback();
  1729. return -2;
  1730. }
  1731. }
  1732. }
  1733. /**
  1734. * Update a detail line
  1735. * @param rowid Id of line to update
  1736. * @param desc Description of line
  1737. * @param pu Prix unitaire (HT ou TTC selon price_base_type) (> 0 even for credit note lines)
  1738. * @param qty Quantity
  1739. * @param remise_percent Pourcentage de remise de la ligne
  1740. * @param date_start Date de debut de validite du service
  1741. * @param date_end Date de fin de validite du service
  1742. * @param tva_tx VAT Rate
  1743. * @param txlocaltax1 Local tax 1 rate
  1744. * @param txlocaltax2 Local tax 2 rate
  1745. * @param price_base_type HT or TTC
  1746. * @param info_bits Miscellanous informations
  1747. * @param type Type of line (0=product, 1=service)
  1748. * @return int < 0 if KO, > 0 if OK
  1749. */
  1750. function updateline($rowid, $desc, $pu, $qty, $remise_percent=0, $date_start, $date_end, $txtva, $txlocaltax1=0, $txlocaltax2=0,$price_base_type='HT', $info_bits=0, $type=0, $fk_parent_line=0, $skip_update_total=0)
  1751. {
  1752. include_once(DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php');
  1753. dol_syslog("Facture::UpdateLine $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1, $txlocaltax2, $price_base_type, $info_bits, $type, $fk_parent_line", LOG_DEBUG);
  1754. if ($this->brouillon)
  1755. {
  1756. $this->db->begin();
  1757. // Clean parameters
  1758. if (empty($qty)) $qty=0;
  1759. if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
  1760. $remise_percent = price2num($remise_percent);
  1761. $qty = price2num($qty);
  1762. $pu = price2num($pu);
  1763. $txtva = price2num($txtva);
  1764. $txlocaltax1 = price2num($txlocaltax1);
  1765. $txlocaltax2 = price2num($txlocaltax2);
  1766. // Check parameters
  1767. if ($type < 0) return -1;
  1768. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  1769. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1770. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1771. $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits);
  1772. $total_ht = $tabprice[0];
  1773. $total_tva = $tabprice[1];
  1774. $total_ttc = $tabprice[2];
  1775. $total_localtax1=$tabprice[9];
  1776. $total_localtax2=$tabprice[10];
  1777. $pu_ht = $tabprice[3];
  1778. $pu_tva = $tabprice[4];
  1779. $pu_ttc = $tabprice[5];
  1780. // Old properties: $price, $remise (deprecated)
  1781. $price = $pu;
  1782. $remise = 0;
  1783. if ($remise_percent > 0)
  1784. {
  1785. $remise = round(($pu * $remise_percent / 100),2);
  1786. $price = ($pu - $remise);
  1787. }
  1788. $price = price2num($price);
  1789. // Update line into database
  1790. $this->line=new FactureLigne($this->db);
  1791. // Stock previous line records
  1792. $staticline=new FactureLigne($this->db);
  1793. $staticline->fetch($rowid);
  1794. $this->line->oldline = $staticline;
  1795. // Reorder if fk_parent_line change
  1796. if (! empty($fk_parent_line) && ! empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line)
  1797. {
  1798. $rangmax = $this->line_max($fk_parent_line);
  1799. $this->line->rang = $rangmax + 1;
  1800. }
  1801. $this->line->rowid = $rowid;
  1802. $this->line->desc = $desc;
  1803. $this->line->qty= ($this->type==2?abs($qty):$qty); // For credit note, quantity is always positive and unit price negative
  1804. $this->line->tva_tx = $txtva;
  1805. $this->line->localtax1_tx = $txlocaltax1;
  1806. $this->line->localtax2_tx = $txlocaltax2;
  1807. $this->line->remise_percent = $remise_percent;
  1808. $this->line->subprice= ($this->type==2?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
  1809. $this->line->date_start = $date_start;
  1810. $this->line->date_end = $date_end;
  1811. $this->line->total_ht= (($this->type==2||$qty<0)?-abs($total_ht):$total_ht); // For credit note and if qty is negative, total is negative
  1812. $this->line->total_tva= (($this->type==2||$qty<0)?-abs($total_tva):$total_tva);
  1813. $this->line->total_localtax1=(($this->type==2||$qty<0)?-abs($total_localtax1):$total_localtax1);
  1814. $this->line->total_localtax2=(($this->type==2||$qty<0)?-abs($total_localtax2):$total_localtax2);
  1815. $this->line->total_ttc= (($this->type==2||$qty<0)?-abs($total_ttc):$total_ttc);
  1816. $this->line->info_bits = $info_bits;
  1817. $this->line->product_type = $type;
  1818. $this->line->fk_parent_line = $fk_parent_line;
  1819. $this->line->skip_update_total = $skip_update_total;
  1820. // A ne plus utiliser
  1821. $this->line->price=$price;
  1822. $this->line->remise=$remise;
  1823. $result=$this->line->update();
  1824. if ($result > 0)
  1825. {
  1826. // Reorder if child line
  1827. if (! empty($fk_parent_line)) $this->line_order(true,'DESC');
  1828. // Mise a jour info denormalisees au niveau facture
  1829. $this->update_price(1);
  1830. $this->db->commit();
  1831. return $result;
  1832. }
  1833. else
  1834. {
  1835. $this->db->rollback();
  1836. return -1;
  1837. }
  1838. }
  1839. else
  1840. {
  1841. $this->error="Facture::UpdateLine Invoice statut makes operation forbidden";
  1842. return -2;
  1843. }
  1844. }
  1845. /**
  1846. * Delete line in database
  1847. * @param rowid Id of line to delete
  1848. * @return int <0 if KO, >0 if OK
  1849. */
  1850. function deleteline($rowid)
  1851. {
  1852. global $langs, $conf;
  1853. dol_syslog("Facture::Deleteline rowid=".$rowid, LOG_DEBUG);
  1854. if (! $this->brouillon)
  1855. {
  1856. $this->error='ErrorBadStatus';
  1857. return -1;
  1858. }
  1859. $this->db->begin();
  1860. // Libere remise liee a ligne de facture
  1861. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1862. $sql.= ' SET fk_facture_line = NULL';
  1863. $sql.= ' WHERE fk_facture_line = '.$rowid;
  1864. dol_syslog("Facture::Deleteline sql=".$sql);
  1865. $result = $this->db->query($sql);
  1866. if (! $result)
  1867. {
  1868. $this->error=$this->db->error();
  1869. dol_syslog("Facture::Deleteline Error ".$this->error, LOG_ERR);
  1870. $this->db->rollback();
  1871. return -1;
  1872. }
  1873. $line=new FactureLigne($this->db);
  1874. // For triggers
  1875. $line->fetch($rowid);
  1876. if ($line->delete() > 0)
  1877. {
  1878. $result=$this->update_price(1);
  1879. if ($result > 0)
  1880. {
  1881. $this->db->commit();
  1882. return 1;
  1883. }
  1884. else
  1885. {
  1886. $this->db->rollback();
  1887. $this->error=$this->db->lasterror();
  1888. return -1;
  1889. }
  1890. }
  1891. else
  1892. {
  1893. $this->db->rollback();
  1894. $this->error=$this->db->lasterror();
  1895. return -1;
  1896. }
  1897. }
  1898. /**
  1899. * \brief Applique une remise relative
  1900. * \param user User qui positionne la remise
  1901. * \param remise
  1902. * \return int <0 si ko, >0 si ok
  1903. */
  1904. function set_remise($user, $remise)
  1905. {
  1906. $remise=trim($remise)?trim($remise):0;
  1907. if ($user->rights->facture->creer)
  1908. {
  1909. $remise=price2num($remise);
  1910. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1911. $sql.= ' SET remise_percent = '.$remise;
  1912. $sql.= ' WHERE rowid = '.$this->id;
  1913. $sql.= ' AND fk_statut = 0 ;';
  1914. if ($this->db->query($sql))
  1915. {
  1916. $this->remise_percent = $remise;
  1917. $this->update_price(1);
  1918. return 1;
  1919. }
  1920. else
  1921. {
  1922. $this->error=$this->db->error();
  1923. return -1;
  1924. }
  1925. }
  1926. }
  1927. /**
  1928. * \brief Applique une remise absolue
  1929. * \param user User qui positionne la remise
  1930. * \param remise
  1931. * \return int <0 si ko, >0 si ok
  1932. */
  1933. function set_remise_absolue($user, $remise)
  1934. {
  1935. $remise=trim($remise)?trim($remise):0;
  1936. if ($user->rights->facture->creer)
  1937. {
  1938. $remise=price2num($remise);
  1939. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1940. $sql.= ' SET remise_absolue = '.$remise;
  1941. $sql.= ' WHERE rowid = '.$this->id;
  1942. $sql.= ' AND fk_statut = 0 ;';
  1943. dol_syslog("Facture::set_remise_absolue sql=$sql");
  1944. if ($this->db->query($sql))
  1945. {
  1946. $this->remise_absolue = $remise;
  1947. $this->update_price(1);
  1948. return 1;
  1949. }
  1950. else
  1951. {
  1952. $this->error=$this->db->error();
  1953. return -1;
  1954. }
  1955. }
  1956. }
  1957. /**
  1958. * Return amount of payments already done
  1959. * @return int Amount of payment already done, <0 if KO
  1960. */
  1961. function getSommePaiement()
  1962. {
  1963. $table='paiement_facture';
  1964. $field='fk_facture';
  1965. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  1966. {
  1967. $table='paiementfourn_facturefourn';
  1968. $field='fk_facturefourn';
  1969. }
  1970. $sql = 'SELECT sum(amount) as amount';
  1971. $sql.= ' FROM '.MAIN_DB_PREFIX.$table;
  1972. $sql.= ' WHERE '.$field.' = '.$this->id;
  1973. dol_syslog("Facture::getSommePaiement sql=".$sql, LOG_DEBUG);
  1974. $resql=$this->db->query($sql);
  1975. if ($resql)
  1976. {
  1977. $obj = $this->db->fetch_object($resql);
  1978. $this->db->free($resql);
  1979. return $obj->amount;
  1980. }
  1981. else
  1982. {
  1983. $this->error=$this->db->lasterror();
  1984. return -1;
  1985. }
  1986. }
  1987. /**
  1988. * Return list of payments
  1989. * @return Array with list of payments
  1990. */
  1991. function getListOfPayments($filtertype='')
  1992. {
  1993. $retarray=array();
  1994. $table='paiement_facture';
  1995. $table2='paiement';
  1996. $field='fk_facture';
  1997. $field2='fk_paiement';
  1998. if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
  1999. {
  2000. $table='paiementfourn_facturefourn';
  2001. $table2='paiementfourn';
  2002. $field='fk_facturefourn';
  2003. $field2='fk_paiementfourn';
  2004. }
  2005. $sql = 'SELECT pf.amount, p.fk_paiement, p.datep, t.code';
  2006. $sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
  2007. $sql.= ' WHERE pf.'.$field.' = '.$this->id;
  2008. $sql.= ' AND pf.'.$field2.' = p.rowid';
  2009. $sql.= ' AND p.fk_paiement = t.id';
  2010. if ($filtertype) $sql.=" AND t.code='PRE'";
  2011. dol_syslog("Facture::getListOfPayments sql=".$sql, LOG_DEBUG);
  2012. $resql=$this->db->query($sql);
  2013. if ($resql)
  2014. {
  2015. $num = $this->db->num_rows($resql);
  2016. $i=0;
  2017. while ($i < $num)
  2018. {
  2019. $obj = $this->db->fetch_object($resql);
  2020. $retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep);
  2021. $i++;
  2022. }
  2023. $this->db->free($resql);
  2024. return $retarray;
  2025. }
  2026. else
  2027. {
  2028. $this->error=$this->db->lasterror();
  2029. dol_print_error($this->db);
  2030. return array();
  2031. }
  2032. }
  2033. /**
  2034. * Return amount (with tax) of all credit notes and deposits invoices used by invoice
  2035. * @return int <0 if KO, Sum of credit notes and deposits amount otherwise
  2036. */
  2037. function getSumCreditNotesUsed()
  2038. {
  2039. require_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php');
  2040. $discountstatic=new DiscountAbsolute($this->db);
  2041. $result=$discountstatic->getSumCreditNotesUsed($this);
  2042. if ($result >= 0)
  2043. {
  2044. return $result;
  2045. }
  2046. else
  2047. {
  2048. $this->error=$discountstatic->error;
  2049. return -1;
  2050. }
  2051. }
  2052. /**
  2053. * Return amount (with tax) of all deposits invoices used by invoice
  2054. * @return int <0 if KO, Sum of deposits amount otherwise
  2055. */
  2056. function getSumDepositsUsed()
  2057. {
  2058. require_once(DOL_DOCUMENT_ROOT.'/core/class/discount.class.php');
  2059. $discountstatic=new DiscountAbsolute($this->db);
  2060. $result=$discountstatic->getSumDepositsUsed($this);
  2061. if ($result >= 0)
  2062. {
  2063. return $result;
  2064. }
  2065. else
  2066. {
  2067. $this->error=$discountstatic->error;
  2068. return -1;
  2069. }
  2070. }
  2071. /**
  2072. * \brief Renvoie tableau des ids de facture avoir issus de la facture
  2073. * \return array Tableau d'id de factures avoirs
  2074. */
  2075. function getListIdAvoirFromInvoice()
  2076. {
  2077. $idarray=array();
  2078. $sql = 'SELECT rowid';
  2079. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  2080. $sql.= ' WHERE fk_facture_source = '.$this->id;
  2081. $sql.= ' AND type = 2';
  2082. $resql=$this->db->query($sql);
  2083. if ($resql)
  2084. {
  2085. $num = $this->db->num_rows($resql);
  2086. $i = 0;
  2087. while ($i < $num)
  2088. {
  2089. $row = $this->db->fetch_row($resql);
  2090. $idarray[]=$row[0];
  2091. $i++;
  2092. }
  2093. }
  2094. else
  2095. {
  2096. dol_print_error($this->db);
  2097. }
  2098. return $idarray;
  2099. }
  2100. /**
  2101. * \brief Renvoie l'id de la facture qui la remplace
  2102. * \param option filtre sur statut ('', 'validated', ...)
  2103. * \return int <0 si KO, 0 si aucune facture ne remplace, id facture sinon
  2104. */
  2105. function getIdReplacingInvoice($option='')
  2106. {
  2107. $sql = 'SELECT rowid';
  2108. $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
  2109. $sql.= ' WHERE fk_facture_source = '.$this->id;
  2110. $sql.= ' AND type < 2';
  2111. if ($option == 'validated') $sql.= ' AND fk_statut = 1';
  2112. // PROTECTION BAD DATA
  2113. // Au cas ou base corrompue et qu'il y a une facture de remplacement validee
  2114. // et une autre non, on donne priorite a la validee.
  2115. // Ne devrait pas arriver (sauf si acces concurrentiel et que 2 personnes
  2116. // ont cree en meme temps une facture de remplacement pour la meme facture)
  2117. $sql.= ' ORDER BY fk_statut DESC';
  2118. $resql=$this->db->query($sql);
  2119. if ($resql)
  2120. {
  2121. $obj = $this->db->fetch_object($resql);
  2122. if ($obj)
  2123. {
  2124. // Si il y en a
  2125. return $obj->rowid;
  2126. }
  2127. else
  2128. {
  2129. // Si aucune facture ne remplace
  2130. return 0;
  2131. }
  2132. }
  2133. else
  2134. {
  2135. return -1;
  2136. }
  2137. }
  2138. /**
  2139. * \brief Retourne le libelle du type de facture
  2140. * \return string Libelle
  2141. */
  2142. function getLibType()
  2143. {
  2144. global $langs;
  2145. if ($this->type == 0) return $langs->trans("InvoiceStandard");
  2146. if ($this->type == 1) return $langs->trans("InvoiceReplacement");
  2147. if ($this->type == 2) return $langs->trans("InvoiceAvoir");
  2148. if ($this->type == 3) return $langs->trans("InvoiceDeposit");
  2149. if ($this->type == 4) return $langs->trans("InvoiceProForma");
  2150. return $langs->trans("Unknown");
  2151. }
  2152. /**
  2153. * Return label of object status
  2154. * @param mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto
  2155. * @param alreadypaid 0=No payment already done, 1=Some payments already done
  2156. * @return string Label
  2157. */
  2158. function getLibStatut($mode=0,$alreadypaid=-1)
  2159. {
  2160. return $this->LibStatut($this->paye,$this->statut,$mode,$alreadypaid,$this->type);
  2161. }
  2162. /**
  2163. * \brief Renvoi le libelle d'un statut donne
  2164. * \param paye Etat paye
  2165. * \param statut Id statut
  2166. * \param mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  2167. * \param alreadypaid Montant deja paye
  2168. * \param type Type facture
  2169. * \return string Libelle du statut
  2170. */
  2171. function LibStatut($paye,$statut,$mode=0,$alreadypaid=-1,$type=0)
  2172. {
  2173. global $langs;
  2174. $langs->load('bills');
  2175. //print "$paye,$statut,$mode,$alreadypaid,$type";
  2176. if ($mode == 0)
  2177. {
  2178. $prefix='';
  2179. if (! $paye)
  2180. {
  2181. if ($statut == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
  2182. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
  2183. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
  2184. if ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
  2185. return $langs->trans('Bill'.$prefix.'StatusStarted');
  2186. }
  2187. else
  2188. {
  2189. if ($type == 2) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
  2190. elseif ($type == 3) return $langs->trans('Bill'.$prefix.'StatusConverted');
  2191. else return $langs->trans('Bill'.$prefix.'StatusPaid');
  2192. }
  2193. }
  2194. if ($mode == 1)
  2195. {
  2196. $prefix='Short';
  2197. if (! $paye)
  2198. {
  2199. if ($statut == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
  2200. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled');
  2201. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
  2202. if ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
  2203. return $langs->trans('Bill'.$prefix.'StatusStarted');
  2204. }
  2205. else
  2206. {
  2207. if ($type == 2) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
  2208. elseif ($type == 3) return $langs->trans('Bill'.$prefix.'StatusConverted');
  2209. else return $langs->trans('Bill'.$prefix.'StatusPaid');
  2210. }
  2211. }
  2212. if ($mode == 2)
  2213. {
  2214. $prefix='Short';
  2215. if (! $paye)
  2216. {
  2217. if ($statut == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
  2218. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
  2219. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut7').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
  2220. if ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
  2221. return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
  2222. }
  2223. else
  2224. {
  2225. if ($type == 2) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
  2226. elseif ($type == 3) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
  2227. else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
  2228. }
  2229. }
  2230. if ($mode == 3)
  2231. {
  2232. $prefix='Short';
  2233. if (! $paye)
  2234. {
  2235. if ($statut == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0');
  2236. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5');
  2237. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut7');
  2238. if ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
  2239. return img_picto($langs->trans('BillStatusStarted'),'statut3');
  2240. }
  2241. else
  2242. {
  2243. if ($type == 2) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
  2244. elseif ($type == 3) return img_picto($langs->trans('BillStatusConverted'),'statut6');
  2245. else return img_picto($langs->trans('BillStatusPaid'),'statut6');
  2246. }
  2247. }
  2248. if ($mode == 4)
  2249. {
  2250. if (! $paye)
  2251. {
  2252. if ($statut == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
  2253. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
  2254. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut7').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
  2255. if ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
  2256. return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
  2257. }
  2258. else
  2259. {
  2260. if ($type == 2) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
  2261. elseif ($type == 3) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
  2262. else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
  2263. }
  2264. }
  2265. if ($mode == 5)
  2266. {
  2267. $prefix='Short';
  2268. if (! $paye)
  2269. {
  2270. if ($statut == 0) return $langs->trans('Bill'.$prefix.'StatusDraft').' '.img_picto($langs->trans('BillStatusDraft'),'statut0');
  2271. if (($statut == 3 || $statut == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled').' '.img_picto($langs->trans('BillStatusCanceled'),'statut5');
  2272. if (($statut == 3 || $statut == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' '.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut7');
  2273. if ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid').' '.img_picto($langs->trans('BillStatusNotPaid'),'statut1');
  2274. return $langs->trans('Bill'.$prefix.'StatusStarted').' '.img_picto($langs->trans('BillStatusStarted'),'statut3');
  2275. }
  2276. else
  2277. {
  2278. if ($type == 2) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' '.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
  2279. elseif ($type == 3) return $langs->trans('Bill'.$prefix.'StatusConverted').' '.img_picto($langs->trans('BillStatusConverted'),'statut6');
  2280. else return $langs->trans('Bill'.$prefix.'StatusPaid').' '.img_picto($langs->trans('BillStatusPaid'),'statut6');
  2281. }
  2282. }
  2283. }
  2284. /**
  2285. * Return next reference of invoice not already used (or last reference)
  2286. * according to numbering module defined into constant FACTURE_ADDON
  2287. * @param soc objet company
  2288. * @param mode 'next' for next value or 'last' for last value
  2289. * @return string free ref or last ref
  2290. */
  2291. function getNextNumRef($soc,$mode='next')
  2292. {
  2293. global $conf, $db, $langs;
  2294. $langs->load("bills");
  2295. // Clean parameters (if not defined or using deprecated value)
  2296. if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON='mod_facture_terre';
  2297. else if ($conf->global->FACTURE_ADDON=='terre') $conf->global->FACTURE_ADDON='mod_facture_terre';
  2298. else if ($conf->global->FACTURE_ADDON=='mercure') $conf->global->FACTURE_ADDON='mod_facture_mercure';
  2299. $mybool=false;
  2300. $file = $conf->global->FACTURE_ADDON.".php";
  2301. $classname = $conf->global->FACTURE_ADDON;
  2302. // Include file with class
  2303. foreach ($conf->file->dol_document_root as $dirroot)
  2304. {
  2305. $dir = $dirroot."/core/modules/facture/";
  2306. // Load file with numbering class (if found)
  2307. $mybool|=@include_once($dir.$file);
  2308. }
  2309. // For compatibility
  2310. if (! $mybool)
  2311. {
  2312. $file = $conf->global->FACTURE_ADDON."/".$conf->global->FACTURE_ADDON.".modules.php";
  2313. $classname = "mod_facture_".$conf->global->FACTURE_ADDON;
  2314. // Include file with class
  2315. foreach ($conf->file->dol_document_root as $dirroot)
  2316. {
  2317. $dir = $dirroot."/core/modules/facture/";
  2318. // Load file with numbering class (if found)
  2319. $mybool|=@include_once($dir.$file);
  2320. }
  2321. }
  2322. //print "xx".$mybool.$dir.$file."-".$classname;
  2323. if (! $mybool)
  2324. {
  2325. dol_print_error('',"Failed to include file ".$file);
  2326. return '';
  2327. }
  2328. $obj = new $classname();
  2329. $numref = "";
  2330. $numref = $obj->getNumRef($soc,$this,$mode);
  2331. if ( $numref != "")
  2332. {
  2333. return $numref;
  2334. }
  2335. else
  2336. {
  2337. //dol_print_error($db,"Facture::getNextNumRef ".$obj->error);
  2338. return false;
  2339. }
  2340. }
  2341. /**
  2342. * \brief Charge les informations de l'onglet info dans l'objet facture
  2343. * \param id Id de la facture a charger
  2344. */
  2345. function info($id)
  2346. {
  2347. $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
  2348. $sql.= ' fk_user_author, fk_user_valid';
  2349. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture as c';
  2350. $sql.= ' WHERE c.rowid = '.$id;
  2351. $result=$this->db->query($sql);
  2352. if ($result)
  2353. {
  2354. if ($this->db->num_rows($result))
  2355. {
  2356. $obj = $this->db->fetch_object($result);
  2357. $this->id = $obj->rowid;
  2358. if ($obj->fk_user_author)
  2359. {
  2360. $cuser = new User($this->db);
  2361. $cuser->fetch($obj->fk_user_author);
  2362. $this->user_creation = $cuser;
  2363. }
  2364. if ($obj->fk_user_valid)
  2365. {
  2366. $vuser = new User($this->db);
  2367. $vuser->fetch($obj->fk_user_valid);
  2368. $this->user_validation = $vuser;
  2369. }
  2370. $this->date_creation = $this->db->jdate($obj->datec);
  2371. $this->date_modification = $this->db->jdate($obj->datem);
  2372. $this->date_validation = $this->db->jdate($obj->datev); // Should be in log table
  2373. }
  2374. $this->db->free($result);
  2375. }
  2376. else
  2377. {
  2378. dol_print_error($this->db);
  2379. }
  2380. }
  2381. /**
  2382. * \brief Change les conditions de reglement de la facture
  2383. * \param cond_reglement_id Id de la nouvelle condition de reglement
  2384. * \param date Date to force payment term
  2385. * \return int >0 si ok, <0 si ko
  2386. */
  2387. function cond_reglement($cond_reglement_id,$date='')
  2388. {
  2389. if ($this->statut >= 0 && $this->paye == 0)
  2390. {
  2391. // Define cond_reglement_id and datelim
  2392. if (strval($date) != '')
  2393. {
  2394. $datelim=$date;
  2395. $cond_reglement_id=0;
  2396. }
  2397. else
  2398. {
  2399. $datelim=$this->calculate_date_lim_reglement($cond_reglement_id);
  2400. $cond_reglement_id=$cond_reglement_id;
  2401. }
  2402. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2403. $sql.= ' SET fk_cond_reglement = '.$cond_reglement_id.',';
  2404. $sql.= ' date_lim_reglement='.$this->db->idate($datelim);
  2405. $sql.= ' WHERE rowid='.$this->id;
  2406. dol_syslog('Facture::cond_reglement sql='.$sql, LOG_DEBUG);
  2407. if ( $this->db->query($sql) )
  2408. {
  2409. $this->cond_reglement_id = $cond_reglement_id;
  2410. return 1;
  2411. }
  2412. else
  2413. {
  2414. dol_syslog('Facture::cond_reglement Erreur '.$sql.' - '.$this->db->error());
  2415. $this->error=$this->db->error();
  2416. return -1;
  2417. }
  2418. }
  2419. else
  2420. {
  2421. dol_syslog('Facture::cond_reglement, etat facture incompatible');
  2422. $this->error='Entity status not compatible '.$this->statut.' '.$this->paye;
  2423. return -2;
  2424. }
  2425. }
  2426. /**
  2427. * \brief Change le mode de reglement
  2428. * \param mode Id du nouveau mode
  2429. * \return int >0 si ok, <0 si ko
  2430. */
  2431. function mode_reglement($mode_reglement_id)
  2432. {
  2433. dol_syslog('Facture::mode_reglement('.$mode_reglement_id.')', LOG_DEBUG);
  2434. if ($this->statut >= 0 && $this->paye == 0)
  2435. {
  2436. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2437. $sql .= ' SET fk_mode_reglement = '.$mode_reglement_id;
  2438. $sql .= ' WHERE rowid='.$this->id;
  2439. if ( $this->db->query($sql) )
  2440. {
  2441. $this->mode_reglement_id = $mode_reglement_id;
  2442. return 1;
  2443. }
  2444. else
  2445. {
  2446. dol_syslog('Facture::mode_reglement Erreur '.$sql.' - '.$this->db->error());
  2447. $this->error=$this->db->error();
  2448. return -1;
  2449. }
  2450. }
  2451. else
  2452. {
  2453. dol_syslog('Facture::mode_reglement, etat facture incompatible');
  2454. $this->error='Etat facture incompatible '.$this->statut.' '.$this->paye;
  2455. return -2;
  2456. }
  2457. }
  2458. /**
  2459. * \brief Renvoi si les lignes de facture sont ventilees et/ou exportees en compta
  2460. * \param user Utilisateur creant la demande
  2461. * \return int <0 if KO, 0=no, 1=yes
  2462. */
  2463. function getVentilExportCompta()
  2464. {
  2465. // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
  2466. $ventilExportCompta = 0 ;
  2467. $num=count($this->lines);
  2468. for ($i = 0; $i < $num; $i++)
  2469. {
  2470. if ($this->lines[$i]->export_compta <> 0 && $this->lines[$i]->code_ventilation <> 0)
  2471. {
  2472. $ventilExportCompta++;
  2473. }
  2474. }
  2475. if ($ventilExportCompta <> 0)
  2476. {
  2477. return 1;
  2478. }
  2479. else
  2480. {
  2481. return 0;
  2482. }
  2483. }
  2484. /**
  2485. * Return if an invoice can be deleted
  2486. * Rule is:
  2487. * If hidden option FACTURE_CAN_BE_REMOVED is on, we can
  2488. * If invoice has a definitive ref, is last, without payment and not dipatched into accountancy -> yes end of rule
  2489. * If invoice is draft and ha a temporary ref -> yes
  2490. * @return int <0 if KO, 0=no, 1=yes
  2491. */
  2492. function is_erasable()
  2493. {
  2494. global $conf;
  2495. if (! empty($conf->global->FACTURE_CAN_BE_REMOVED)) return 1;
  2496. // on verifie si la facture est en numerotation provisoire
  2497. $facref = substr($this->ref, 1, 4);
  2498. // If not a draft invoice and not temporary invoice
  2499. if ($facref != 'PROV')
  2500. {
  2501. $maxfacnumber = $this->getNextNumRef($this->client,'last');
  2502. $ventilExportCompta = $this->getVentilExportCompta();
  2503. // Si derniere facture et si non ventilee, on peut supprimer
  2504. if ($maxfacnumber == $this->ref && $ventilExportCompta == 0)
  2505. {
  2506. return 1;
  2507. }
  2508. }
  2509. else if ($this->statut == 0 && $facref == 'PROV') // Si facture brouillon et provisoire
  2510. {
  2511. return 1;
  2512. }
  2513. return 0;
  2514. }
  2515. /**
  2516. * \brief Renvoi liste des factures remplacables
  2517. * Statut validee ou abandonnee pour raison autre + non payee + aucun paiement + pas deja remplacee
  2518. * \param socid Id societe
  2519. * \return array Tableau des factures ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
  2520. */
  2521. function list_replacable_invoices($socid=0)
  2522. {
  2523. global $conf;
  2524. $return = array();
  2525. $sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut,";
  2526. $sql.= " ff.rowid as rowidnext";
  2527. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2528. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  2529. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
  2530. $sql.= " WHERE (f.fk_statut = 1 OR (f.fk_statut = 3 AND f.close_code = 'abandon'))";
  2531. $sql.= " AND f.entity = ".$conf->entity;
  2532. $sql.= " AND f.paye = 0"; // Pas classee payee completement
  2533. $sql.= " AND pf.fk_paiement IS NULL"; // Aucun paiement deja fait
  2534. $sql.= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement
  2535. if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
  2536. $sql.= " ORDER BY f.facnumber";
  2537. dol_syslog("Facture::list_replacable_invoices sql=$sql");
  2538. $resql=$this->db->query($sql);
  2539. if ($resql)
  2540. {
  2541. while ($obj=$this->db->fetch_object($resql))
  2542. {
  2543. $return[$obj->rowid]=array( 'id' => $obj->rowid,
  2544. 'ref' => $obj->facnumber,
  2545. 'status' => $obj->fk_statut);
  2546. }
  2547. //print_r($return);
  2548. return $return;
  2549. }
  2550. else
  2551. {
  2552. $this->error=$this->db->error();
  2553. dol_syslog("Facture::list_replacable_invoices ".$this->error, LOG_ERR);
  2554. return -1;
  2555. }
  2556. }
  2557. /**
  2558. * \brief Renvoi liste des factures qualifiables pour correction par avoir
  2559. * Les factures qui respectent les regles suivantes sont retournees:
  2560. * (validee + paiement en cours) ou classee (payee completement ou payee partiellement) + pas deja remplacee + pas deja avoir
  2561. * \param socid Id societe
  2562. * \return array Tableau des factures ($id => $ref)
  2563. */
  2564. function list_qualified_avoir_invoices($socid=0)
  2565. {
  2566. global $conf;
  2567. $return = array();
  2568. $sql = "SELECT f.rowid as rowid, f.facnumber, f.fk_statut, pf.fk_paiement";
  2569. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2570. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  2571. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=1)";
  2572. $sql.= " WHERE f.entity = ".$conf->entity;
  2573. $sql.= " AND f.fk_statut in (1,2)";
  2574. // $sql.= " WHERE f.fk_statut >= 1";
  2575. // $sql.= " AND (f.paye = 1"; // Classee payee completement
  2576. // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
  2577. $sql.= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
  2578. $sql.= " AND f.type != 2"; // Type non 2 si facture non avoir
  2579. if ($socid > 0) $sql.=" AND f.fk_soc = ".$socid;
  2580. $sql.= " ORDER BY f.facnumber";
  2581. dol_syslog("Facture::list_qualified_avoir_invoices sql=$sql");
  2582. $resql=$this->db->query($sql);
  2583. if ($resql)
  2584. {
  2585. while ($obj=$this->db->fetch_object($resql))
  2586. {
  2587. $qualified=0;
  2588. if ($obj->fk_statut == 1) $qualified=1;
  2589. if ($obj->fk_statut == 2) $qualified=1;
  2590. if ($qualified)
  2591. {
  2592. //$ref=$obj->facnumber;
  2593. $paymentornot=($obj->fk_paiement?1:0);
  2594. $return[$obj->rowid]=$paymentornot;
  2595. }
  2596. }
  2597. return $return;
  2598. }
  2599. else
  2600. {
  2601. $this->error=$this->db->error();
  2602. dol_syslog("Facture::list_avoir_invoices ".$this->error, LOG_ERR);
  2603. return -1;
  2604. }
  2605. }
  2606. /**
  2607. * \brief Create a withdrawal request for a standing order
  2608. * \param user User asking standing order
  2609. * \return int <0 if KO, >0 if OK
  2610. */
  2611. function demande_prelevement($user)
  2612. {
  2613. dol_syslog("Facture::demande_prelevement", LOG_DEBUG);
  2614. $soc = new Societe($this->db);
  2615. $soc->id = $this->socid;
  2616. $soc->load_ban();
  2617. if ($this->statut > 0 && $this->paye == 0)
  2618. {
  2619. $sql = 'SELECT count(*)';
  2620. $sql.= ' FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  2621. $sql.= ' WHERE fk_facture = '.$this->id;
  2622. $sql.= ' AND traite = 0';
  2623. $resql=$this->db->query($sql);
  2624. if ($resql)
  2625. {
  2626. $row = $this->db->fetch_row($resql);
  2627. if ($row[0] == 0)
  2628. {
  2629. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  2630. $sql .= ' (fk_facture, amount, date_demande, fk_user_demande, code_banque, code_guichet, number, cle_rib)';
  2631. $sql .= ' VALUES ('.$this->id;
  2632. $sql .= ",'".price2num($this->total_ttc)."'";
  2633. $sql .= ",".$this->db->idate(mktime()).",".$user->id;
  2634. $sql .= ",'".$soc->bank_account->code_banque."'";
  2635. $sql .= ",'".$soc->bank_account->code_guichet."'";
  2636. $sql .= ",'".$soc->bank_account->number."'";
  2637. $sql .= ",'".$soc->bank_account->cle_rib."')";
  2638. if ( $this->db->query($sql))
  2639. {
  2640. return 1;
  2641. }
  2642. else
  2643. {
  2644. $this->error=$this->db->error();
  2645. dol_syslog('Facture::DemandePrelevement Erreur');
  2646. return -1;
  2647. }
  2648. }
  2649. else
  2650. {
  2651. $this->error="A request already exists";
  2652. dol_syslog('Facture::DemandePrelevement Impossible de creer une demande, demande deja en cours');
  2653. }
  2654. }
  2655. else
  2656. {
  2657. $this->error=$this->db->error();
  2658. dol_syslog('Facture::DemandePrelevement Erreur -2');
  2659. return -2;
  2660. }
  2661. }
  2662. else
  2663. {
  2664. $this->error="Status of invoice does not allow this";
  2665. dol_syslog("Facture::DemandePrelevement ".$this->error." $this->statut, $this->paye, $this->mode_reglement_id");
  2666. return -3;
  2667. }
  2668. }
  2669. /**
  2670. * Supprime une demande de prelevement
  2671. * @param user utilisateur creant la demande
  2672. * @param did id de la demande a supprimer
  2673. */
  2674. function demande_prelevement_delete($user, $did)
  2675. {
  2676. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'prelevement_facture_demande';
  2677. $sql .= ' WHERE rowid = '.$did;
  2678. $sql .= ' AND traite = 0';
  2679. if ( $this->db->query( $sql) )
  2680. {
  2681. return 0;
  2682. }
  2683. else
  2684. {
  2685. dol_syslog('Facture::DemandePrelevement Erreur');
  2686. return -1;
  2687. }
  2688. }
  2689. /**
  2690. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2691. * @param user Objet user
  2692. * @return int <0 if KO, >0 if OK
  2693. */
  2694. function load_board($user)
  2695. {
  2696. global $conf, $user;
  2697. $now=dol_now();
  2698. $this->nbtodo=$this->nbtodolate=0;
  2699. $clause = " WHERE";
  2700. $sql = "SELECT f.rowid, f.date_lim_reglement as datefin";
  2701. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2702. if (!$user->rights->societe->client->voir && !$user->societe_id)
  2703. {
  2704. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
  2705. $sql.= " WHERE sc.fk_user = " .$user->id;
  2706. $clause = " AND";
  2707. }
  2708. $sql.= $clause." f.paye=0";
  2709. $sql.= " AND f.entity = ".$conf->entity;
  2710. $sql.= " AND f.fk_statut = 1";
  2711. if ($user->societe_id) $sql.= " AND f.fk_soc = ".$user->societe_id;
  2712. $resql=$this->db->query($sql);
  2713. if ($resql)
  2714. {
  2715. while ($obj=$this->db->fetch_object($resql))
  2716. {
  2717. $this->nbtodo++;
  2718. if ($this->db->jdate($obj->datefin) < ($now - $conf->facture->client->warning_delay)) $this->nbtodolate++;
  2719. }
  2720. return 1;
  2721. }
  2722. else
  2723. {
  2724. dol_print_error($this->db);
  2725. $this->error=$this->db->error();
  2726. return -1;
  2727. }
  2728. }
  2729. /* gestion des contacts d'une facture */
  2730. /**
  2731. * \brief Retourne id des contacts clients de facturation
  2732. * \return array Liste des id contacts facturation
  2733. */
  2734. function getIdBillingContact()
  2735. {
  2736. return $this->getIdContact('external','BILLING');
  2737. }
  2738. /**
  2739. * \brief Retourne id des contacts clients de livraison
  2740. * \return array Liste des id contacts livraison
  2741. */
  2742. function getIdShippingContact()
  2743. {
  2744. return $this->getIdContact('external','SHIPPING');
  2745. }
  2746. /**
  2747. * Initialise an instance with random values.
  2748. * Used to build previews or test instances.
  2749. * id must be 0 if object instance is a specimen.
  2750. *
  2751. * @return void
  2752. */
  2753. function initAsSpecimen()
  2754. {
  2755. global $user,$langs,$conf;
  2756. $now=dol_now();
  2757. $prodids = array();
  2758. $sql = "SELECT rowid";
  2759. $sql.= " FROM ".MAIN_DB_PREFIX."product";
  2760. $sql.= " WHERE entity = ".$conf->entity;
  2761. $resql = $this->db->query($sql);
  2762. if ($resql)
  2763. {
  2764. $num_prods = $this->db->num_rows($resql);
  2765. $i = 0;
  2766. while ($i < $num_prods)
  2767. {
  2768. $i++;
  2769. $row = $this->db->fetch_row($resql);
  2770. $prodids[$i] = $row[0];
  2771. }
  2772. }
  2773. // Initialize parameters
  2774. $this->id=0;
  2775. $this->ref = 'SPECIMEN';
  2776. $this->specimen=1;
  2777. $this->socid = 1;
  2778. $this->date = $now;
  2779. $this->date_lim_reglement=$this->date+3600*24*30;
  2780. $this->cond_reglement_id = 1;
  2781. $this->cond_reglement_code = 'RECEP';
  2782. $this->mode_reglement_id = 7;
  2783. $this->mode_reglement_code = ''; // No particular payment mode defined
  2784. $this->note_public='This is a comment (public)';
  2785. $this->note='This is a comment (private)';
  2786. // Lines
  2787. $nbp = 5;
  2788. $xnbp = 0;
  2789. while ($xnbp < $nbp)
  2790. {
  2791. $line=new FactureLigne($this->db);
  2792. $line->desc=$langs->trans("Description")." ".$xnbp;
  2793. $line->qty=1;
  2794. $line->subprice=100;
  2795. $line->price=100;
  2796. $line->tva_tx=19.6;
  2797. $line->localtax1_tx=0;
  2798. $line->localtax2_tx=0;
  2799. if ($xnbp == 2)
  2800. {
  2801. $line->total_ht=50;
  2802. $line->total_ttc=59.8;
  2803. $line->total_tva=9.8;
  2804. $line->remise_percent=50;
  2805. }
  2806. else
  2807. {
  2808. $line->total_ht=100;
  2809. $line->total_ttc=119.6;
  2810. $line->total_tva=19.6;
  2811. $line->remise_percent=00;
  2812. }
  2813. $prodid = rand(1, $num_prods);
  2814. $line->fk_product=$prodids[$prodid];
  2815. $this->lines[$xnbp]=$line;
  2816. $this->total_ht += $line->total_ht;
  2817. $this->total_tva += $line->total_tva;
  2818. $this->total_ttc += $line->total_ttc;
  2819. $xnbp++;
  2820. }
  2821. // Add a line "offered"
  2822. $line=new FactureLigne($this->db);
  2823. $line->desc=$langs->trans("Description")." ".$xnbp;
  2824. $line->qty=1;
  2825. $line->subprice=100;
  2826. $line->price=100;
  2827. $line->tva_tx=19.6;
  2828. $line->localtax1_tx=0;
  2829. $line->localtax2_tx=0;
  2830. $line->remise_percent=100;
  2831. $line->total_ht=0;
  2832. $line->total_ttc=0; // 90 * 1.196
  2833. $line->total_tva=0;
  2834. $prodid = rand(1, $num_prods);
  2835. $line->fk_product=$prodids[$prodid];
  2836. $this->lines[$xnbp]=$line;
  2837. $xnbp++;
  2838. }
  2839. /**
  2840. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  2841. *
  2842. * @param user Objet user
  2843. * @return int <0 if KO, >0 if OK
  2844. */
  2845. function load_state_board()
  2846. {
  2847. global $conf, $user;
  2848. $this->nb=array();
  2849. $clause = "WHERE";
  2850. $sql = "SELECT count(f.rowid) as nb";
  2851. $sql.= " FROM ".MAIN_DB_PREFIX."facture as f";
  2852. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  2853. if (!$user->rights->societe->client->voir && !$user->societe_id)
  2854. {
  2855. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  2856. $sql.= " WHERE sc.fk_user = " .$user->id;
  2857. $clause = "AND";
  2858. }
  2859. $sql.= " ".$clause." f.entity = ".$conf->entity;
  2860. $resql=$this->db->query($sql);
  2861. if ($resql)
  2862. {
  2863. while ($obj=$this->db->fetch_object($resql))
  2864. {
  2865. $this->nb["invoices"]=$obj->nb;
  2866. }
  2867. return 1;
  2868. }
  2869. else
  2870. {
  2871. dol_print_error($this->db);
  2872. $this->error=$this->db->error();
  2873. return -1;
  2874. }
  2875. }
  2876. /**
  2877. * Return an array of invoice lines
  2878. */
  2879. function getLinesArray()
  2880. {
  2881. $sql = 'SELECT l.rowid, l.description, l.fk_product, l.product_type, l.qty, l.tva_tx,';
  2882. $sql.= ' l.fk_remise_except,';
  2883. $sql.= ' l.remise_percent, l.subprice, l.info_bits, l.rang, l.special_code,';
  2884. $sql.= ' l.total_ht, l.total_tva, l.total_ttc,';
  2885. $sql.= ' l.date_start,';
  2886. $sql.= ' l.date_end,';
  2887. $sql.= ' l.product_type,';
  2888. $sql.= ' p.ref as product_ref, p.fk_product_type, p.label as product_label,';
  2889. $sql.= ' p.description as product_desc';
  2890. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
  2891. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product p ON l.fk_product=p.rowid';
  2892. $sql.= ' WHERE l.fk_facture = '.$this->id;
  2893. $sql.= ' ORDER BY l.rang ASC, l.rowid';
  2894. $resql = $this->db->query($sql);
  2895. if ($resql)
  2896. {
  2897. $num = $this->db->num_rows($resql);
  2898. $i = 0;
  2899. while ($i < $num)
  2900. {
  2901. $obj = $this->db->fetch_object($resql);
  2902. $this->lines[$i]->id = $obj->rowid;
  2903. $this->lines[$i]->description = $obj->description;
  2904. $this->lines[$i]->fk_product = $obj->fk_product;
  2905. $this->lines[$i]->ref = $obj->product_ref;
  2906. $this->lines[$i]->product_label = $obj->product_label;
  2907. $this->lines[$i]->product_desc = $obj->product_desc;
  2908. $this->lines[$i]->fk_product_type = $obj->fk_product_type;
  2909. $this->lines[$i]->product_type = $obj->product_type;
  2910. $this->lines[$i]->qty = $obj->qty;
  2911. $this->lines[$i]->subprice = $obj->subprice;
  2912. $this->lines[$i]->fk_remise_except = $obj->fk_remise_except;
  2913. $this->lines[$i]->remise_percent = $obj->remise_percent;
  2914. $this->lines[$i]->tva_tx = $obj->tva_tx;
  2915. $this->lines[$i]->info_bits = $obj->info_bits;
  2916. $this->lines[$i]->total_ht = $obj->total_ht;
  2917. $this->lines[$i]->total_tva = $obj->total_tva;
  2918. $this->lines[$i]->total_ttc = $obj->total_ttc;
  2919. $this->lines[$i]->special_code = $obj->special_code;
  2920. $this->lines[$i]->rang = $obj->rang;
  2921. $this->lines[$i]->date_start = $this->db->jdate($obj->date_start);
  2922. $this->lines[$i]->date_end = $this->db->jdate($obj->date_end);
  2923. $i++;
  2924. }
  2925. $this->db->free($resql);
  2926. return 1;
  2927. }
  2928. else
  2929. {
  2930. $this->error=$this->db->error();
  2931. dol_syslog("Error sql=$sql, error=".$this->error,LOG_ERR);
  2932. return -1;
  2933. }
  2934. }
  2935. }
  2936. /**
  2937. * \class FactureLigne
  2938. * \brief Classe permettant la gestion des lignes de factures
  2939. * \remarks Gere des lignes de la table llx_facturedet
  2940. */
  2941. class FactureLigne
  2942. {
  2943. var $db;
  2944. var $error;
  2945. var $oldline;
  2946. //! From llx_facturedet
  2947. var $rowid;
  2948. //! Id facture
  2949. var $fk_facture;
  2950. //! Id parent line
  2951. var $fk_parent_line;
  2952. //! Description ligne
  2953. var $desc;
  2954. var $fk_product; // Id of predefined product
  2955. var $product_type = 0; // Type 0 = product, 1 = Service
  2956. var $qty; // Quantity (example 2)
  2957. var $tva_tx; // Taux tva produit/service (example 19.6)
  2958. var $localtax1_tx; // Local tax 1
  2959. var $localtax2_tx; // Local tax 2
  2960. var $subprice; // P.U. HT (example 100)
  2961. var $remise_percent; // % de la remise ligne (example 20%)
  2962. var $fk_remise_except; // Link to line into llx_remise_except
  2963. var $rang = 0;
  2964. var $info_bits = 0; // Liste d'options cumulables:
  2965. // Bit 0: 0 si TVA normal - 1 si TVA NPR
  2966. // Bit 1: 0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
  2967. var $special_code; // Liste d'options non cumulabels:
  2968. // 1: frais de port
  2969. // 2: ecotaxe
  2970. // 3: ??
  2971. var $origin;
  2972. var $origin_id;
  2973. //! Total HT de la ligne toute quantite et incluant la remise ligne
  2974. var $total_ht;
  2975. //! Total TVA de la ligne toute quantite et incluant la remise ligne
  2976. var $total_tva;
  2977. var $total_localtax1; //Total Local tax 1 de la ligne
  2978. var $total_localtax2; //Total Local tax 2 de la ligne
  2979. //! Total TTC de la ligne toute quantite et incluant la remise ligne
  2980. var $total_ttc;
  2981. var $fk_code_ventilation = 0;
  2982. var $fk_export_compta = 0;
  2983. var $date_start;
  2984. var $date_end;
  2985. // Ne plus utiliser
  2986. var $price; // P.U. HT apres remise % de ligne (exemple 80)
  2987. var $remise; // Montant calcule de la remise % sur PU HT (exemple 20)
  2988. // From llx_product
  2989. var $ref; // Product ref (deprecated)
  2990. var $product_ref; // Product ref
  2991. var $libelle; // Product label (deprecated)
  2992. var $product_label; // Product label
  2993. var $product_desc; // Description produit
  2994. var $skip_update_total; // Skip update price total for special lines
  2995. /**
  2996. * \brief Constructeur d'objets ligne de facture
  2997. * \param DB handler d'acces base de donnee
  2998. */
  2999. function FactureLigne($DB)
  3000. {
  3001. $this->db= $DB ;
  3002. }
  3003. /**
  3004. * \brief Recupere l'objet ligne de facture
  3005. * \param rowid id de la ligne de facture
  3006. */
  3007. function fetch($rowid)
  3008. {
  3009. $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.description, fd.price, fd.qty, fd.tva_tx,';
  3010. $sql.= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice,';
  3011. $sql.= ' fd.date_start as date_start, fd.date_end as date_end,';
  3012. $sql.= ' fd.info_bits, fd.total_ht, fd.total_tva, fd.total_ttc, fd.rang,';
  3013. $sql.= ' fd.fk_code_ventilation, fd.fk_export_compta,';
  3014. $sql.= ' p.ref as product_ref, p.label as product_libelle, p.description as product_desc';
  3015. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
  3016. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
  3017. $sql.= ' WHERE fd.rowid = '.$rowid;
  3018. $result = $this->db->query($sql);
  3019. if ($result)
  3020. {
  3021. $objp = $this->db->fetch_object($result);
  3022. $this->rowid = $objp->rowid;
  3023. $this->fk_facture = $objp->fk_facture;
  3024. $this->fk_parent_line = $objp->fk_parent_line;
  3025. $this->desc = $objp->description;
  3026. $this->qty = $objp->qty;
  3027. $this->subprice = $objp->subprice;
  3028. $this->tva_tx = $objp->tva_tx;
  3029. $this->localtax1_tx = $objp->localtax1_tx;
  3030. $this->localtax2_tx = $objp->localtax2_tx;
  3031. $this->remise_percent = $objp->remise_percent;
  3032. $this->fk_remise_except = $objp->fk_remise_except;
  3033. $this->fk_product = $objp->fk_product;
  3034. $this->product_type = $objp->product_type;
  3035. $this->date_start = $this->db->jdate($objp->date_start);
  3036. $this->date_end = $this->db->jdate($objp->date_end);
  3037. $this->info_bits = $objp->info_bits;
  3038. $this->total_ht = $objp->total_ht;
  3039. $this->total_tva = $objp->total_tva;
  3040. $this->total_localtax1 = $objp->total_localtax1;
  3041. $this->total_localtax2 = $objp->total_localtax2;
  3042. $this->total_ttc = $objp->total_ttc;
  3043. $this->fk_code_ventilation = $objp->fk_code_ventilation;
  3044. $this->fk_export_compta = $objp->fk_export_compta;
  3045. $this->rang = $objp->rang;
  3046. // Ne plus utiliser
  3047. $this->price = $objp->price;
  3048. $this->remise = $objp->remise;
  3049. $this->ref = $objp->product_ref; // deprecated
  3050. $this->product_ref = $objp->product_ref;
  3051. $this->libelle = $objp->product_libelle; // deprecated
  3052. $this->product_label = $objp->product_libelle;
  3053. $this->product_desc = $objp->product_desc;
  3054. $this->db->free($result);
  3055. }
  3056. else
  3057. {
  3058. dol_print_error($this->db);
  3059. }
  3060. }
  3061. /**
  3062. * \brief Insert line in database
  3063. * \param notrigger 1 no triggers
  3064. * \return int <0 if KO, >0 if OK
  3065. */
  3066. function insert($notrigger=0)
  3067. {
  3068. global $langs,$user,$conf;
  3069. dol_syslog("FactureLigne::Insert rang=".$this->rang, LOG_DEBUG);
  3070. // Clean parameters
  3071. $this->desc=trim($this->desc);
  3072. if (empty($this->tva_tx)) $this->tva_tx=0;
  3073. if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
  3074. if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
  3075. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  3076. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  3077. if (empty($this->rang)) $this->rang=0;
  3078. if (empty($this->remise)) $this->remise=0;
  3079. if (empty($this->remise_percent)) $this->remise_percent=0;
  3080. if (empty($this->info_bits)) $this->info_bits=0;
  3081. if (empty($this->subprice)) $this->subprice=0;
  3082. if (empty($this->price)) $this->price=0;
  3083. if (empty($this->special_code)) $this->special_code=0;
  3084. if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
  3085. // Check parameters
  3086. if ($this->product_type < 0) return -1;
  3087. $this->db->begin();
  3088. // Insertion dans base de la ligne
  3089. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
  3090. $sql.= ' (fk_facture, fk_parent_line, description, qty, tva_tx, localtax1_tx, localtax2_tx,';
  3091. $sql.= ' fk_product, product_type, remise_percent, subprice, price, remise, fk_remise_except,';
  3092. $sql.= ' date_start, date_end, fk_code_ventilation, fk_export_compta, ';
  3093. $sql.= ' rang, special_code,';
  3094. $sql.= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2)';
  3095. $sql.= " VALUES (".$this->fk_facture.",";
  3096. $sql.= " ".($this->fk_parent_line>0?"'".$this->fk_parent_line."'":"null").",";
  3097. $sql.= " '".$this->db->escape($this->desc)."',";
  3098. $sql.= " ".price2num($this->qty).",";
  3099. $sql.= " ".price2num($this->tva_tx).",";
  3100. $sql.= " ".price2num($this->localtax1_tx).",";
  3101. $sql.= " ".price2num($this->localtax2_tx).",";
  3102. if ($this->fk_product) { $sql.= "'".$this->fk_product."',"; }
  3103. else { $sql.='null,'; }
  3104. $sql.= " ".$this->product_type.",";
  3105. $sql.= " ".price2num($this->remise_percent).",";
  3106. $sql.= " ".price2num($this->subprice).",";
  3107. $sql.= " ".price2num($this->price).",";
  3108. $sql.= " ".($this->remise?price2num($this->remise):'0').","; // Deprecated
  3109. if ($this->fk_remise_except) $sql.= $this->fk_remise_except.",";
  3110. else $sql.= 'null,';
  3111. if ($this->date_start) { $sql.= "'".$this->db->idate($this->date_start)."',"; }
  3112. else { $sql.='null,'; }
  3113. if ($this->date_end) { $sql.= "'".$this->db->idate($this->date_end)."',"; }
  3114. else { $sql.='null,'; }
  3115. $sql.= ' '.$this->fk_code_ventilation.',';
  3116. $sql.= ' '.$this->fk_export_compta.',';
  3117. $sql.= ' '.$this->rang.',';
  3118. $sql.= ' '.$this->special_code.',';
  3119. $sql.= " '".$this->info_bits."',";
  3120. $sql.= " ".price2num($this->total_ht).",";
  3121. $sql.= " ".price2num($this->total_tva).",";
  3122. $sql.= " ".price2num($this->total_ttc).",";
  3123. $sql.= " ".price2num($this->total_localtax1).",";
  3124. $sql.= " ".price2num($this->total_localtax2);
  3125. $sql.= ')';
  3126. dol_syslog("FactureLigne::insert sql=".$sql);
  3127. $resql=$this->db->query($sql);
  3128. if ($resql)
  3129. {
  3130. $this->rowid=$this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
  3131. // Si fk_remise_except defini, on lie la remise a la facture
  3132. // ce qui la flague comme "consommee".
  3133. if ($this->fk_remise_except)
  3134. {
  3135. $discount=new DiscountAbsolute($this->db);
  3136. $result=$discount->fetch($this->fk_remise_except);
  3137. if ($result >= 0)
  3138. {
  3139. // Check if discount was found
  3140. if ($result > 0)
  3141. {
  3142. // Check if discount not already affected to another invoice
  3143. if ($discount->fk_facture)
  3144. {
  3145. $this->error=$langs->trans("ErrorDiscountAlreadyUsed",$discount->id);
  3146. dol_syslog("FactureLigne::insert Error ".$this->error, LOG_ERR);
  3147. $this->db->rollback();
  3148. return -3;
  3149. }
  3150. else
  3151. {
  3152. $result=$discount->link_to_invoice($this->rowid,0);
  3153. if ($result < 0)
  3154. {
  3155. $this->error=$discount->error;
  3156. dol_syslog("FactureLigne::insert Error ".$this->error, LOG_ERR);
  3157. $this->db->rollback();
  3158. return -3;
  3159. }
  3160. }
  3161. }
  3162. else
  3163. {
  3164. $this->error=$langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
  3165. dol_syslog("FactureLigne::insert Error ".$this->error, LOG_ERR);
  3166. $this->db->rollback();
  3167. return -3;
  3168. }
  3169. }
  3170. else
  3171. {
  3172. $this->error=$discount->error;
  3173. dol_syslog("FactureLigne::insert Error ".$this->error, LOG_ERR);
  3174. $this->db->rollback();
  3175. return -3;
  3176. }
  3177. }
  3178. if (! $notrigger)
  3179. {
  3180. // Appel des triggers
  3181. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  3182. $interface=new Interfaces($this->db);
  3183. $result = $interface->run_triggers('LINEBILL_INSERT',$this,$user,$langs,$conf);
  3184. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  3185. // Fin appel triggers
  3186. }
  3187. $this->db->commit();
  3188. return $this->rowid;
  3189. }
  3190. else
  3191. {
  3192. $this->error=$this->db->error();
  3193. dol_syslog("FactureLigne::insert Error ".$this->error, LOG_ERR);
  3194. $this->db->rollback();
  3195. return -2;
  3196. }
  3197. }
  3198. /**
  3199. * Update line into database
  3200. *
  3201. * @return int <0 if KO, >0 if OK
  3202. */
  3203. function update()
  3204. {
  3205. global $user,$langs,$conf;
  3206. // Clean parameters
  3207. $this->desc=trim($this->desc);
  3208. if (empty($this->tva_tx)) $this->tva_tx=0;
  3209. if (empty($this->localtax1_tx)) $this->localtax1_tx=0;
  3210. if (empty($this->localtax2_tx)) $this->localtax2_tx=0;
  3211. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  3212. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  3213. if (empty($this->remise)) $this->remise=0;
  3214. if (empty($this->remise_percent)) $this->remise_percent=0;
  3215. if (empty($this->info_bits)) $this->info_bits=0;
  3216. if (empty($this->product_type)) $this->product_type=0;
  3217. if (empty($this->fk_parent_line)) $this->fk_parent_line=0;
  3218. // Check parameters
  3219. if ($this->product_type < 0) return -1;
  3220. $this->db->begin();
  3221. // Mise a jour ligne en base
  3222. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  3223. $sql.= " description='".$this->db->escape($this->desc)."'";
  3224. $sql.= ",subprice=".price2num($this->subprice)."";
  3225. $sql.= ",price=".price2num($this->price)."";
  3226. $sql.= ",remise=".price2num($this->remise)."";
  3227. $sql.= ",remise_percent=".price2num($this->remise_percent)."";
  3228. if ($this->fk_remise_except) $sql.= ",fk_remise_except=".$this->fk_remise_except;
  3229. else $sql.= ",fk_remise_except=null";
  3230. $sql.= ",tva_tx=".price2num($this->tva_tx)."";
  3231. $sql.= ",localtax1_tx=".price2num($this->localtax1_tx)."";
  3232. $sql.= ",localtax2_tx=".price2num($this->localtax2_tx)."";
  3233. $sql.= ",qty=".price2num($this->qty)."";
  3234. if ($this->date_start) { $sql.= ",date_start='".$this->db->idate($this->date_start)."'"; }
  3235. else { $sql.=',date_start=null'; }
  3236. if ($this->date_end) { $sql.= ",date_end='".$this->db->idate($this->date_end)."'"; }
  3237. else { $sql.=',date_end=null'; }
  3238. $sql.= ",product_type=".$this->product_type;
  3239. $sql.= ",info_bits='".$this->info_bits."'";
  3240. if (empty($this->skip_update_total))
  3241. {
  3242. $sql.= ",total_ht=".price2num($this->total_ht)."";
  3243. $sql.= ",total_tva=".price2num($this->total_tva)."";
  3244. $sql.= ",total_ttc=".price2num($this->total_ttc)."";
  3245. }
  3246. $sql.= ",total_localtax1=".price2num($this->total_localtax1)."";
  3247. $sql.= ",total_localtax2=".price2num($this->total_localtax2)."";
  3248. $sql.= ",fk_parent_line=".($this->fk_parent_line>0?$this->fk_parent_line:"null");
  3249. if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
  3250. $sql.= " WHERE rowid = ".$this->rowid;
  3251. dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG);
  3252. $resql=$this->db->query($sql);
  3253. if ($resql)
  3254. {
  3255. if (! $notrigger)
  3256. {
  3257. // Appel des triggers
  3258. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  3259. $interface=new Interfaces($this->db);
  3260. $result = $interface->run_triggers('LINEBILL_UPDATE',$this,$user,$langs,$conf);
  3261. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  3262. // Fin appel triggers
  3263. }
  3264. $this->db->commit();
  3265. return 1;
  3266. }
  3267. else
  3268. {
  3269. $this->error=$this->db->error();
  3270. dol_syslog(get_class($this)."::update Error ".$this->error, LOG_ERR);
  3271. $this->db->rollback();
  3272. return -2;
  3273. }
  3274. }
  3275. /**
  3276. * Delete line in database
  3277. * @return int <0 si ko, >0 si ok
  3278. */
  3279. function delete()
  3280. {
  3281. global $conf,$langs,$user;
  3282. $this->db->begin();
  3283. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid;
  3284. dol_syslog("FactureLigne::delete sql=".$sql, LOG_DEBUG);
  3285. if ($this->db->query($sql) )
  3286. {
  3287. // Appel des triggers
  3288. include_once(DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php");
  3289. $interface=new Interfaces($this->db);
  3290. $result = $interface->run_triggers('LINEBILL_DELETE',$this,$user,$langs,$conf);
  3291. if ($result < 0) { $error++; $this->errors=$interface->errors; }
  3292. // Fin appel triggers
  3293. $this->db->commit();
  3294. return 1;
  3295. }
  3296. else
  3297. {
  3298. $this->error=$this->db->error()." sql=".$sql;
  3299. dol_syslog("FactureLigne::delete Error ".$this->error, LOG_ERR);
  3300. $this->db->rollback();
  3301. return -1;
  3302. }
  3303. }
  3304. /**
  3305. * \brief Mise a jour en base des champs total_xxx de ligne de facture
  3306. * \return int <0 si ko, >0 si ok
  3307. */
  3308. function update_total()
  3309. {
  3310. $this->db->begin();
  3311. dol_syslog("FactureLigne::update_total", LOG_DEBUG);
  3312. // Clean parameters
  3313. if (empty($this->total_localtax1)) $this->total_localtax1=0;
  3314. if (empty($this->total_localtax2)) $this->total_localtax2=0;
  3315. // Mise a jour ligne en base
  3316. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  3317. $sql.= " total_ht=".price2num($this->total_ht)."";
  3318. $sql.= ",total_tva=".price2num($this->total_tva)."";
  3319. $sql.= ",total_localtax1=".price2num($this->total_localtax1)."";
  3320. $sql.= ",total_localtax2=".price2num($this->total_localtax2)."";
  3321. $sql.= ",total_ttc=".price2num($this->total_ttc)."";
  3322. $sql.= " WHERE rowid = ".$this->rowid;
  3323. dol_syslog("PropaleLigne::update_total sql=".$sql, LOG_DEBUG);
  3324. $resql=$this->db->query($sql);
  3325. if ($resql)
  3326. {
  3327. $this->db->commit();
  3328. return 1;
  3329. }
  3330. else
  3331. {
  3332. $this->error=$this->db->error();
  3333. dol_syslog("FactureLigne::update_total Error ".$this->error, LOG_ERR);
  3334. $this->db->rollback();
  3335. return -2;
  3336. }
  3337. }
  3338. }
  3339. ?>