PageRenderTime 88ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

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

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