facture-rec.class.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849
  1. <?php
  2. /* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@capnetworks.com>
  5. * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
  6. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  7. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  8. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  9. * Copyright (C) 2017 Frédéric France <frederic.france@netlogic.fr>
  10. *
  11. * This program is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. */
  24. /**
  25. * \file htdocs/compta/facture/class/facture-rec.class.php
  26. * \ingroup facture
  27. * \brief Fichier de la classe des factures recurentes
  28. */
  29. require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
  30. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  33. /**
  34. * Class to manage invoice templates
  35. */
  36. class FactureRec extends CommonInvoice
  37. {
  38. public $element='facturerec';
  39. public $table_element='facture_rec';
  40. public $table_element_line='facturedet_rec';
  41. public $fk_element='fk_facture';
  42. public $picto='bill';
  43. var $entity;
  44. var $number;
  45. var $date;
  46. var $amount;
  47. var $remise;
  48. var $tva;
  49. var $total;
  50. var $db_table;
  51. var $propalid;
  52. var $date_last_gen;
  53. var $date_when;
  54. var $nb_gen_done;
  55. var $nb_gen_max;
  56. var $frequency;
  57. var $unit_frequency;
  58. var $rang;
  59. var $special_code;
  60. var $usenewprice=0;
  61. var $suspended; // status
  62. const STATUS_NOTSUSPENDED = 0;
  63. const STATUS_SUSPENDED = 1;
  64. /**
  65. * Constructor
  66. *
  67. * @param DoliDB $db Database handler
  68. */
  69. function __construct($db)
  70. {
  71. $this->db = $db;
  72. }
  73. /**
  74. * Create a predefined invoice
  75. *
  76. * @param User $user User object
  77. * @param int $facid Id of source invoice
  78. * @return int <0 if KO, id of invoice created if OK
  79. */
  80. function create($user, $facid)
  81. {
  82. global $conf;
  83. $error=0;
  84. $now=dol_now();
  85. // Clean parameters
  86. $this->titre=trim($this->titre);
  87. $this->usenewprice=empty($this->usenewprice)?0:$this->usenewprice;
  88. if (empty($this->suspended)) $this->suspended=0;
  89. // No frequency defined then no next date to execution
  90. if (empty($this->frequency))
  91. {
  92. $this->frequency=0;
  93. $this->date_when=null;
  94. }
  95. $this->frequency=abs($this->frequency);
  96. $this->nb_gen_done=0;
  97. $this->nb_gen_max=empty($this->nb_gen_max)?0:$this->nb_gen_max;
  98. $this->auto_validate=empty($this->auto_validate)?0:$this->auto_validate;
  99. $this->generate_pdf = empty($this->generate_pdf)?0:$this->generate_pdf;
  100. $this->db->begin();
  101. // Charge facture modele
  102. $facsrc=new Facture($this->db);
  103. $result=$facsrc->fetch($facid);
  104. if ($result > 0)
  105. {
  106. // On positionne en mode brouillon la facture
  107. $this->brouillon = 1;
  108. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_rec (";
  109. $sql.= "titre";
  110. $sql.= ", fk_soc";
  111. $sql.= ", entity";
  112. $sql.= ", datec";
  113. $sql.= ", amount";
  114. $sql.= ", remise";
  115. $sql.= ", note_private";
  116. $sql.= ", note_public";
  117. $sql.= ", modelpdf";
  118. $sql.= ", fk_user_author";
  119. $sql.= ", fk_projet";
  120. $sql.= ", fk_account";
  121. $sql.= ", fk_cond_reglement";
  122. $sql.= ", fk_mode_reglement";
  123. $sql.= ", usenewprice";
  124. $sql.= ", frequency";
  125. $sql.= ", unit_frequency";
  126. $sql.= ", date_when";
  127. $sql.= ", date_last_gen";
  128. $sql.= ", nb_gen_done";
  129. $sql.= ", nb_gen_max";
  130. $sql.= ", auto_validate";
  131. $sql.= ", generate_pdf";
  132. $sql.= ", fk_multicurrency";
  133. $sql.= ", multicurrency_code";
  134. $sql.= ", multicurrency_tx";
  135. $sql.= ", suspended";
  136. $sql.= ") VALUES (";
  137. $sql.= "'".$this->db->escape($this->titre)."'";
  138. $sql.= ", ".$facsrc->socid;
  139. $sql.= ", ".$conf->entity;
  140. $sql.= ", '".$this->db->idate($now)."'";
  141. $sql.= ", ".(!empty($facsrc->amount)?$facsrc->amount:'0');
  142. $sql.= ", ".(!empty($facsrc->remise)?$this->remise:'0');
  143. $sql.= ", ".(!empty($this->note_private)?("'".$this->db->escape($this->note_private)."'"):"NULL");
  144. $sql.= ", ".(!empty($this->note_public)?("'".$this->db->escape($this->note_public)."'"):"NULL");
  145. $sql.= ", ".(!empty($this->modelpdf)?("'".$this->db->escape($this->modelpdf)."'"):"NULL");
  146. $sql.= ", '".$this->db->escape($user->id)."'";
  147. $sql.= ", ".(! empty($facsrc->fk_project)?"'".$facsrc->fk_project."'":"null");
  148. $sql.= ", ".(! empty($facsrc->fk_account)?"'".$facsrc->fk_account."'":"null");
  149. $sql.= ", ".($facsrc->cond_reglement_id > 0 ? $this->db->escape($facsrc->cond_reglement_id) : "null");
  150. $sql.= ", ".($facsrc->mode_reglement_id > 0 ? $this->db->escape($facsrc->mode_reglement_id) : "null");
  151. $sql.= ", ".$this->usenewprice;
  152. $sql.= ", ".$this->frequency;
  153. $sql.= ", '".$this->db->escape($this->unit_frequency)."'";
  154. $sql.= ", ".(!empty($this->date_when)?"'".$this->db->idate($this->date_when)."'":'NULL');
  155. $sql.= ", ".(!empty($this->date_last_gen)?"'".$this->db->idate($this->date_last_gen)."'":'NULL');
  156. $sql.= ", ".$this->db->escape($this->nb_gen_done);
  157. $sql.= ", ".$this->db->escape($this->nb_gen_max);
  158. $sql.= ", ".$this->db->escape($this->auto_validate);
  159. $sql.= ", ".$this->db->escape($this->generate_pdf);
  160. $sql.= ", ".$this->db->escape($facsrc->fk_multicurrency);
  161. $sql.= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
  162. $sql.= ", ".$this->db->escape($facsrc->multicurrency_tx);
  163. $sql.= ", ".$this->db->escape($this->suspended);
  164. $sql.= ")";
  165. if ($this->db->query($sql))
  166. {
  167. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec");
  168. // Fields used into addline later
  169. $this->fk_multicurrency = $facsrc->fk_multicurrency;
  170. $this->multicurrency_code = $facsrc->multicurrency_code;
  171. $this->multicurrency_tx = $facsrc->multicurrency_tx;
  172. // Add lines
  173. $num=count($facsrc->lines);
  174. for ($i = 0; $i < $num; $i++)
  175. {
  176. $tva_tx = $facsrc->lines[$i]->tva_tx;
  177. if (! empty($facsrc->lines[$i]->vat_src_code) && ! preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')';
  178. $result_insert = $this->addline(
  179. $facsrc->lines[$i]->desc,
  180. $facsrc->lines[$i]->subprice,
  181. $facsrc->lines[$i]->qty,
  182. $tva_tx,
  183. $facsrc->lines[$i]->localtax1_tx,
  184. $facsrc->lines[$i]->localtax2_tx,
  185. $facsrc->lines[$i]->fk_product,
  186. $facsrc->lines[$i]->remise_percent,
  187. 'HT',
  188. $facsrc->lines[$i]->info_bits,
  189. '',
  190. 0,
  191. $facsrc->lines[$i]->product_type,
  192. $facsrc->lines[$i]->rang,
  193. $facsrc->lines[$i]->special_code,
  194. $facsrc->lines[$i]->label,
  195. $facsrc->lines[$i]->fk_unit,
  196. $facsrc->lines[$i]->multicurrency_subprice
  197. );
  198. if ($result_insert < 0)
  199. {
  200. $error++;
  201. }
  202. }
  203. if (! empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects
  204. {
  205. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  206. }
  207. // Add object linked
  208. if (! $error && $this->id && is_array($this->linked_objects) && ! empty($this->linked_objects))
  209. {
  210. foreach($this->linked_objects as $origin => $tmp_origin_id)
  211. {
  212. if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
  213. {
  214. foreach($tmp_origin_id as $origin_id)
  215. {
  216. $ret = $this->add_object_linked($origin, $origin_id);
  217. if (! $ret)
  218. {
  219. $this->error=$this->db->lasterror();
  220. $error++;
  221. }
  222. }
  223. }
  224. else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  225. {
  226. $origin_id = $tmp_origin_id;
  227. $ret = $this->add_object_linked($origin, $origin_id);
  228. if (! $ret)
  229. {
  230. $this->error=$this->db->lasterror();
  231. $error++;
  232. }
  233. }
  234. }
  235. }
  236. if ($error)
  237. {
  238. $this->db->rollback();
  239. }
  240. else
  241. {
  242. $this->db->commit();
  243. return $this->id;
  244. }
  245. }
  246. else
  247. {
  248. $this->error=$this->db->lasterror();
  249. $this->db->rollback();
  250. return -2;
  251. }
  252. }
  253. else
  254. {
  255. $this->db->rollback();
  256. return -1;
  257. }
  258. }
  259. /**
  260. * Load object and lines
  261. *
  262. * @param int $rowid Id of object to load
  263. * @param string $ref Reference of recurring invoice
  264. * @param string $ref_ext External reference of invoice
  265. * @param int $ref_int Internal reference of other object
  266. * @return int >0 if OK, <0 if KO, 0 if not found
  267. */
  268. function fetch($rowid, $ref='', $ref_ext='', $ref_int='')
  269. {
  270. $sql = 'SELECT f.rowid, f.entity, f.titre, f.suspended, f.fk_soc, f.amount, f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc';
  271. $sql.= ', f.remise_percent, f.remise_absolue, f.remise';
  272. $sql.= ', f.date_lim_reglement as dlr';
  273. $sql.= ', f.note_private, f.note_public, f.fk_user_author';
  274. $sql.= ', f.modelpdf';
  275. $sql.= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet';
  276. $sql.= ', f.fk_account';
  277. $sql.= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.usenewprice, f.auto_validate';
  278. $sql.= ', f.generate_pdf';
  279. $sql.= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  280. $sql.= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  281. $sql.= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  282. //$sql.= ', el.fk_source';
  283. $sql.= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
  284. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  285. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  286. //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
  287. $sql.= ' WHERE f.entity IN ('.getEntity('facture').')';
  288. if ($rowid) $sql.= ' AND f.rowid='.$rowid;
  289. elseif ($ref) $sql.= " AND f.titre='".$this->db->escape($ref)."'";
  290. /* This field are not used for template invoice
  291. if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  292. if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'";
  293. */
  294. $result = $this->db->query($sql);
  295. if ($result)
  296. {
  297. if ($this->db->num_rows($result))
  298. {
  299. $obj = $this->db->fetch_object($result);
  300. $this->id = $obj->rowid;
  301. $this->entity = $obj->entity;
  302. $this->titre = $obj->titre;
  303. $this->ref = $obj->titre;
  304. $this->ref_client = $obj->ref_client;
  305. $this->suspended = $obj->suspended;
  306. $this->type = $obj->type;
  307. $this->datep = $obj->dp;
  308. $this->date = $obj->df;
  309. $this->amount = $obj->amount;
  310. $this->remise_percent = $obj->remise_percent;
  311. $this->remise_absolue = $obj->remise_absolue;
  312. $this->remise = $obj->remise;
  313. $this->total_ht = $obj->total;
  314. $this->total_tva = $obj->tva;
  315. $this->total_localtax1 = $obj->localtax1;
  316. $this->total_localtax2 = $obj->localtax2;
  317. $this->total_ttc = $obj->total_ttc;
  318. $this->paye = $obj->paye;
  319. $this->close_code = $obj->close_code;
  320. $this->close_note = $obj->close_note;
  321. $this->socid = $obj->fk_soc;
  322. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  323. $this->mode_reglement_id = $obj->fk_mode_reglement;
  324. $this->mode_reglement_code = $obj->mode_reglement_code;
  325. $this->mode_reglement = $obj->mode_reglement_libelle;
  326. $this->cond_reglement_id = $obj->fk_cond_reglement;
  327. $this->cond_reglement_code = $obj->cond_reglement_code;
  328. $this->cond_reglement = $obj->cond_reglement_libelle;
  329. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  330. $this->fk_project = $obj->fk_projet;
  331. $this->fk_account = $obj->fk_account;
  332. $this->fk_facture_source = $obj->fk_facture_source;
  333. $this->note_private = $obj->note_private;
  334. $this->note_public = $obj->note_public;
  335. $this->user_author = $obj->fk_user_author;
  336. $this->modelpdf = $obj->modelpdf;
  337. $this->rang = $obj->rang;
  338. $this->special_code = $obj->special_code;
  339. $this->frequency = $obj->frequency;
  340. $this->unit_frequency = $obj->unit_frequency;
  341. $this->date_when = $this->db->jdate($obj->date_when);
  342. $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
  343. $this->nb_gen_done = $obj->nb_gen_done;
  344. $this->nb_gen_max = $obj->nb_gen_max;
  345. $this->usenewprice = $obj->usenewprice;
  346. $this->auto_validate = $obj->auto_validate;
  347. $this->generate_pdf = $obj->generate_pdf;
  348. // Multicurrency
  349. $this->fk_multicurrency = $obj->fk_multicurrency;
  350. $this->multicurrency_code = $obj->multicurrency_code;
  351. $this->multicurrency_tx = $obj->multicurrency_tx;
  352. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  353. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  354. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  355. if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1;
  356. // Retreive all extrafield
  357. // fetch optionals attributes and labels
  358. $this->fetch_optionals();
  359. /*
  360. * Lines
  361. */
  362. $result=$this->fetch_lines();
  363. if ($result < 0)
  364. {
  365. $this->error=$this->db->lasterror();
  366. return -3;
  367. }
  368. return 1;
  369. }
  370. else
  371. {
  372. $this->error='Bill with id '.$rowid.' or ref '.$ref.' not found sql='.$sql;
  373. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  374. return -2;
  375. }
  376. }
  377. else
  378. {
  379. $this->error=$this->db->error();
  380. return -1;
  381. }
  382. }
  383. /**
  384. * Create an array of invoice lines
  385. *
  386. * @return int >0 if OK, <0 if KO
  387. */
  388. function getLinesArray()
  389. {
  390. return $this->fetch_lines();
  391. }
  392. /**
  393. * Recupere les lignes de factures predefinies dans this->lines
  394. *
  395. * @return int 1 if OK, < 0 if KO
  396. */
  397. function fetch_lines()
  398. {
  399. $this->lines=array();
  400. // Retreive all extrafield for line
  401. // fetch optionals attributes and labels
  402. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  403. $extrafieldsline=new ExtraFields($this->db);
  404. $extrafieldsline=$extrafieldsline->fetch_name_optionals_label('facturedet_rec',true);
  405. $sql = 'SELECT l.rowid, l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx, ';
  406. $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
  407. $sql.= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc,';
  408. //$sql.= ' l.situation_percent, l.fk_prev_id,';
  409. //$sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice,';
  410. $sql.= ' l.rang, l.special_code,';
  411. //$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_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
  412. $sql.= ' l.fk_unit, l.fk_contract_line,';
  413. $sql.= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  414. $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  415. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
  416. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  417. $sql.= ' WHERE l.fk_facture = '.$this->id;
  418. $sql.= ' ORDER BY l.rang';
  419. dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
  420. $result = $this->db->query($sql);
  421. if ($result)
  422. {
  423. $num = $this->db->num_rows($result);
  424. $i = 0;
  425. while ($i < $num)
  426. {
  427. $objp = $this->db->fetch_object($result);
  428. $line = new FactureLigneRec($this->db);
  429. $line->id = $objp->rowid;
  430. $line->rowid = $objp->rowid;
  431. $line->desc = $objp->description; // Description line
  432. $line->description = $objp->description; // Description line
  433. $line->product_type = $objp->product_type; // Type of line
  434. $line->ref = $objp->product_ref; // Ref product
  435. $line->product_ref = $objp->product_ref; // Ref product
  436. $line->libelle = $objp->product_label; // deprecated
  437. $line->product_label = $objp->product_label; // Label product
  438. $line->product_desc = $objp->product_desc; // Description product
  439. $line->fk_product_type = $objp->fk_product_type; // Type of product
  440. $line->qty = $objp->qty;
  441. $line->subprice = $objp->subprice;
  442. $line->label = $objp->custom_label; // @deprecated
  443. $line->vat_src_code = $objp->vat_src_code;
  444. $line->tva_tx = $objp->tva_tx;
  445. $line->localtax1_tx = $objp->localtax1_tx;
  446. $line->localtax2_tx = $objp->localtax2_tx;
  447. $line->localtax1_type = $objp->localtax1_type;
  448. $line->localtax2_type = $objp->localtax2_type;
  449. $line->remise_percent = $objp->remise_percent;
  450. $line->fk_remise_except = $objp->fk_remise_except;
  451. $line->fk_product = $objp->fk_product;
  452. $line->date_start_fill = $objp->date_start_fill;
  453. $line->date_end_fill = $objp->date_end_fill;
  454. $line->info_bits = $objp->info_bits;
  455. $line->total_ht = $objp->total_ht;
  456. $line->total_tva = $objp->total_tva;
  457. $line->total_ttc = $objp->total_ttc;
  458. $line->code_ventilation = $objp->fk_code_ventilation;
  459. $line->rang = $objp->rang;
  460. $line->special_code = $objp->special_code;
  461. $line->fk_unit = $objp->fk_unit;
  462. $line->fk_contract_line = $objp->fk_contract_line;
  463. // Ne plus utiliser
  464. $line->price = $objp->price;
  465. $line->remise = $objp->remise;
  466. $extralabelsline = $line->fetch_optionals($line->id);
  467. // Multicurrency
  468. $line->fk_multicurrency = $objp->fk_multicurrency;
  469. $line->multicurrency_code = $objp->multicurrency_code;
  470. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  471. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  472. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  473. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  474. $this->lines[$i] = $line;
  475. $i++;
  476. }
  477. $this->db->free($result);
  478. return 1;
  479. }
  480. else
  481. {
  482. $this->error=$this->db->lasterror();
  483. return -3;
  484. }
  485. }
  486. /**
  487. * Delete template invoice
  488. *
  489. * @param User $user User that delete.
  490. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  491. * @param int $idwarehouse Id warehouse to use for stock change.
  492. * @return int <0 if KO, >0 if OK
  493. */
  494. function delete(User $user, $notrigger=0, $idwarehouse=-1)
  495. {
  496. $rowid=$this->id;
  497. dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG);
  498. $error=0;
  499. $this->db->begin();
  500. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".$rowid;
  501. dol_syslog($sql);
  502. if ($this->db->query($sql))
  503. {
  504. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".$rowid;
  505. dol_syslog($sql);
  506. if ($this->db->query($sql))
  507. {
  508. // Delete linked object
  509. $res = $this->deleteObjectLinked();
  510. if ($res < 0) $error=-3;
  511. }
  512. else
  513. {
  514. $this->error=$this->db->lasterror();
  515. $error=-1;
  516. }
  517. }
  518. else
  519. {
  520. $this->error=$this->db->lasterror();
  521. $error=-2;
  522. }
  523. if (! $error)
  524. {
  525. $this->db->commit();
  526. return 1;
  527. }
  528. else
  529. {
  530. $this->db->rollback();
  531. return $error;
  532. }
  533. }
  534. /**
  535. * Add a line to invoice
  536. *
  537. * @param string $desc Description de la ligne
  538. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  539. * @param double $qty Quantite
  540. * @param double $txtva Taux de tva force, sinon -1
  541. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  542. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  543. * @param int $fk_product Id du produit/service predefini
  544. * @param double $remise_percent Pourcentage de remise de la ligne
  545. * @param string $price_base_type HT or TTC
  546. * @param int $info_bits VAT npr or not ?
  547. * @param int $fk_remise_except Id remise
  548. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  549. * @param int $type Type of line (0=product, 1=service)
  550. * @param int $rang Position of line
  551. * @param int $special_code Special code
  552. * @param string $label Label of the line
  553. * @param string $fk_unit Unit
  554. * @param double $pu_ht_devise Unit price in currency
  555. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  556. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  557. * @return int <0 if KO, Id of line if OK
  558. */
  559. function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise=0, $date_start_fill=0, $date_end_fill=0)
  560. {
  561. global $mysoc;
  562. $facid=$this->id;
  563. 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,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type,fk_unit=$fk_unit,pu_ht_devise=$pu_ht_devise,date_start_fill=$date_start_fill,date_end_fill=$date_end_fill", LOG_DEBUG);
  564. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  565. // Check parameters
  566. if ($type < 0) return -1;
  567. $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  568. // Clean vat code
  569. $vat_src_code='';
  570. if (preg_match('/\((.*)\)/', $txtva, $reg))
  571. {
  572. $vat_src_code = $reg[1];
  573. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  574. }
  575. if ($this->brouillon)
  576. {
  577. // Clean parameters
  578. $remise_percent=price2num($remise_percent);
  579. if (empty($remise_percent)) $remise_percent=0;
  580. $qty=price2num($qty);
  581. $pu_ht = price2num($pu_ht);
  582. $pu_ttc = price2num($pu_ttc);
  583. $txtva = price2num($txtva);
  584. $txlocaltax1 = price2num($txlocaltax1);
  585. $txlocaltax2 = price2num($txlocaltax2);
  586. if (empty($txtva)) $txtva=0;
  587. if (empty($txlocaltax1)) $txlocaltax1=0;
  588. if (empty($txlocaltax2)) $txlocaltax2=0;
  589. if (empty($info_bits)) $info_bits=0;
  590. if ($price_base_type=='HT')
  591. {
  592. $pu=$pu_ht;
  593. }
  594. else
  595. {
  596. $pu=$pu_ttc;
  597. }
  598. // Calcul du total TTC et de la TVA pour la ligne a partir de
  599. // qty, pu, remise_percent et txtva
  600. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  601. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  602. $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  603. $total_ht = $tabprice[0];
  604. $total_tva = $tabprice[1];
  605. $total_ttc = $tabprice[2];
  606. $total_localtax1=$tabprice[9];
  607. $total_localtax2=$tabprice[10];
  608. $pu_ht = $tabprice[3];
  609. // MultiCurrency
  610. $multicurrency_total_ht = $tabprice[16];
  611. $multicurrency_total_tva = $tabprice[17];
  612. $multicurrency_total_ttc = $tabprice[18];
  613. $pu_ht_devise = $tabprice[19];
  614. $product_type=$type;
  615. if ($fk_product)
  616. {
  617. $product=new Product($this->db);
  618. $result=$product->fetch($fk_product);
  619. $product_type=$product->type;
  620. }
  621. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
  622. $sql.= "fk_facture";
  623. $sql.= ", label";
  624. $sql.= ", description";
  625. $sql.= ", price";
  626. $sql.= ", qty";
  627. $sql.= ", tva_tx";
  628. $sql.= ", vat_src_code";
  629. $sql.= ", localtax1_tx";
  630. $sql.= ", localtax1_type";
  631. $sql.= ", localtax2_tx";
  632. $sql.= ", localtax2_type";
  633. $sql.= ", fk_product";
  634. $sql.= ", product_type";
  635. $sql.= ", remise_percent";
  636. $sql.= ", subprice";
  637. $sql.= ", remise";
  638. $sql.= ", total_ht";
  639. $sql.= ", total_tva";
  640. $sql.= ", total_localtax1";
  641. $sql.= ", total_localtax2";
  642. $sql.= ", total_ttc";
  643. $sql.= ", date_start_fill";
  644. $sql.= ", date_end_fill";
  645. $sql.= ", info_bits";
  646. $sql.= ", rang";
  647. $sql.= ", special_code";
  648. $sql.= ", fk_unit";
  649. $sql.= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  650. $sql.= ") VALUES (";
  651. $sql.= "'".$facid."'";
  652. $sql.= ", ".(! empty($label)?"'".$this->db->escape($label)."'":"null");
  653. $sql.= ", '".$this->db->escape($desc)."'";
  654. $sql.= ", ".price2num($pu_ht);
  655. $sql.= ", ".price2num($qty);
  656. $sql.= ", ".price2num($txtva);
  657. $sql.= ", '".$this->db->escape($vat_src_code)."'";
  658. $sql.= ", ".price2num($txlocaltax1);
  659. $sql.= ", '".$this->db->escape($localtaxes_type[0])."'";
  660. $sql.= ", ".price2num($txlocaltax2);
  661. $sql.= ", '".$this->db->escape($localtaxes_type[2])."'";
  662. $sql.= ", ".(! empty($fk_product)?"'".$fk_product."'":"null");
  663. $sql.= ", ".$product_type;
  664. $sql.= ", ".price2num($remise_percent);
  665. $sql.= ", ".price2num($pu_ht);
  666. $sql.= ", null";
  667. $sql.= ", ".price2num($total_ht);
  668. $sql.= ", ".price2num($total_tva);
  669. $sql.= ", ".price2num($total_localtax1);
  670. $sql.= ", ".price2num($total_localtax2);
  671. $sql.= ", ".price2num($total_ttc);
  672. $sql.= ", ".(int) $date_start_fill;
  673. $sql.= ", ".(int) $date_end_fill;
  674. $sql.= ", ".$info_bits;
  675. $sql.= ", ".$rang;
  676. $sql.= ", ".$special_code;
  677. $sql.= ", ".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
  678. $sql.= ", ".(int) $this->fk_multicurrency;
  679. $sql.= ", '".$this->db->escape($this->multicurrency_code)."'";
  680. $sql.= ", ".price2num($pu_ht_devise);
  681. $sql.= ", ".price2num($multicurrency_total_ht);
  682. $sql.= ", ".price2num($multicurrency_total_tva);
  683. $sql.= ", ".price2num($multicurrency_total_ttc);
  684. $sql.= ")";
  685. dol_syslog(get_class($this)."::addline", LOG_DEBUG);
  686. if ($this->db->query($sql))
  687. {
  688. $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
  689. $this->id=$facid;
  690. $this->update_price();
  691. return $lineId;
  692. }
  693. else
  694. {
  695. $this->error=$this->db->lasterror();
  696. return -1;
  697. }
  698. }
  699. }
  700. /**
  701. * Update a line to invoice
  702. *
  703. * @param int $rowid Id of line to update
  704. * @param string $desc Description de la ligne
  705. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  706. * @param double $qty Quantite
  707. * @param double $txtva Taux de tva force, sinon -1
  708. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  709. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  710. * @param int $fk_product Id du produit/service predefini
  711. * @param double $remise_percent Pourcentage de remise de la ligne
  712. * @param string $price_base_type HT or TTC
  713. * @param int $info_bits Bits de type de lignes
  714. * @param int $fk_remise_except Id remise
  715. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  716. * @param int $type Type of line (0=product, 1=service)
  717. * @param int $rang Position of line
  718. * @param int $special_code Special code
  719. * @param string $label Label of the line
  720. * @param string $fk_unit Unit
  721. * @param double $pu_ht_devise Unit price in currency
  722. * @param int $notrigger disable line update trigger
  723. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  724. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  725. * @return int <0 if KO, Id of line if OK
  726. */
  727. function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1=0, $txlocaltax2=0, $fk_product=0, $remise_percent=0, $price_base_type='HT', $info_bits=0, $fk_remise_except='', $pu_ttc=0, $type=0, $rang=-1, $special_code=0, $label='', $fk_unit=null, $pu_ht_devise = 0, $notrigger=0, $date_start_fill=0, $date_end_fill=0)
  728. {
  729. global $mysoc;
  730. $facid=$this->id;
  731. dol_syslog(get_class($this)."::updateline facid=".$facid." rowid=$rowid, desc=$desc, pu_ht=$pu_ht, qty=$qty, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product, remise_percent=$remise_percent, info_bits=$info_bits, fk_remise_except=$fk_remise_except, price_base_type=$price_base_type, pu_ttc=$pu_ttc, type=$type, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
  732. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  733. // Clean parameters
  734. if (empty($remise_percent)) $remise_percent = 0;
  735. // Check parameters
  736. if ($type < 0) return -1;
  737. $localtaxes_type=getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  738. // Clean vat code
  739. $vat_src_code='';
  740. if (preg_match('/\((.*)\)/', $txtva, $reg))
  741. {
  742. $vat_src_code = $reg[1];
  743. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  744. }
  745. if ($this->brouillon)
  746. {
  747. // Clean parameters
  748. $remise_percent=price2num($remise_percent);
  749. $qty=price2num($qty);
  750. if (empty($info_bits)) $info_bits=0;
  751. $pu_ht=price2num($pu_ht);
  752. $pu_ttc=price2num($pu_ttc);
  753. $txtva=price2num($txtva);
  754. $txlocaltax1 = price2num($txlocaltax1);
  755. $txlocaltax2 = price2num($txlocaltax2);
  756. if (empty($txlocaltax1)) $txlocaltax1=0;
  757. if (empty($txlocaltax2)) $txlocaltax2=0;
  758. if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice=0;
  759. if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
  760. if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
  761. if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
  762. if ($price_base_type=='HT')
  763. {
  764. $pu=$pu_ht;
  765. }
  766. else
  767. {
  768. $pu=$pu_ttc;
  769. }
  770. // Calcul du total TTC et de la TVA pour la ligne a partir de
  771. // qty, pu, remise_percent et txtva
  772. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  773. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  774. $tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, 100, $this->multicurrency_tx, $pu_ht_devise);
  775. $total_ht = $tabprice[0];
  776. $total_tva = $tabprice[1];
  777. $total_ttc = $tabprice[2];
  778. $total_localtax1=$tabprice[9];
  779. $total_localtax2=$tabprice[10];
  780. $pu_ht = $tabprice[3];
  781. $pu_tva = $tabprice[4];
  782. $pu_ttc = $tabprice[5];
  783. // MultiCurrency
  784. $multicurrency_total_ht = $tabprice[16];
  785. $multicurrency_total_tva = $tabprice[17];
  786. $multicurrency_total_ttc = $tabprice[18];
  787. $pu_ht_devise = $tabprice[19];
  788. $product_type=$type;
  789. if ($fk_product)
  790. {
  791. $product=new Product($this->db);
  792. $result=$product->fetch($fk_product);
  793. $product_type=$product->type;
  794. }
  795. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
  796. $sql.= "fk_facture = '".$facid."'";
  797. $sql.= ", label=".(! empty($label)?"'".$this->db->escape($label)."'":"null");
  798. $sql.= ", description='".$this->db->escape($desc)."'";
  799. $sql.= ", price=".price2num($pu_ht);
  800. $sql.= ", qty=".price2num($qty);
  801. $sql.= ", tva_tx=".price2num($txtva);
  802. $sql.= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
  803. $sql.= ", localtax1_tx=".$txlocaltax1;
  804. $sql.= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
  805. $sql.= ", localtax2_tx=".$txlocaltax2;
  806. $sql.= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
  807. $sql.= ", fk_product=".(! empty($fk_product)?"'".$fk_product."'":"null");
  808. $sql.= ", product_type=".$product_type;
  809. $sql.= ", remise_percent='".price2num($remise_percent)."'";
  810. $sql.= ", subprice='".price2num($pu_ht)."'";
  811. $sql.= ", total_ht='".price2num($total_ht)."'";
  812. $sql.= ", total_tva='".price2num($total_tva)."'";
  813. $sql.= ", total_localtax1='".price2num($total_localtax1)."'";
  814. $sql.= ", total_localtax2='".price2num($total_localtax2)."'";
  815. $sql.= ", total_ttc='".price2num($total_ttc)."'";
  816. $sql.= ", date_start_fill=".((int) $date_start_fill);
  817. $sql.= ", date_end_fill=".((int) $date_end_fill);
  818. $sql.= ", info_bits=".$info_bits;
  819. $sql.= ", rang=".$rang;
  820. $sql.= ", special_code=".$special_code;
  821. $sql.= ", fk_unit=".($fk_unit?"'".$this->db->escape($fk_unit)."'":"null");
  822. $sql.= ', multicurrency_subprice = '.$pu_ht_devise;
  823. $sql.= ', multicurrency_total_ht = '.$multicurrency_total_ht;
  824. $sql.= ', multicurrency_total_tva = '.$multicurrency_total_tva;
  825. $sql.= ', multicurrency_total_ttc = '.$multicurrency_total_ttc;
  826. $sql.= " WHERE rowid = ".$rowid;
  827. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  828. if ($this->db->query($sql))
  829. {
  830. $this->id=$facid;
  831. $this->update_price();
  832. return 1;
  833. }
  834. else
  835. {
  836. $this->error=$this->db->lasterror();
  837. return -1;
  838. }
  839. }
  840. }
  841. /**
  842. * Return the next date of
  843. *
  844. * @return timestamp false if KO, timestamp if OK
  845. */
  846. function getNextDate()
  847. {
  848. if (empty($this->date_when)) return false;
  849. return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency);
  850. }
  851. /**
  852. * Return if maximum number of generation is reached
  853. *
  854. * @return boolean False by default, True if maximum number of generation is reached
  855. */
  856. function isMaxNbGenReached()
  857. {
  858. $ret = false;
  859. if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) $ret = true;
  860. return $ret;
  861. }
  862. /**
  863. * Format string to output with by striking the string if max number of generation was reached
  864. *
  865. * @param string $ret Default value to output
  866. * @return boolean False by default, True if maximum number of generation is reached
  867. */
  868. function strikeIfMaxNbGenReached($ret)
  869. {
  870. // Special case to strike the date
  871. return ($this->isMaxNbGenReached()?'<strike>':'').$ret.($this->isMaxNbGenReached()?'</strike>':'');
  872. }
  873. /**
  874. * Create all recurrents invoices (for all entities if multicompany is used).
  875. * A result may also be provided into this->output.
  876. *
  877. * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found.
  878. *
  879. * @param int $restictoninvoiceid 0=All qualified template invoices found. > 0 = restrict action on invoice ID
  880. * @param int $forcevalidation 1=Force validation of invoice whatever is template auto_validate flag.
  881. * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
  882. */
  883. function createRecurringInvoices($restictoninvoiceid=0, $forcevalidation=0)
  884. {
  885. global $conf, $langs, $db, $user;
  886. $error=0;
  887. $langs->load("bills");
  888. $langs->load('main');
  889. $nb_create=0;
  890. $now = dol_now();
  891. $tmparray=dol_getdate($now);
  892. $today = dol_mktime(23,59,59,$tmparray['mon'],$tmparray['mday'],$tmparray['year']); // Today is last second of current day
  893. dol_syslog("createRecurringInvoices restictoninvoiceid=".$restictoninvoiceid." forcevalidation=".$forcevalidation);
  894. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
  895. $sql.= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
  896. $sql.= " AND (date_when IS NULL OR date_when <= '".$db->idate($today)."')";
  897. $sql.= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
  898. $sql.= ' AND suspended = 0';
  899. $sql.= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here
  900. if ($restictoninvoiceid > 0) $sql.=' AND rowid = '.$restictoninvoiceid;
  901. $sql.= $db->order('entity', 'ASC');
  902. //print $sql;exit;
  903. $resql = $db->query($sql);
  904. if ($resql)
  905. {
  906. $i=0;
  907. $num = $db->num_rows($resql);
  908. if ($num) $this->output.=$langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n";
  909. else $this->output.=$langs->trans("NoQualifiedRecurringInvoiceTemplateFound");
  910. $saventity = $conf->entity;
  911. while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass.
  912. {
  913. $line = $db->fetch_object($resql);
  914. $db->begin();
  915. $invoiceidgenerated = 0;
  916. $facturerec = new FactureRec($db);
  917. $facturerec->fetch($line->rowid);
  918. if ($facturerec->id > 0)
  919. {
  920. // Set entity context
  921. $conf->entity = $facturerec->entity;
  922. dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
  923. $facture = new Facture($db);
  924. $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
  925. $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
  926. $facture->type = self::TYPE_STANDARD;
  927. $facture->brouillon = 1;
  928. $facture->date = (empty($facturerec->date_when)?$now:$facturerec->date_when); // We could also use dol_now here but we prefer date_when so invoice has real date when we would like even if we generate later.
  929. $facture->socid = $facturerec->socid;
  930. $invoiceidgenerated = $facture->create($user);
  931. if ($invoiceidgenerated <= 0)
  932. {
  933. $this->errors = $facture->errors;
  934. $this->error = $facture->error;
  935. $error++;
  936. }
  937. if (! $error && ($facturerec->auto_validate || $forcevalidation))
  938. {
  939. $result = $facture->validate($user);
  940. if ($result <= 0)
  941. {
  942. $this->errors = $facture->errors;
  943. $this->error = $facture->error;
  944. $error++;
  945. }
  946. }
  947. if (! $error && $facturerec->generate_pdf)
  948. {
  949. // We refresh the object in order to have all necessary data (like date_lim_reglement)
  950. $facture->fetch($facture->id);
  951. $result = $facture->generateDocument($facturerec->modelpdf, $langs);
  952. if ($result <= 0)
  953. {
  954. $this->errors = $facture->errors;
  955. $this->error = $facture->error;
  956. $error++;
  957. }
  958. }
  959. }
  960. else
  961. {
  962. $error++;
  963. $this->error="Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n";
  964. $this->errors[]="Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity;
  965. dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity);
  966. }
  967. if (! $error && $invoiceidgenerated >= 0)
  968. {
  969. $db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
  970. dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
  971. $nb_create++;
  972. $this->output.=$langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
  973. }
  974. else
  975. {
  976. $db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
  977. }
  978. $i++;
  979. }
  980. $conf->entity = $saventity; // Restore entity context
  981. }
  982. else dol_print_error($db);
  983. $this->output=trim($this->output);
  984. return $error?$error:0;
  985. }
  986. /**
  987. * Return clicable name (with picto eventually)
  988. *
  989. * @param int $withpicto Add picto into link
  990. * @param string $option Where point the link
  991. * @param int $max Maxlength of ref
  992. * @param int $short 1=Return just URL
  993. * @param string $moretitle Add more text to title tooltip
  994. * @param int $notooltip 1=Disable tooltip
  995. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  996. * @return string String with URL
  997. */
  998. function getNomUrl($withpicto=0,$option='',$max=0,$short=0,$moretitle='',$notooltip='',$save_lastsearch_value=-1)
  999. {
  1000. global $langs;
  1001. $result='';
  1002. $label = '<u>' . $langs->trans("ShowInvoice") . '</u>';
  1003. if (! empty($this->ref))
  1004. $label .= '<br><b>'.$langs->trans('Ref') . ':</b> ' . $this->ref;
  1005. if (! empty($this->date_last_gen))
  1006. $label .= '<br><b>'.$langs->trans('DateLastGeneration') . ':</b> ' . dol_print_date($this->date_last_gen, 'dayhour');
  1007. if ($this->frequency > 0)
  1008. {
  1009. if (! empty($this->date_when))
  1010. {
  1011. $label .= '<br><b>'.$langs->trans('NextDateToExecution') . ':</b> ';
  1012. $label .= (empty($this->suspended)?'':'<strike>'). dol_print_date($this->date_when, 'day').(empty($this->suspended)?'':'</strike>'); // No hour for this property
  1013. if (! empty($this->suspended)) $label .= ' ('.$langs->trans("Disabled").')';
  1014. }
  1015. }
  1016. $url = DOL_URL_ROOT.'/compta/facture/fiche-rec.php?facid='.$this->id;
  1017. if ($short) return $url;
  1018. if ($option != 'nolink')
  1019. {
  1020. // Add param to save lastsearch_values or not
  1021. $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
  1022. if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
  1023. if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
  1024. }
  1025. $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1026. $linkend='</a>';
  1027. $result .= $linkstart;
  1028. if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip?0:1);
  1029. if ($withpicto != 2) $result.= $this->ref;
  1030. $result .= $linkend;
  1031. return $result;
  1032. }
  1033. /**
  1034. * Return label of object status
  1035. *
  1036. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto
  1037. * @param integer $alreadypaid Not used on recurring invoices
  1038. * @return string Label of status
  1039. */
  1040. function getLibStatut($mode=0, $alreadypaid=-1)
  1041. {
  1042. return $this->LibStatut($this->frequency?1:0, $this->suspended, $mode, $alreadypaid, empty($this->type)?0:$this->type);
  1043. }
  1044. /**
  1045. * Return label of a status
  1046. *
  1047. * @param int $recur Is it a recurring invoice ?
  1048. * @param int $status Id status (suspended or not)
  1049. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=long label + picto
  1050. * @param integer $alreadypaid Not used for recurring invoices
  1051. * @param int $type Type invoice
  1052. * @return string Label of status
  1053. */
  1054. function LibStatut($recur, $status, $mode=0, $alreadypaid=-1, $type=0)
  1055. {
  1056. global $langs;
  1057. $langs->load('bills');
  1058. //print "$recur,$status,$mode,$alreadypaid,$type";
  1059. if ($mode == 0)
  1060. {
  1061. $prefix='';
  1062. if ($recur)
  1063. {
  1064. if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
  1065. else return $langs->trans('Active');
  1066. }
  1067. else
  1068. {
  1069. if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
  1070. else return $langs->trans("Draft");
  1071. }
  1072. }
  1073. if ($mode == 1)
  1074. {
  1075. $prefix='Short';
  1076. if ($recur)
  1077. {
  1078. if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
  1079. else return $langs->trans('Active');
  1080. }
  1081. else
  1082. {
  1083. if ($status == self::STATUS_SUSPENDED) return $langs->trans('Disabled');
  1084. else return $langs->trans("Draft");
  1085. }
  1086. }
  1087. if ($mode == 2)
  1088. {
  1089. if ($recur)
  1090. {
  1091. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
  1092. else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active');
  1093. }
  1094. else
  1095. {
  1096. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
  1097. else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
  1098. }
  1099. }
  1100. if ($mode == 3)
  1101. {
  1102. if ($recur)
  1103. {
  1104. $prefix='Short';
  1105. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6');
  1106. else return img_picto($langs->trans('Active'),'statut4');
  1107. }
  1108. else
  1109. {
  1110. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6');
  1111. else return img_picto($langs->trans('Draft'),'statut0');
  1112. }
  1113. }
  1114. if ($mode == 4)
  1115. {
  1116. $prefix='';
  1117. if ($recur)
  1118. {
  1119. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
  1120. else return img_picto($langs->trans('Active'),'statut4').' '.$langs->trans('Active');
  1121. }
  1122. else
  1123. {
  1124. if ($status == self::STATUS_SUSPENDED) return img_picto($langs->trans('Disabled'),'statut6').' '.$langs->trans('Disabled');
  1125. else return img_picto($langs->trans('Draft'),'statut0').' '.$langs->trans('Draft');
  1126. }
  1127. }
  1128. if ($mode == 5 || $mode == 6)
  1129. {
  1130. $prefix='';
  1131. if ($mode == 5) $prefix='Short';
  1132. if ($recur)
  1133. {
  1134. if ($status == self::STATUS_SUSPENDED) return '<span class="xhideonsmartphone">'.$langs->trans('Disabled').' </span>'.img_picto($langs->trans('Disabled'),'statut6');
  1135. else return '<span class="xhideonsmartphone">'.$langs->trans('Active').' </span>'.img_picto($langs->trans('Active'),'statut4');
  1136. }
  1137. else
  1138. {
  1139. if ($status == self::STATUS_SUSPENDED) return '<span class="xhideonsmartphone">'.$langs->trans('Disabled').' </span>'.img_picto($langs->trans('Disabled'),'statut6');
  1140. else return $langs->trans('Draft').' '.img_picto($langs->trans('Active'),'statut0');
  1141. }
  1142. }
  1143. }
  1144. /**
  1145. * Initialise an instance with random values.
  1146. * Used to build previews or test instances.
  1147. * id must be 0 if object instance is a specimen.
  1148. *
  1149. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  1150. * @return void
  1151. */
  1152. function initAsSpecimen($option='')
  1153. {
  1154. global $user,$langs,$conf;
  1155. $now=dol_now();
  1156. $arraynow=dol_getdate($now);
  1157. $nownotime=dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  1158. // Load array of products prodids
  1159. $num_prods = 0;
  1160. $prodids = array();
  1161. $sql = "SELECT rowid";
  1162. $sql.= " FROM ".MAIN_DB_PREFIX."product";
  1163. $sql.= " WHERE entity IN (".getEntity('product').")";
  1164. $resql = $this->db->query($sql);
  1165. if ($resql)
  1166. {
  1167. $num_prods = $this->db->num_rows($resql);
  1168. $i = 0;
  1169. while ($i < $num_prods)
  1170. {
  1171. $i++;
  1172. $row = $this->db->fetch_row($resql);
  1173. $prodids[$i] = $row[0];
  1174. }
  1175. }
  1176. // Initialize parameters
  1177. $this->id=0;
  1178. $this->ref = 'SPECIMEN';
  1179. $this->specimen=1;
  1180. $this->socid = 1;
  1181. $this->date = $nownotime;
  1182. $this->date_lim_reglement = $nownotime + 3600 * 24 *30;
  1183. $this->cond_reglement_id = 1;
  1184. $this->cond_reglement_code = 'RECEP';
  1185. $this->date_lim_reglement=$this->calculate_date_lim_reglement();
  1186. $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
  1187. $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
  1188. $this->note_public='This is a comment (public)';
  1189. $this->note_private='This is a comment (private)';
  1190. $this->note='This is a comment (private)';
  1191. $this->fk_incoterms=0;
  1192. $this->location_incoterms='';
  1193. if (empty($option) || $option != 'nolines')
  1194. {
  1195. // Lines
  1196. $nbp = 5;
  1197. $xnbp = 0;
  1198. while ($xnbp < $nbp)
  1199. {
  1200. $line=new FactureLigne($this->db);
  1201. $line->desc=$langs->trans("Description")." ".$xnbp;
  1202. $line->qty=1;
  1203. $line->subprice=100;
  1204. $line->tva_tx=19.6;
  1205. $line->localtax1_tx=0;
  1206. $line->localtax2_tx=0;
  1207. $line->remise_percent=0;
  1208. if ($xnbp == 1) // Qty is negative (product line)
  1209. {
  1210. $prodid = mt_rand(1, $num_prods);
  1211. $line->fk_product=$prodids[$prodid];
  1212. $line->qty=-1;
  1213. $line->total_ht=-100;
  1214. $line->total_ttc=-119.6;
  1215. $line->total_tva=-19.6;
  1216. }
  1217. else if ($xnbp == 2) // UP is negative (free line)
  1218. {
  1219. $line->subprice=-100;
  1220. $line->total_ht=-100;
  1221. $line->total_ttc=-119.6;
  1222. $line->total_tva=-19.6;
  1223. $line->remise_percent=0;
  1224. }
  1225. else if ($xnbp == 3) // Discount is 50% (product line)
  1226. {
  1227. $prodid = mt_rand(1, $num_prods);
  1228. $line->fk_product=$prodids[$prodid];
  1229. $line->total_ht=50;
  1230. $line->total_ttc=59.8;
  1231. $line->total_tva=9.8;
  1232. $line->remise_percent=50;
  1233. }
  1234. else // (product line)
  1235. {
  1236. $prodid = mt_rand(1, $num_prods);
  1237. $line->fk_product=$prodids[$prodid];
  1238. $line->total_ht=100;
  1239. $line->total_ttc=119.6;
  1240. $line->total_tva=19.6;
  1241. $line->remise_percent=00;
  1242. }
  1243. $this->lines[$xnbp]=$line;
  1244. $xnbp++;
  1245. $this->total_ht += $line->total_ht;
  1246. $this->total_tva += $line->total_tva;
  1247. $this->total_ttc += $line->total_ttc;
  1248. }
  1249. $this->revenuestamp = 0;
  1250. // Add a line "offered"
  1251. $line=new FactureLigne($this->db);
  1252. $line->desc=$langs->trans("Description")." (offered line)";
  1253. $line->qty=1;
  1254. $line->subprice=100;
  1255. $line->tva_tx=19.6;
  1256. $line->localtax1_tx=0;
  1257. $line->localtax2_tx=0;
  1258. $line->remise_percent=100;
  1259. $line->total_ht=0;
  1260. $line->total_ttc=0; // 90 * 1.196
  1261. $line->total_tva=0;
  1262. $prodid = mt_rand(1, $num_prods);
  1263. $line->fk_product=$prodids[$prodid];
  1264. $this->lines[$xnbp]=$line;
  1265. $xnbp++;
  1266. }
  1267. $this->usenewprice = 1;
  1268. }
  1269. /**
  1270. * Function used to replace a thirdparty id with another one.
  1271. *
  1272. * @param DoliDB $db Database handler
  1273. * @param int $origin_id Old thirdparty id
  1274. * @param int $dest_id New thirdparty id
  1275. * @return bool
  1276. */
  1277. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1278. {
  1279. $tables = array(
  1280. 'facture_rec'
  1281. );
  1282. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1283. }
  1284. /**
  1285. * Update frequency and unit
  1286. *
  1287. * @param int $frequency value of frequency
  1288. * @param string $unit unit of frequency (d, m, y)
  1289. * @return int <0 if KO, >0 if OK
  1290. */
  1291. function setFrequencyAndUnit($frequency,$unit)
  1292. {
  1293. if (! $this->table_element)
  1294. {
  1295. dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined",LOG_ERR);
  1296. return -1;
  1297. }
  1298. if (!empty($frequency) && empty($unit))
  1299. {
  1300. dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined",LOG_ERR);
  1301. return -2;
  1302. }
  1303. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1304. $sql.= ' SET frequency = '.($frequency?$this->db->escape($frequency):'null');
  1305. if (!empty($unit))
  1306. {
  1307. $sql.= ', unit_frequency = \''.$this->db->escape($unit).'\'';
  1308. }
  1309. $sql.= ' WHERE rowid = '.$this->id;
  1310. dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
  1311. if ($this->db->query($sql))
  1312. {
  1313. $this->frequency = $frequency;
  1314. if (!empty($unit)) $this->unit_frequency = $unit;
  1315. return 1;
  1316. }
  1317. else
  1318. {
  1319. dol_print_error($this->db);
  1320. return -1;
  1321. }
  1322. }
  1323. /**
  1324. * Update the next date of execution
  1325. *
  1326. * @param datetime $date date of execution
  1327. * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done
  1328. * @return int <0 if KO, >0 if OK
  1329. */
  1330. function setNextDate($date, $increment_nb_gen_done=0)
  1331. {
  1332. if (! $this->table_element)
  1333. {
  1334. dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined",LOG_ERR);
  1335. return -1;
  1336. }
  1337. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1338. $sql.= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
  1339. if ($increment_nb_gen_done>0) $sql.= ', nb_gen_done = nb_gen_done + 1';
  1340. $sql.= ' WHERE rowid = '.$this->id;
  1341. dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
  1342. if ($this->db->query($sql))
  1343. {
  1344. $this->date_when = $date;
  1345. if ($increment_nb_gen_done>0) $this->nb_gen_done++;
  1346. return 1;
  1347. }
  1348. else
  1349. {
  1350. dol_print_error($this->db);
  1351. return -1;
  1352. }
  1353. }
  1354. /**
  1355. * Update the maximum period
  1356. *
  1357. * @param int $nb number of maximum period
  1358. * @return int <0 if KO, >0 if OK
  1359. */
  1360. function setMaxPeriod($nb)
  1361. {
  1362. if (! $this->table_element)
  1363. {
  1364. dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined",LOG_ERR);
  1365. return -1;
  1366. }
  1367. if (empty($nb)) $nb=0;
  1368. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1369. $sql.= ' SET nb_gen_max = '.$nb;
  1370. $sql.= ' WHERE rowid = '.$this->id;
  1371. dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
  1372. if ($this->db->query($sql))
  1373. {
  1374. $this->nb_gen_max = $nb;
  1375. return 1;
  1376. }
  1377. else
  1378. {
  1379. dol_print_error($this->db);
  1380. return -1;
  1381. }
  1382. }
  1383. /**
  1384. * Update the auto validate flag of invoice
  1385. *
  1386. * @param int $validate 0 to create in draft, 1 to create and validate invoice
  1387. * @return int <0 if KO, >0 if OK
  1388. */
  1389. function setAutoValidate($validate)
  1390. {
  1391. if (! $this->table_element)
  1392. {
  1393. dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined",LOG_ERR);
  1394. return -1;
  1395. }
  1396. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1397. $sql.= ' SET auto_validate = '.$validate;
  1398. $sql.= ' WHERE rowid = '.$this->id;
  1399. dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
  1400. if ($this->db->query($sql))
  1401. {
  1402. $this->auto_validate = $validate;
  1403. return 1;
  1404. }
  1405. else
  1406. {
  1407. dol_print_error($this->db);
  1408. return -1;
  1409. }
  1410. }
  1411. /**
  1412. * Update the auto generate documents
  1413. *
  1414. * @param int $validate 0 no document, 1 to generate document
  1415. * @return int <0 if KO, >0 if OK
  1416. */
  1417. function setGeneratePdf($validate)
  1418. {
  1419. if (! $this->table_element)
  1420. {
  1421. dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined",LOG_ERR);
  1422. return -1;
  1423. }
  1424. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1425. $sql.= ' SET generate_pdf = '.$validate;
  1426. $sql.= ' WHERE rowid = '.$this->id;
  1427. dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG);
  1428. if ($this->db->query($sql))
  1429. {
  1430. $this->generate_pdf = $validate;
  1431. return 1;
  1432. }
  1433. else
  1434. {
  1435. dol_print_error($this->db);
  1436. return -1;
  1437. }
  1438. }
  1439. /**
  1440. * Update the model for documents
  1441. *
  1442. * @param string $model model of document generator
  1443. * @return int <0 if KO, >0 if OK
  1444. */
  1445. function setModelPdf($model)
  1446. {
  1447. if (! $this->table_element)
  1448. {
  1449. dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined",LOG_ERR);
  1450. return -1;
  1451. }
  1452. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1453. $sql.= ' SET modelpdf = "' . $model . '"';
  1454. $sql.= ' WHERE rowid = '.$this->id;
  1455. dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG);
  1456. if ($this->db->query($sql))
  1457. {
  1458. $this->modelpdf = $model;
  1459. return 1;
  1460. }
  1461. else
  1462. {
  1463. dol_print_error($this->db);
  1464. return -1;
  1465. }
  1466. }
  1467. }
  1468. /**
  1469. * Class to manage invoice lines of templates.
  1470. * Saved into database table llx_facturedet_rec
  1471. */
  1472. class FactureLigneRec extends CommonInvoiceLine
  1473. {
  1474. public $element='facturedetrec';
  1475. public $table_element='facturedet_rec';
  1476. var $date_start_fill;
  1477. var $date_end_fill;
  1478. /**
  1479. * Delete line in database
  1480. *
  1481. * @param User $user Object user
  1482. * @param int $notrigger Disable triggers
  1483. * @return int <0 if KO, >0 if OK
  1484. */
  1485. function delete(User $user, $notrigger = false)
  1486. {
  1487. $error=0;
  1488. $this->db->begin();
  1489. if (! $error) {
  1490. if (! $notrigger) {
  1491. // Call triggers
  1492. $result=$this->call_trigger('LINEBILLREC_DELETE', $user);
  1493. if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
  1494. // End call triggers
  1495. }
  1496. }
  1497. if (! $error)
  1498. {
  1499. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
  1500. $res = $this->db->query($sql);
  1501. if($res===false) {
  1502. $error++;
  1503. $this->errors[] = $this->db->lasterror();
  1504. }
  1505. }
  1506. // Commit or rollback
  1507. if ($error) {
  1508. $this->db->rollback();
  1509. return -1;
  1510. } else {
  1511. $this->db->commit();
  1512. return 1;
  1513. }
  1514. }
  1515. /**
  1516. * Recupere les lignes de factures predefinies dans this->lines
  1517. *
  1518. * @param int $rowid Id of invoice
  1519. * @return int 1 if OK, < 0 if KO
  1520. */
  1521. function fetch($rowid)
  1522. {
  1523. $sql = 'SELECT l.rowid, l.fk_facture ,l.fk_product, l.product_type, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
  1524. $sql.= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
  1525. $sql.= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
  1526. $sql.= ' l.rang, l.special_code,';
  1527. $sql.= ' l.fk_unit, l.fk_contract_line,';
  1528. $sql.= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  1529. $sql.= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
  1530. $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  1531. $sql.= ' WHERE l.rowid = '.$rowid;
  1532. $sql.= ' ORDER BY l.rang';
  1533. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  1534. $result = $this->db->query($sql);
  1535. if ($result)
  1536. {
  1537. $objp = $this->db->fetch_object($result);
  1538. $this->id = $objp->rowid;
  1539. $this->label = $objp->custom_label; // Label line
  1540. $this->desc = $objp->description; // Description line
  1541. $this->description = $objp->description; // Description line
  1542. $this->product_type = $objp->product_type; // Type of line
  1543. $this->ref = $objp->product_ref; // Ref product
  1544. $this->product_ref = $objp->product_ref; // Ref product
  1545. $this->libelle = $objp->product_label; // deprecated
  1546. $this->product_label = $objp->product_label; // Label product
  1547. $this->product_desc = $objp->product_desc; // Description product
  1548. $this->fk_product_type = $objp->fk_product_type; // Type of product
  1549. $this->qty = $objp->qty;
  1550. $this->price = $objp->price;
  1551. $this->subprice = $objp->subprice;
  1552. $this->fk_facture = $objp->fk_facture;
  1553. $this->vat_src_code = $objp->vat_src_code;
  1554. $this->tva_tx = $objp->tva_tx;
  1555. $this->localtax1_tx = $objp->localtax1_tx;
  1556. $this->localtax2_tx = $objp->localtax2_tx;
  1557. $this->localtax1_type = $objp->localtax1_type;
  1558. $this->localtax2_type = $objp->localtax2_type;
  1559. $this->remise_percent = $objp->remise_percent;
  1560. $this->fk_remise_except = $objp->fk_remise_except;
  1561. $this->fk_product = $objp->fk_product;
  1562. $this->date_start_fill = $objp->date_start_fill;
  1563. $this->date_end_fill = $objp->date_end_fill;
  1564. $this->info_bits = $objp->info_bits;
  1565. $this->total_ht = $objp->total_ht;
  1566. $this->total_tva = $objp->total_tva;
  1567. $this->total_ttc = $objp->total_ttc;
  1568. $this->code_ventilation = $objp->fk_code_ventilation;
  1569. $this->rang = $objp->rang;
  1570. $this->special_code = $objp->special_code;
  1571. $this->fk_unit = $objp->fk_unit;
  1572. $this->fk_contract_line = $objp->fk_contract_line;
  1573. $this->db->free($result);
  1574. return 1;
  1575. }
  1576. else
  1577. {
  1578. $this->error=$this->db->lasterror();
  1579. return -3;
  1580. }
  1581. }
  1582. /**
  1583. * Update a line to invoice_rec.
  1584. *
  1585. * @param User $user User
  1586. * @param int $notrigger No trigger
  1587. * @return int <0 if KO, Id of line if OK
  1588. */
  1589. function update(User $user, $notrigger=0)
  1590. {
  1591. global $conf;
  1592. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1593. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
  1594. $sql.= " fk_facture = ".$this->fk_facture;
  1595. $sql.= ", label=".(! empty($this->label)?"'".$this->db->escape($this->label)."'":"null");
  1596. $sql.= ", description='".$this->db->escape($this->desc)."'";
  1597. $sql.= ", price=".price2num($this->price);
  1598. $sql.= ", qty=".price2num($this->qty);
  1599. $sql.= ", tva_tx=".price2num($this->tva_tx);
  1600. $sql.= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
  1601. $sql.= ", localtax1_tx=".price2num($this->localtax1_tx);
  1602. $sql.= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  1603. $sql.= ", localtax2_tx=".price2num($this->localtax2_tx);
  1604. $sql.= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  1605. $sql.= ", fk_product=".($this->fk_product > 0 ? $this->fk_product :"null");
  1606. $sql.= ", product_type=".$this->product_type;
  1607. $sql.= ", remise_percent='".price2num($this->remise_percent)."'";
  1608. $sql.= ", subprice='".price2num($this->subprice)."'";
  1609. $sql.= ", info_bits='".price2num($this->info_bits)."'";
  1610. $sql.= ", date_start_fill=".(int) $this->date_start_fill;
  1611. $sql.= ", date_end_fill=".(int) $this->date_end_fill;
  1612. if (empty($this->skip_update_total))
  1613. {
  1614. $sql.= ", total_ht=".price2num($this->total_ht);
  1615. $sql.= ", total_tva=".price2num($this->total_tva);
  1616. $sql.= ", total_localtax1=".price2num($this->total_localtax1);
  1617. $sql.= ", total_localtax2=".price2num($this->total_localtax2);
  1618. $sql.= ", total_ttc=".price2num($this->total_ttc);
  1619. }
  1620. $sql.= ", rang=".$this->rang;
  1621. $sql.= ", special_code=".$this->special_code;
  1622. $sql.= ", fk_unit=".($this->fk_unit ?"'".$this->db->escape($this->fk_unit )."'":"null");
  1623. $sql.= ", fk_contract_line=".($this->fk_contract_line?$this->fk_contract_line:"null");
  1624. $sql.= " WHERE rowid = ".$this->id;
  1625. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  1626. $resql=$this->db->query($sql);
  1627. if ($resql)
  1628. {
  1629. if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  1630. {
  1631. $result=$this->insertExtraFields();
  1632. if ($result < 0)
  1633. {
  1634. $error++;
  1635. }
  1636. }
  1637. if (! $error && ! $notrigger)
  1638. {
  1639. // Call trigger
  1640. $result=$this->call_trigger('LINEBILL_REC_UPDATE', $user);
  1641. if ($result < 0)
  1642. {
  1643. $this->db->rollback();
  1644. return -2;
  1645. }
  1646. // End call triggers
  1647. }
  1648. $this->db->commit();
  1649. return 1;
  1650. }
  1651. else
  1652. {
  1653. $this->error=$this->db->lasterror();
  1654. $this->db->rollback();
  1655. return -2;
  1656. }
  1657. }
  1658. }