facture-rec.class.php 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319
  1. <?php
  2. /* Copyright (C) 2003-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2009-2012 Regis Houssin <regis.houssin@inodbox.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-2020 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 <https://www.gnu.org/licenses/>.
  23. */
  24. /**
  25. * \file htdocs/compta/facture/class/facture-rec.class.php
  26. * \ingroup facture
  27. * \brief File of class to manage recurring invoices
  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. const TRIGGER_PREFIX = 'BILLREC';
  39. /**
  40. * @var string ID to identify managed object
  41. */
  42. public $element = 'facturerec';
  43. /**
  44. * @var string Name of table without prefix where object is stored
  45. */
  46. public $table_element = 'facture_rec';
  47. /**
  48. * @var string Name of subtable line
  49. */
  50. public $table_element_line = 'facturedet_rec';
  51. /**
  52. * @var string Field with ID of parent key if this field has a parent
  53. */
  54. public $fk_element = 'fk_facture';
  55. /**
  56. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  57. */
  58. public $picto = 'bill';
  59. /**
  60. * @var int Entity
  61. */
  62. public $entity;
  63. /**
  64. * {@inheritdoc}
  65. */
  66. protected $table_ref_field = 'titre';
  67. /**
  68. * @var string The label of recurring invoice
  69. */
  70. public $title;
  71. public $socid;
  72. public $number;
  73. public $date;
  74. public $remise;
  75. public $remise_absolue;
  76. public $remise_percent;
  77. /**
  78. * @deprecated
  79. * @see $total_ht
  80. */
  81. public $total;
  82. /**
  83. * @deprecated
  84. * @see $total_tva
  85. */
  86. public $tva;
  87. public $date_last_gen;
  88. public $date_when;
  89. public $nb_gen_done;
  90. public $nb_gen_max;
  91. public $user_author;
  92. /**
  93. * @var int Frequency
  94. */
  95. public $frequency;
  96. /**
  97. * @var string Unit frequency
  98. */
  99. public $unit_frequency;
  100. public $rang;
  101. public $special_code;
  102. public $usenewprice = 0;
  103. public $date_lim_reglement;
  104. public $cond_reglement_code; // Code in llx_c_paiement
  105. public $mode_reglement_code; // Code in llx_c_paiement
  106. public $suspended; // status
  107. public $auto_validate; // 0 to create in draft, 1 to create and validate the new invoice
  108. public $generate_pdf; // 1 to generate PDF on invoice generation (default)
  109. /**
  110. * @var int 1 if status is draft
  111. * @deprecated
  112. */
  113. public $brouillon;
  114. /**
  115. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  116. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  117. * 'label' the translation key.
  118. * 'enabled' is a condition when the field must be managed.
  119. * 'position' is the sort order of field.
  120. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  121. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  122. * 'noteditable' says if field is not editable (1 or 0)
  123. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  124. * 'index' if we want an index in database.
  125. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  126. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  127. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  128. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  129. * 'help' is a string visible as a tooltip on field
  130. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  131. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  132. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  133. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  134. *
  135. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  136. */
  137. // BEGIN MODULEBUILDER PROPERTIES
  138. /**
  139. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  140. */
  141. public $fields = array(
  142. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  143. 'titre' =>array('type'=>'varchar(100)', 'label'=>'Titre', 'enabled'=>1, 'showoncombobox' => 1, 'visible'=>-1, 'position'=>15),
  144. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
  145. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'$conf->societe->enabled', 'visible'=>-1, 'notnull'=>1, 'position'=>25),
  146. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  147. //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
  148. 'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  149. //'remise_percent' =>array('type'=>'double', 'label'=>'Remise percent', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  150. //'remise_absolue' =>array('type'=>'double', 'label'=>'Remise absolue', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  151. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'Tva', 'enabled'=>1, 'visible'=>-1, 'position'=>55, 'isameasure'=>1),
  152. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'Localtax1', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'isameasure'=>1),
  153. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'Localtax2', 'enabled'=>1, 'visible'=>-1, 'position'=>65, 'isameasure'=>1),
  154. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'Total', 'enabled'=>1, 'visible'=>-1, 'position'=>70, 'isameasure'=>1),
  155. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>75, 'isameasure'=>1),
  156. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  157. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Fk projet', 'enabled'=>"isModEnabled('project')", 'visible'=>-1, 'position'=>85),
  158. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'Fk cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  159. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'Fk mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  160. 'date_lim_reglement' =>array('type'=>'date', 'label'=>'Date lim reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  161. 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>105),
  162. 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>110),
  163. 'modelpdf' =>array('type'=>'varchar(255)', 'label'=>'Modelpdf', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  164. 'date_when' =>array('type'=>'datetime', 'label'=>'Date when', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  165. 'date_last_gen' =>array('type'=>'datetime', 'label'=>'Date last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  166. 'nb_gen_done' =>array('type'=>'integer', 'label'=>'Nb gen done', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  167. 'nb_gen_max' =>array('type'=>'integer', 'label'=>'Nb gen max', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  168. 'frequency' =>array('type'=>'integer', 'label'=>'Frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
  169. 'unit_frequency' =>array('type'=>'varchar(2)', 'label'=>'UnitFrequency', 'enabled'=>1, 'visible'=>-1, 'position'=>152),
  170. 'usenewprice' =>array('type'=>'integer', 'label'=>'UseNewPrice', 'enabled'=>1, 'visible'=>0, 'position'=>155),
  171. 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>160, 'isameasure'=>1),
  172. 'auto_validate' =>array('type'=>'integer', 'label'=>'Auto validate', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  173. 'generate_pdf' =>array('type'=>'integer', 'label'=>'Generate pdf', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  174. 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>'$conf->banque->enabled', 'visible'=>-1, 'position'=>175),
  175. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  176. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  177. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>190, 'isameasure'=>1),
  178. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>195, 'isameasure'=>1),
  179. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>200, 'isameasure'=>1),
  180. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>205, 'isameasure'=>1),
  181. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>210),
  182. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>215),
  183. 'suspended' =>array('type'=>'integer', 'label'=>'Suspended', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  184. );
  185. // END MODULEBUILDER PROPERTIES
  186. const STATUS_NOTSUSPENDED = 0;
  187. const STATUS_SUSPENDED = 1;
  188. /**
  189. * Constructor
  190. *
  191. * @param DoliDB $db Database handler
  192. */
  193. public function __construct(DoliDB $db)
  194. {
  195. $this->db = $db;
  196. }
  197. /**
  198. * Create a predefined invoice
  199. *
  200. * @param User $user User object
  201. * @param int $facid Id of source invoice
  202. * @param int $notrigger No trigger
  203. * @return int <0 if KO, id of invoice created if OK
  204. */
  205. public function create($user, $facid, $notrigger = 0)
  206. {
  207. global $conf;
  208. $error = 0;
  209. $now = dol_now();
  210. // Clean parameters
  211. $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated
  212. $this->title = trim($this->title);
  213. $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice;
  214. if (empty($this->suspended)) {
  215. $this->suspended = 0;
  216. }
  217. // No frequency defined then no next date to execution
  218. if (empty($this->frequency)) {
  219. $this->frequency = 0;
  220. $this->date_when = null;
  221. }
  222. $this->frequency = abs($this->frequency);
  223. $this->nb_gen_done = 0;
  224. $this->nb_gen_max = empty($this->nb_gen_max) ? 0 : $this->nb_gen_max;
  225. $this->auto_validate = empty($this->auto_validate) ? 0 : $this->auto_validate;
  226. $this->generate_pdf = empty($this->generate_pdf) ? 0 : $this->generate_pdf;
  227. $this->db->begin();
  228. // Charge facture modele
  229. $facsrc = new Facture($this->db);
  230. $result = $facsrc->fetch($facid);
  231. if ($result > 0) {
  232. // On positionne en mode brouillon la facture
  233. $this->brouillon = 1;
  234. $this->fk_soc = $facsrc->socid;
  235. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_rec (";
  236. $sql .= "titre";
  237. $sql .= ", fk_soc";
  238. $sql .= ", entity";
  239. $sql .= ", datec";
  240. $sql .= ", amount";
  241. $sql .= ", remise";
  242. $sql .= ", note_private";
  243. $sql .= ", note_public";
  244. $sql .= ", modelpdf";
  245. $sql .= ", fk_user_author";
  246. $sql .= ", fk_projet";
  247. $sql .= ", fk_account";
  248. $sql .= ", fk_cond_reglement";
  249. $sql .= ", fk_mode_reglement";
  250. $sql .= ", usenewprice";
  251. $sql .= ", frequency";
  252. $sql .= ", unit_frequency";
  253. $sql .= ", date_when";
  254. $sql .= ", date_last_gen";
  255. $sql .= ", nb_gen_done";
  256. $sql .= ", nb_gen_max";
  257. $sql .= ", auto_validate";
  258. $sql .= ", generate_pdf";
  259. $sql .= ", fk_multicurrency";
  260. $sql .= ", multicurrency_code";
  261. $sql .= ", multicurrency_tx";
  262. $sql .= ", suspended";
  263. $sql .= ") VALUES (";
  264. $sql .= "'".$this->db->escape($this->titre ? $this->titre : $this->title)."'";
  265. $sql .= ", ".((int) $this->fk_soc);
  266. $sql .= ", ".((int) $conf->entity);
  267. $sql .= ", '".$this->db->idate($now)."'";
  268. $sql .= ", ".(!empty($facsrc->total_ttc) ? ((float) $facsrc->total_ttc) : '0');
  269. $sql .= ", ".(!empty($facsrc->remise_absolue) ? ((float) $this->remise_absolue) : '0');
  270. $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
  271. $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
  272. $sql .= ", ".(!empty($this->model_pdf) ? ("'".$this->db->escape($this->model_pdf)."'") : "NULL");
  273. $sql .= ", ".((int) $user->id);
  274. $sql .= ", ".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null");
  275. $sql .= ", ".(!empty($facsrc->fk_account) ? ((int) $facsrc->fk_account) : "null");
  276. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
  277. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
  278. $sql .= ", ".((int) $this->usenewprice);
  279. $sql .= ", ".((int) $this->frequency);
  280. $sql .= ", '".$this->db->escape($this->unit_frequency)."'";
  281. $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'NULL');
  282. $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'NULL');
  283. $sql .= ", ".((int) $this->nb_gen_done);
  284. $sql .= ", ".((int) $this->nb_gen_max);
  285. $sql .= ", ".((int) $this->auto_validate);
  286. $sql .= ", ".((int) $this->generate_pdf);
  287. $sql .= ", ".((int) $facsrc->fk_multicurrency);
  288. $sql .= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
  289. $sql .= ", ".((float) $facsrc->multicurrency_tx);
  290. $sql .= ", ".((int) $this->suspended);
  291. $sql .= ")";
  292. if ($this->db->query($sql)) {
  293. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec");
  294. // Fields used into addline later
  295. $this->fk_multicurrency = $facsrc->fk_multicurrency;
  296. $this->multicurrency_code = $facsrc->multicurrency_code;
  297. $this->multicurrency_tx = $facsrc->multicurrency_tx;
  298. // Add lines
  299. $num = count($facsrc->lines);
  300. for ($i = 0; $i < $num; $i++) {
  301. $tva_tx = $facsrc->lines[$i]->tva_tx;
  302. if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  303. $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')';
  304. }
  305. $default_start_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_START');
  306. $default_end_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_END');
  307. $result_insert = $this->addline(
  308. $facsrc->lines[$i]->desc,
  309. $facsrc->lines[$i]->subprice,
  310. $facsrc->lines[$i]->qty,
  311. $tva_tx,
  312. $facsrc->lines[$i]->localtax1_tx,
  313. $facsrc->lines[$i]->localtax2_tx,
  314. $facsrc->lines[$i]->fk_product,
  315. $facsrc->lines[$i]->remise_percent,
  316. 'HT',
  317. $facsrc->lines[$i]->info_bits,
  318. '',
  319. 0,
  320. $facsrc->lines[$i]->product_type,
  321. $facsrc->lines[$i]->rang,
  322. $facsrc->lines[$i]->special_code,
  323. $facsrc->lines[$i]->label,
  324. $facsrc->lines[$i]->fk_unit,
  325. $facsrc->lines[$i]->multicurrency_subprice,
  326. $default_start_fill,
  327. $default_end_fill,
  328. null,
  329. $facsrc->lines[$i]->pa_ht
  330. );
  331. if ($result_insert < 0) {
  332. $error++;
  333. } else {
  334. $objectline = new FactureLigneRec($this->db);
  335. $result2 = $objectline->fetch($result_insert);
  336. if ($result2 > 0) {
  337. // Extrafields
  338. if (method_exists($facsrc->lines[$i], 'fetch_optionals')) {
  339. $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->id);
  340. $objectline->array_options = $facsrc->lines[$i]->array_options;
  341. }
  342. $result = $objectline->insertExtraFields();
  343. if ($result < 0) {
  344. $error++;
  345. }
  346. } elseif ($result2 < 0) {
  347. $this->errors[] = $objectline->error;
  348. $error++;
  349. }
  350. }
  351. }
  352. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  353. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  354. }
  355. // Add object linked
  356. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  357. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  358. 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, ...))
  359. foreach ($tmp_origin_id as $origin_id) {
  360. $ret = $this->add_object_linked($origin, $origin_id);
  361. if (!$ret) {
  362. $this->error = $this->db->lasterror();
  363. $error++;
  364. }
  365. }
  366. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  367. {
  368. $origin_id = $tmp_origin_id;
  369. $ret = $this->add_object_linked($origin, $origin_id);
  370. if (!$ret) {
  371. $this->error = $this->db->lasterror();
  372. $error++;
  373. }
  374. }
  375. }
  376. }
  377. if (!$error) {
  378. $result = $this->insertExtraFields();
  379. if ($result < 0) {
  380. $error++;
  381. }
  382. }
  383. if (!$error && !$notrigger) {
  384. // Call trigger
  385. $result = $this->call_trigger('BILLREC_CREATE', $user);
  386. if ($result < 0) {
  387. $this->db->rollback();
  388. return -2;
  389. }
  390. // End call triggers
  391. }
  392. if ($error) {
  393. $this->db->rollback();
  394. return -3;
  395. } else {
  396. $this->db->commit();
  397. return $this->id;
  398. }
  399. } else {
  400. $this->error = $this->db->lasterror();
  401. $this->db->rollback();
  402. return -2;
  403. }
  404. } else {
  405. $this->db->rollback();
  406. return -1;
  407. }
  408. }
  409. /**
  410. * Update a line invoice_rec.
  411. *
  412. * @param User $user User
  413. * @param int $notrigger No trigger
  414. * @return int <0 if KO, Id of line if OK
  415. */
  416. public function update(User $user, $notrigger = 0)
  417. {
  418. $error = 0;
  419. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET";
  420. $sql .= " entity = ".((int) $this->entity).",";
  421. $sql .= " titre = '".$this->db->escape($this->title)."',";
  422. $sql .= " suspended = ".((int) $this->suspended).",";
  423. $sql .= " fk_soc = ".((int) $this->socid).",";
  424. $sql .= " total_tva = ".((float) $this->total_tva).",";
  425. $sql .= " localtax1 = ".((float) $this->total_localtax1).",";
  426. $sql .= " localtax2 = ".((float) $this->total_localtax2).",";
  427. $sql .= " total_ht = ".((float) $this->total_ht).",";
  428. $sql .= " total_ttc = ".((float) $this->total_ttc).",";
  429. $sql .= " remise_percent = ".((float) $this->remise_percent);
  430. // TODO Add missing fields
  431. $sql .= " WHERE rowid = ".((int) $this->id);
  432. $this->db->begin();
  433. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  434. $resql = $this->db->query($sql);
  435. if ($resql) {
  436. if (!$error) {
  437. $result = $this->insertExtraFields();
  438. if ($result < 0) {
  439. $error++;
  440. }
  441. }
  442. if (!$error && !$notrigger) {
  443. // Call trigger
  444. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  445. if ($result < 0) {
  446. $this->db->rollback();
  447. return -2;
  448. }
  449. // End call triggers
  450. }
  451. $this->db->commit();
  452. return 1;
  453. } else {
  454. $this->error = $this->db->lasterror();
  455. $this->db->rollback();
  456. return -1;
  457. }
  458. }
  459. /**
  460. * Load object and lines
  461. *
  462. * @param int $rowid Id of object to load
  463. * @param string $ref Reference of recurring invoice
  464. * @param string $ref_ext External reference of invoice
  465. * @return int >0 if OK, <0 if KO, 0 if not found
  466. */
  467. public function fetch($rowid, $ref = '', $ref_ext = '')
  468. {
  469. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  470. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc, f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc';
  471. $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
  472. $sql .= ', f.date_lim_reglement as dlr';
  473. $sql .= ', f.note_private, f.note_public, f.fk_user_author';
  474. $sql .= ', f.modelpdf as model_pdf';
  475. $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project';
  476. $sql .= ', f.fk_account';
  477. $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';
  478. $sql .= ', f.generate_pdf';
  479. $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  480. $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  481. $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  482. //$sql.= ', el.fk_source';
  483. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
  484. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  485. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  486. //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
  487. $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')';
  488. if ($rowid) {
  489. $sql .= ' AND f.rowid = '.((int) $rowid);
  490. } elseif ($ref) {
  491. $sql .= " AND f.titre = '".$this->db->escape($ref)."'";
  492. } else {
  493. $sql .= ' AND f.rowid = 0';
  494. }
  495. /* This field are not used for template invoice
  496. if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  497. */
  498. $result = $this->db->query($sql);
  499. if ($result) {
  500. if ($this->db->num_rows($result)) {
  501. $obj = $this->db->fetch_object($result);
  502. $this->id = $obj->rowid;
  503. $this->entity = $obj->entity;
  504. $this->titre = $obj->title; // deprecated
  505. $this->title = $obj->title;
  506. $this->ref = $obj->title;
  507. $this->suspended = $obj->suspended;
  508. $this->remise_percent = $obj->remise_percent;
  509. $this->remise_absolue = $obj->remise_absolue;
  510. $this->remise = $obj->remise;
  511. $this->total_ht = $obj->total_ht;
  512. $this->total_tva = $obj->total_tva;
  513. $this->total_localtax1 = $obj->localtax1;
  514. $this->total_localtax2 = $obj->localtax2;
  515. $this->total_ttc = $obj->total_ttc;
  516. $this->socid = $obj->fk_soc;
  517. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  518. $this->mode_reglement_id = $obj->fk_mode_reglement;
  519. $this->mode_reglement_code = $obj->mode_reglement_code;
  520. $this->mode_reglement = $obj->mode_reglement_libelle;
  521. $this->cond_reglement_id = $obj->fk_cond_reglement;
  522. $this->cond_reglement_code = $obj->cond_reglement_code;
  523. $this->cond_reglement = $obj->cond_reglement_libelle;
  524. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  525. $this->fk_project = $obj->fk_project;
  526. $this->fk_account = $obj->fk_account;
  527. $this->note_private = $obj->note_private;
  528. $this->note_public = $obj->note_public;
  529. $this->user_author = $obj->fk_user_author;
  530. $this->modelpdf = $obj->model_pdf; // deprecated
  531. $this->model_pdf = $obj->model_pdf;
  532. //$this->special_code = $obj->special_code;
  533. $this->frequency = $obj->frequency;
  534. $this->unit_frequency = $obj->unit_frequency;
  535. $this->date_when = $this->db->jdate($obj->date_when);
  536. $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
  537. $this->nb_gen_done = $obj->nb_gen_done;
  538. $this->nb_gen_max = $obj->nb_gen_max;
  539. $this->usenewprice = $obj->usenewprice;
  540. $this->auto_validate = $obj->auto_validate;
  541. $this->generate_pdf = $obj->generate_pdf;
  542. // Multicurrency
  543. $this->fk_multicurrency = $obj->fk_multicurrency;
  544. $this->multicurrency_code = $obj->multicurrency_code;
  545. $this->multicurrency_tx = $obj->multicurrency_tx;
  546. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  547. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  548. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  549. if ($this->statut == self::STATUS_DRAFT) {
  550. $this->brouillon = 1;
  551. }
  552. // Retrieve all extrafield
  553. // fetch optionals attributes and labels
  554. $this->fetch_optionals();
  555. /*
  556. * Lines
  557. */
  558. $result = $this->fetch_lines();
  559. if ($result < 0) {
  560. $this->error = $this->db->lasterror();
  561. return -3;
  562. }
  563. return 1;
  564. } else {
  565. $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
  566. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  567. return -2;
  568. }
  569. } else {
  570. $this->error = $this->db->error();
  571. return -1;
  572. }
  573. }
  574. /**
  575. * Create an array of invoice lines
  576. *
  577. * @return int >0 if OK, <0 if KO
  578. */
  579. public function getLinesArray()
  580. {
  581. return $this->fetch_lines();
  582. }
  583. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  584. /**
  585. * Get lines of template invoices into this->lines
  586. *
  587. * @return int 1 if OK, < 0 if KO
  588. */
  589. public function fetch_lines()
  590. {
  591. // phpcs:enable
  592. $this->lines = array();
  593. // Retrieve all extrafield for line
  594. // fetch optionals attributes and labels
  595. /*if (!is_object($extrafields)) {
  596. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  597. $extrafields = new ExtraFields($this->db);
  598. }
  599. $extrafields->fetch_name_optionals_label($this->table_element_line, true);
  600. */
  601. dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
  602. $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, ';
  603. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
  604. $sql .= ' l.info_bits, l.date_start_fill, l.date_end_fill, l.total_ht, l.total_tva, l.total_ttc, l.fk_product_fournisseur_price, l.buy_price_ht as pa_ht,';
  605. $sql .= ' l.rang, l.special_code,';
  606. $sql .= ' l.fk_unit, l.fk_contract_line,';
  607. $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  608. $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  609. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
  610. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  611. $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
  612. $sql .= ' ORDER BY l.rang';
  613. $result = $this->db->query($sql);
  614. if ($result) {
  615. $num = $this->db->num_rows($result);
  616. $i = 0;
  617. while ($i < $num) {
  618. $objp = $this->db->fetch_object($result);
  619. $line = new FactureLigneRec($this->db);
  620. $line->id = $objp->rowid;
  621. $line->rowid = $objp->rowid;
  622. $line->desc = $objp->description; // Description line
  623. $line->description = $objp->description; // Description line
  624. $line->ref = $objp->product_ref; // Ref product
  625. $line->product_ref = $objp->product_ref; // Ref product
  626. $line->libelle = $objp->product_label; // deprecated
  627. $line->product_label = $objp->product_label; // Label product
  628. $line->product_desc = $objp->product_desc; // Description product
  629. $line->product_type = $objp->product_type; // Type of line
  630. $line->fk_product_type = $objp->fk_product_type; // Type of product
  631. $line->qty = $objp->qty;
  632. $line->subprice = $objp->subprice;
  633. $line->label = $objp->custom_label; // @deprecated
  634. $line->vat_src_code = $objp->vat_src_code;
  635. $line->tva_tx = $objp->tva_tx;
  636. $line->localtax1_tx = $objp->localtax1_tx;
  637. $line->localtax2_tx = $objp->localtax2_tx;
  638. $line->localtax1_type = $objp->localtax1_type;
  639. $line->localtax2_type = $objp->localtax2_type;
  640. $line->remise_percent = $objp->remise_percent;
  641. //$line->fk_remise_except = $objp->fk_remise_except;
  642. $line->fk_product = $objp->fk_product;
  643. $line->date_start_fill = $objp->date_start_fill;
  644. $line->date_end_fill = $objp->date_end_fill;
  645. $line->info_bits = $objp->info_bits;
  646. $line->total_ht = $objp->total_ht;
  647. $line->total_tva = $objp->total_tva;
  648. $line->total_ttc = $objp->total_ttc;
  649. //$line->code_ventilation = $objp->fk_code_ventilation;
  650. $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
  651. $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility
  652. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht);
  653. $line->buyprice = $marginInfos[0];
  654. $line->pa_ht = $marginInfos[0]; // For backward compatibility
  655. $line->marge_tx = $marginInfos[1];
  656. $line->marque_tx = $marginInfos[2];
  657. $line->rang = $objp->rang;
  658. $line->special_code = $objp->special_code;
  659. $line->fk_unit = $objp->fk_unit;
  660. $line->fk_contract_line = $objp->fk_contract_line;
  661. // Ne plus utiliser
  662. $line->price = $objp->price;
  663. $line->remise = $objp->remise;
  664. $line->fetch_optionals();
  665. // Multicurrency
  666. $line->fk_multicurrency = $objp->fk_multicurrency;
  667. $line->multicurrency_code = $objp->multicurrency_code;
  668. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  669. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  670. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  671. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  672. $this->lines[$i] = $line;
  673. $i++;
  674. }
  675. $this->db->free($result);
  676. return 1;
  677. } else {
  678. $this->error = $this->db->lasterror();
  679. return -3;
  680. }
  681. }
  682. /**
  683. * Delete template invoice
  684. *
  685. * @param User $user User that delete.
  686. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  687. * @param int $idwarehouse Id warehouse to use for stock change.
  688. * @return int <0 if KO, >0 if OK
  689. */
  690. public function delete(User $user, $notrigger = 0, $idwarehouse = -1)
  691. {
  692. $rowid = $this->id;
  693. dol_syslog(get_class($this)."::delete rowid=".((int) $rowid), LOG_DEBUG);
  694. $error = 0;
  695. $this->db->begin();
  696. $main = MAIN_DB_PREFIX.'facturedet_rec';
  697. $ef = $main."_extrafields";
  698. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
  699. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".((int) $rowid);
  700. if ($this->db->query($sqlef) && $this->db->query($sql)) {
  701. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".((int) $rowid);
  702. dol_syslog($sql);
  703. if ($this->db->query($sql)) {
  704. // Delete linked object
  705. $res = $this->deleteObjectLinked();
  706. if ($res < 0) {
  707. $error = -3;
  708. }
  709. // Delete extrafields
  710. $res = $this->deleteExtraFields();
  711. if ($res < 0) {
  712. $error = -4;
  713. }
  714. } else {
  715. $this->error = $this->db->lasterror();
  716. $error = -1;
  717. }
  718. } else {
  719. $this->error = $this->db->lasterror();
  720. $error = -2;
  721. }
  722. if (!$error && !$notrigger) {
  723. // Call trigger
  724. $result = $this->call_trigger('BILLREC_DELETE', $user);
  725. if ($result < 0) {
  726. $error++;
  727. }
  728. // End call triggers
  729. }
  730. if (!$error) {
  731. $this->db->commit();
  732. return 1;
  733. } else {
  734. $this->db->rollback();
  735. return $error;
  736. }
  737. }
  738. /**
  739. * Add a line to invoice
  740. *
  741. * @param string $desc Description de la ligne
  742. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  743. * @param double $qty Quantite
  744. * @param double $txtva Taux de tva force, sinon -1
  745. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  746. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  747. * @param int $fk_product Product/Service ID predefined
  748. * @param double $remise_percent Percentage discount of the line
  749. * @param string $price_base_type HT or TTC
  750. * @param int $info_bits VAT npr or not ?
  751. * @param int $fk_remise_except Id remise
  752. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  753. * @param int $type Type of line (0=product, 1=service)
  754. * @param int $rang Position of line
  755. * @param int $special_code Special code
  756. * @param string $label Label of the line
  757. * @param string $fk_unit Unit
  758. * @param double $pu_ht_devise Unit price in currency
  759. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  760. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  761. * @param int $fk_fournprice Supplier price id (to calculate margin) or ''
  762. * @param int $pa_ht Buying price of line (to calculate margin) or ''
  763. * @return int <0 if KO, Id of line if OK
  764. */
  765. public 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, $fk_fournprice = null, $pa_ht = 0)
  766. {
  767. global $mysoc;
  768. $facid = $this->id;
  769. 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,pa_ht=$pa_ht", LOG_DEBUG);
  770. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  771. // Check parameters
  772. if ($type < 0) {
  773. return -1;
  774. }
  775. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  776. // Clean vat code
  777. $reg = array();
  778. $vat_src_code = '';
  779. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  780. $vat_src_code = $reg[1];
  781. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  782. }
  783. if ($this->brouillon) {
  784. // Clean parameters
  785. $remise_percent = price2num($remise_percent);
  786. if (empty($remise_percent)) {
  787. $remise_percent = 0;
  788. }
  789. $qty = price2num($qty);
  790. $pu_ht = price2num($pu_ht);
  791. $pu_ttc = price2num($pu_ttc);
  792. if (!preg_match('/\((.*)\)/', $txtva)) {
  793. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  794. }
  795. $txlocaltax1 = price2num($txlocaltax1);
  796. $txlocaltax2 = price2num($txlocaltax2);
  797. if (empty($txtva)) {
  798. $txtva = 0;
  799. }
  800. if (empty($txlocaltax1)) {
  801. $txlocaltax1 = 0;
  802. }
  803. if (empty($txlocaltax2)) {
  804. $txlocaltax2 = 0;
  805. }
  806. if (empty($info_bits)) {
  807. $info_bits = 0;
  808. }
  809. if ($price_base_type == 'HT') {
  810. $pu = $pu_ht;
  811. } else {
  812. $pu = $pu_ttc;
  813. }
  814. // Calcul du total TTC et de la TVA pour la ligne a partir de
  815. // qty, pu, remise_percent et txtva
  816. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  817. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  818. $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);
  819. $total_ht = $tabprice[0];
  820. $total_tva = $tabprice[1];
  821. $total_ttc = $tabprice[2];
  822. $total_localtax1 = $tabprice[9];
  823. $total_localtax2 = $tabprice[10];
  824. $pu_ht = $tabprice[3];
  825. // MultiCurrency
  826. $multicurrency_total_ht = $tabprice[16];
  827. $multicurrency_total_tva = $tabprice[17];
  828. $multicurrency_total_ttc = $tabprice[18];
  829. $pu_ht_devise = $tabprice[19];
  830. $product_type = $type;
  831. if ($fk_product) {
  832. $product = new Product($this->db);
  833. $result = $product->fetch($fk_product);
  834. $product_type = $product->type;
  835. }
  836. // Rank to use
  837. $ranktouse = $rang;
  838. if ($ranktouse == -1) {
  839. $rangmax = $this->line_max(0);
  840. $ranktouse = $rangmax + 1;
  841. }
  842. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
  843. $sql .= "fk_facture";
  844. $sql .= ", label";
  845. $sql .= ", description";
  846. $sql .= ", price";
  847. $sql .= ", qty";
  848. $sql .= ", tva_tx";
  849. $sql .= ", vat_src_code";
  850. $sql .= ", localtax1_tx";
  851. $sql .= ", localtax1_type";
  852. $sql .= ", localtax2_tx";
  853. $sql .= ", localtax2_type";
  854. $sql .= ", fk_product";
  855. $sql .= ", product_type";
  856. $sql .= ", remise_percent";
  857. $sql .= ", subprice";
  858. $sql .= ", remise";
  859. $sql .= ", total_ht";
  860. $sql .= ", total_tva";
  861. $sql .= ", total_localtax1";
  862. $sql .= ", total_localtax2";
  863. $sql .= ", total_ttc";
  864. $sql .= ", date_start_fill";
  865. $sql .= ", date_end_fill";
  866. $sql .= ", fk_product_fournisseur_price";
  867. $sql .= ", buy_price_ht";
  868. $sql .= ", info_bits";
  869. $sql .= ", rang";
  870. $sql .= ", special_code";
  871. $sql .= ", fk_unit";
  872. $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  873. $sql .= ") VALUES (";
  874. $sql .= " ".((int) $facid);
  875. $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
  876. $sql .= ", '".$this->db->escape($desc)."'";
  877. $sql .= ", ".price2num($pu_ht);
  878. $sql .= ", ".price2num($qty);
  879. $sql .= ", ".price2num($txtva);
  880. $sql .= ", '".$this->db->escape($vat_src_code)."'";
  881. $sql .= ", ".price2num($txlocaltax1);
  882. $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'";
  883. $sql .= ", ".price2num($txlocaltax2);
  884. $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'";
  885. $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
  886. $sql .= ", ".((int) $product_type);
  887. $sql .= ", ".price2num($remise_percent);
  888. $sql .= ", ".price2num($pu_ht);
  889. $sql .= ", null";
  890. $sql .= ", ".price2num($total_ht);
  891. $sql .= ", ".price2num($total_tva);
  892. $sql .= ", ".price2num($total_localtax1);
  893. $sql .= ", ".price2num($total_localtax2);
  894. $sql .= ", ".price2num($total_ttc);
  895. $sql .= ", ".(int) $date_start_fill;
  896. $sql .= ", ".(int) $date_end_fill;
  897. $sql .= ", ".($fk_fournprice > 0 ? $fk_fournprice : 'null');
  898. $sql .= ", ".($pa_ht ? price2num($pa_ht) : 0);
  899. $sql .= ", ".((int) $info_bits);
  900. $sql .= ", ".((int) $ranktouse);
  901. $sql .= ", ".((int) $special_code);
  902. $sql .= ", ".($fk_unit ? ((int) $fk_unit) : "null");
  903. $sql .= ", ".(int) $this->fk_multicurrency;
  904. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  905. $sql .= ", ".price2num($pu_ht_devise, 'CU');
  906. $sql .= ", ".price2num($multicurrency_total_ht, 'CT');
  907. $sql .= ", ".price2num($multicurrency_total_tva, 'CT');
  908. $sql .= ", ".price2num($multicurrency_total_ttc, 'CT');
  909. $sql .= ")";
  910. dol_syslog(get_class($this)."::addline", LOG_DEBUG);
  911. if ($this->db->query($sql)) {
  912. $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
  913. $this->id = $facid;
  914. $this->update_price(1);
  915. return $lineId;
  916. } else {
  917. $this->error = $this->db->lasterror();
  918. return -1;
  919. }
  920. }
  921. }
  922. /**
  923. * Update a line to invoice
  924. *
  925. * @param int $rowid Id of line to update
  926. * @param string $desc Description de la ligne
  927. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  928. * @param double $qty Quantite
  929. * @param double $txtva Taux de tva force, sinon -1
  930. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  931. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  932. * @param int $fk_product Product/Service ID predefined
  933. * @param double $remise_percent Percentage discount of the line
  934. * @param string $price_base_type HT or TTC
  935. * @param int $info_bits Bits of type of lines
  936. * @param int $fk_remise_except Id remise
  937. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  938. * @param int $type Type of line (0=product, 1=service)
  939. * @param int $rang Position of line
  940. * @param int $special_code Special code
  941. * @param string $label Label of the line
  942. * @param string $fk_unit Unit
  943. * @param double $pu_ht_devise Unit price in currency
  944. * @param int $notrigger disable line update trigger
  945. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  946. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  947. * @param int $fk_fournprice Id of origin supplier price
  948. * @param int $pa_ht Price (without tax) of product for margin calculation
  949. * @return int <0 if KO, Id of line if OK
  950. */
  951. public 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, $fk_fournprice = null, $pa_ht = 0)
  952. {
  953. global $mysoc;
  954. $facid = $this->id;
  955. 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);
  956. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  957. // Clean parameters
  958. if (empty($remise_percent)) {
  959. $remise_percent = 0;
  960. }
  961. // Check parameters
  962. if ($type < 0) {
  963. return -1;
  964. }
  965. if ($this->brouillon) {
  966. // Clean parameters
  967. $remise_percent = price2num($remise_percent);
  968. $qty = price2num($qty);
  969. if (empty($info_bits)) {
  970. $info_bits = 0;
  971. }
  972. $pu_ht = price2num($pu_ht);
  973. $pu_ttc = price2num($pu_ttc);
  974. $pu_ht_devise = price2num($pu_ht_devise);
  975. if (!preg_match('/\((.*)\)/', $txtva)) {
  976. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  977. }
  978. $txlocaltax1 = price2num($txlocaltax1);
  979. $txlocaltax2 = price2num($txlocaltax2);
  980. if (empty($txlocaltax1)) {
  981. $txlocaltax1 = 0;
  982. }
  983. if (empty($txlocaltax2)) {
  984. $txlocaltax2 = 0;
  985. }
  986. if (empty($this->multicurrency_subprice)) {
  987. $this->multicurrency_subprice = 0;
  988. }
  989. if (empty($this->multicurrency_total_ht)) {
  990. $this->multicurrency_total_ht = 0;
  991. }
  992. if (empty($this->multicurrency_total_tva)) {
  993. $this->multicurrency_total_tva = 0;
  994. }
  995. if (empty($this->multicurrency_total_ttc)) {
  996. $this->multicurrency_total_ttc = 0;
  997. }
  998. if ($price_base_type == 'HT') {
  999. $pu = $pu_ht;
  1000. } else {
  1001. $pu = $pu_ttc;
  1002. }
  1003. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  1004. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1005. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1006. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  1007. // Clean vat code
  1008. $vat_src_code = '';
  1009. $reg = array();
  1010. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  1011. $vat_src_code = $reg[1];
  1012. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  1013. }
  1014. $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);
  1015. $total_ht = $tabprice[0];
  1016. $total_tva = $tabprice[1];
  1017. $total_ttc = $tabprice[2];
  1018. $total_localtax1 = $tabprice[9];
  1019. $total_localtax2 = $tabprice[10];
  1020. $pu_ht = $tabprice[3];
  1021. $pu_tva = $tabprice[4];
  1022. $pu_ttc = $tabprice[5];
  1023. // MultiCurrency
  1024. $multicurrency_total_ht = $tabprice[16];
  1025. $multicurrency_total_tva = $tabprice[17];
  1026. $multicurrency_total_ttc = $tabprice[18];
  1027. $pu_ht_devise = $tabprice[19];
  1028. $product_type = $type;
  1029. if ($fk_product) {
  1030. $product = new Product($this->db);
  1031. $result = $product->fetch($fk_product);
  1032. $product_type = $product->type;
  1033. }
  1034. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
  1035. $sql .= "fk_facture = ".((int) $facid);
  1036. $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
  1037. $sql .= ", description='".$this->db->escape($desc)."'";
  1038. $sql .= ", price=".price2num($pu_ht);
  1039. $sql .= ", qty=".price2num($qty);
  1040. $sql .= ", tva_tx=".price2num($txtva);
  1041. $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
  1042. $sql .= ", localtax1_tx=".((float) $txlocaltax1);
  1043. $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
  1044. $sql .= ", localtax2_tx=".((float) $txlocaltax2);
  1045. $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
  1046. $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
  1047. $sql .= ", product_type=".((int) $product_type);
  1048. $sql .= ", remise_percent='".price2num($remise_percent)."'";
  1049. $sql .= ", subprice='".price2num($pu_ht)."'";
  1050. $sql .= ", total_ht='".price2num($total_ht)."'";
  1051. $sql .= ", total_tva='".price2num($total_tva)."'";
  1052. $sql .= ", total_localtax1='".price2num($total_localtax1)."'";
  1053. $sql .= ", total_localtax2='".price2num($total_localtax2)."'";
  1054. $sql .= ", total_ttc='".price2num($total_ttc)."'";
  1055. $sql .= ", date_start_fill=".((int) $date_start_fill);
  1056. $sql .= ", date_end_fill=".((int) $date_end_fill);
  1057. $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null');
  1058. $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0);
  1059. $sql .= ", info_bits=".((int) $info_bits);
  1060. $sql .= ", rang=".((int) $rang);
  1061. $sql .= ", special_code=".((int) $special_code);
  1062. $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
  1063. $sql .= ', multicurrency_subprice = '.price2num($pu_ht_devise);
  1064. $sql .= ', multicurrency_total_ht = '.price2num($multicurrency_total_ht);
  1065. $sql .= ', multicurrency_total_tva = '.price2num($multicurrency_total_tva);
  1066. $sql .= ', multicurrency_total_ttc = '.price2num($multicurrency_total_ttc);
  1067. $sql .= " WHERE rowid = ".((int) $rowid);
  1068. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  1069. if ($this->db->query($sql)) {
  1070. $this->id = $facid;
  1071. $this->update_price(1);
  1072. return 1;
  1073. } else {
  1074. $this->error = $this->db->lasterror();
  1075. return -1;
  1076. }
  1077. }
  1078. }
  1079. /**
  1080. * Return the next date of
  1081. *
  1082. * @return int|false false if KO, timestamp if OK
  1083. */
  1084. public function getNextDate()
  1085. {
  1086. if (empty($this->date_when)) {
  1087. return false;
  1088. }
  1089. return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency);
  1090. }
  1091. /**
  1092. * Return if maximum number of generation is reached
  1093. *
  1094. * @return boolean False by default, True if maximum number of generation is reached
  1095. */
  1096. public function isMaxNbGenReached()
  1097. {
  1098. $ret = false;
  1099. if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) {
  1100. $ret = true;
  1101. }
  1102. return $ret;
  1103. }
  1104. /**
  1105. * Format string to output with by striking the string if max number of generation was reached
  1106. *
  1107. * @param string $ret Default value to output
  1108. * @return boolean False by default, True if maximum number of generation is reached
  1109. */
  1110. public function strikeIfMaxNbGenReached($ret)
  1111. {
  1112. // Special case to strike the date
  1113. return ($this->isMaxNbGenReached() ? '<strike>' : '').$ret.($this->isMaxNbGenReached() ? '</strike>' : '');
  1114. }
  1115. /**
  1116. * Create all recurrents invoices (for all entities if multicompany is used).
  1117. * A result may also be provided into this->output.
  1118. *
  1119. * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found.
  1120. *
  1121. * @param int $restrictioninvoiceid 0=All qualified template invoices found. > 0 = restrict action on invoice ID
  1122. * @param int $forcevalidation 1=Force validation of invoice whatever is template auto_validate flag.
  1123. * @param int $notrigger Disable the trigger
  1124. * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
  1125. */
  1126. public function createRecurringInvoices($restrictioninvoiceid = 0, $forcevalidation = 0, $notrigger = 0)
  1127. {
  1128. global $conf, $langs, $db, $user, $hookmanager;
  1129. $error = 0;
  1130. $nb_create = 0;
  1131. // Load translation files required by the page
  1132. $langs->loadLangs(array("main", "bills"));
  1133. $now = dol_now();
  1134. $tmparray = dol_getdate($now);
  1135. $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day
  1136. $this->output = null;
  1137. dol_syslog("createRecurringInvoices restrictioninvoiceid=".$restrictioninvoiceid." forcevalidation=".$forcevalidation);
  1138. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture_rec';
  1139. $sql .= ' WHERE frequency > 0'; // A recurring invoice is an invoice with a frequency
  1140. $sql .= " AND (date_when IS NULL OR date_when <= '".$this->db->idate($today)."')";
  1141. $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)';
  1142. $sql .= ' AND suspended = 0';
  1143. $sql .= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here
  1144. if ($restrictioninvoiceid > 0) {
  1145. $sql .= ' AND rowid = '.((int) $restrictioninvoiceid);
  1146. }
  1147. $sql .= $this->db->order('entity', 'ASC');
  1148. //print $sql;exit;
  1149. $parameters = array(
  1150. 'restrictioninvoiceid' => $restrictioninvoiceid,
  1151. 'forcevalidation' => $forcevalidation,
  1152. );
  1153. $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks
  1154. $resql = $this->db->query($sql);
  1155. if ($resql) {
  1156. $i = 0;
  1157. $num = $this->db->num_rows($resql);
  1158. if ($num) {
  1159. $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n";
  1160. } else {
  1161. $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound");
  1162. }
  1163. $saventity = $conf->entity;
  1164. while ($i < $num) { // Loop on each template invoice. If $num = 0, test is false at first pass.
  1165. $line = $this->db->fetch_object($resql);
  1166. $this->db->begin();
  1167. $invoiceidgenerated = 0;
  1168. $facture = null;
  1169. $facturerec = new FactureRec($this->db);
  1170. $facturerec->fetch($line->rowid);
  1171. if ($facturerec->id > 0) {
  1172. // Set entity context
  1173. $conf->entity = $facturerec->entity;
  1174. dol_syslog("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref.", entity=".$facturerec->entity);
  1175. $facture = new Facture($this->db);
  1176. $facture->fac_rec = $facturerec->id; // We will create $facture from this recurring invoice
  1177. $facture->fk_fac_rec_source = $facturerec->id; // We will create $facture from this recurring invoice
  1178. $facture->type = self::TYPE_STANDARD;
  1179. $facture->brouillon = 1;
  1180. $facture->statut = self::STATUS_DRAFT;
  1181. $facture->status = self::STATUS_DRAFT;
  1182. $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.
  1183. $facture->socid = $facturerec->socid;
  1184. if (!empty($facturerec->fk_multicurrency)) {
  1185. $facture->fk_multicurrency = $facturerec->fk_multicurrency;
  1186. $facture->multicurrency_code = $facturerec->multicurrency_code;
  1187. $facture->multicurrency_tx = $facturerec->multicurrency_tx;
  1188. }
  1189. $invoiceidgenerated = $facture->create($user);
  1190. if ($invoiceidgenerated <= 0) {
  1191. $this->errors = $facture->errors;
  1192. $this->error = $facture->error;
  1193. $error++;
  1194. }
  1195. if (!$error && ($facturerec->auto_validate || $forcevalidation)) {
  1196. $result = $facture->validate($user);
  1197. if ($result <= 0) {
  1198. $this->errors = $facture->errors;
  1199. $this->error = $facture->error;
  1200. $error++;
  1201. }
  1202. }
  1203. if (!$error && $facturerec->generate_pdf) {
  1204. // We refresh the object in order to have all necessary data (like date_lim_reglement)
  1205. $facture->fetch($facture->id);
  1206. $result = $facture->generateDocument($facturerec->model_pdf, $langs);
  1207. if ($result <= 0) {
  1208. $this->errors = $facture->errors;
  1209. $this->error = $facture->error;
  1210. $error++;
  1211. }
  1212. }
  1213. if (!$error && !$notrigger) {
  1214. // Call trigger
  1215. $result = $facturerec->call_trigger('BILLREC_CREATEBILL', $user);
  1216. if ($result < 0) {
  1217. $this->errors = $facturerec->errors;
  1218. $this->error = $facturerec->error;
  1219. $error++;
  1220. }
  1221. // End call triggers
  1222. }
  1223. } else {
  1224. $error++;
  1225. $this->error = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity."\n";
  1226. $this->errors[] = "Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity;
  1227. dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity);
  1228. }
  1229. if (!$error && $invoiceidgenerated >= 0) {
  1230. $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
  1231. dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation");
  1232. $nb_create++;
  1233. $this->output .= $langs->trans("InvoiceGeneratedFromTemplate", $facture->ref, $facturerec->ref)."\n";
  1234. } else {
  1235. $this->db->rollback("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref);
  1236. }
  1237. $parameters = array(
  1238. 'cpt' => $i,
  1239. 'total' => $num,
  1240. 'errorCount' => $error,
  1241. 'invoiceidgenerated' => $invoiceidgenerated,
  1242. 'facturerec' => $facturerec, // it's an object which PHP passes by "reference", so modifiable by hooks.
  1243. 'this' => $this, // it's an object which PHP passes by "reference", so modifiable by hooks.
  1244. );
  1245. $reshook = $hookmanager->executeHooks('afterCreationOfRecurringInvoice', $parameters, $facture); // note: $facture can be modified by hooks (warning: $facture can be null)
  1246. $i++;
  1247. }
  1248. $conf->entity = $saventity; // Restore entity context
  1249. } else {
  1250. dol_print_error($this->db);
  1251. }
  1252. $this->output = trim($this->output);
  1253. return $error ? $error : 0;
  1254. }
  1255. /**
  1256. * Return clicable name (with picto eventually)
  1257. *
  1258. * @param int $withpicto Add picto into link
  1259. * @param string $option Where point the link
  1260. * @param int $max Maxlength of ref
  1261. * @param int $short 1=Return just URL
  1262. * @param string $moretitle Add more text to title tooltip
  1263. * @param int $notooltip 1=Disable tooltip
  1264. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1265. * @return string String with URL
  1266. */
  1267. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = '', $save_lastsearch_value = -1)
  1268. {
  1269. global $langs, $hookmanager;
  1270. $result = '';
  1271. $label = '<u>'.$langs->trans("RepeatableInvoice").'</u>';
  1272. if (!empty($this->ref)) {
  1273. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1274. }
  1275. if ($this->frequency > 0) {
  1276. $label .= '<br><b>'.$langs->trans('Frequency').':</b> '.$langs->trans('FrequencyPer_'.$this->unit_frequency, $this->frequency);
  1277. }
  1278. if (!empty($this->date_last_gen)) {
  1279. $label .= '<br><b>'.$langs->trans('DateLastGeneration').':</b> '.dol_print_date($this->date_last_gen, 'dayhour');
  1280. }
  1281. if ($this->frequency > 0) {
  1282. if (!empty($this->date_when)) {
  1283. $label .= '<br><b>'.$langs->trans('NextDateToExecution').':</b> ';
  1284. $label .= (empty($this->suspended) ? '' : '<strike>').dol_print_date($this->date_when, 'day').(empty($this->suspended) ? '' : '</strike>'); // No hour for this property
  1285. if (!empty($this->suspended)) {
  1286. $label .= ' ('.$langs->trans("Disabled").')';
  1287. }
  1288. }
  1289. }
  1290. $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id;
  1291. if ($short) {
  1292. return $url;
  1293. }
  1294. if ($option != 'nolink') {
  1295. // Add param to save lastsearch_values or not
  1296. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1297. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1298. $add_save_lastsearch_values = 1;
  1299. }
  1300. if ($add_save_lastsearch_values) {
  1301. $url .= '&save_lastsearch_values=1';
  1302. }
  1303. }
  1304. $linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  1305. $linkend = '</a>';
  1306. $result .= $linkstart;
  1307. if ($withpicto) {
  1308. $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);
  1309. }
  1310. if ($withpicto != 2) {
  1311. $result .= $this->ref;
  1312. }
  1313. $result .= $linkend;
  1314. global $action;
  1315. $hookmanager->initHooks(array($this->element . 'dao'));
  1316. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1317. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1318. if ($reshook > 0) {
  1319. $result = $hookmanager->resPrint;
  1320. } else {
  1321. $result .= $hookmanager->resPrint;
  1322. }
  1323. return $result;
  1324. }
  1325. /**
  1326. * Return label of object status
  1327. *
  1328. * @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
  1329. * @param integer $alreadypaid Not used on recurring invoices
  1330. * @return string Label of status
  1331. */
  1332. public function getLibStatut($mode = 0, $alreadypaid = -1)
  1333. {
  1334. return $this->LibStatut($this->frequency ? 1 : 0, $this->suspended, $mode, $alreadypaid, empty($this->type) ? 0 : $this->type);
  1335. }
  1336. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1337. /**
  1338. * Return label of a status
  1339. *
  1340. * @param int $recur Is it a recurring invoice ?
  1341. * @param int $status Id status (suspended or not)
  1342. * @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
  1343. * @param integer $alreadypaid Not used for recurring invoices
  1344. * @param int $type Type invoice
  1345. * @return string Label of status
  1346. */
  1347. public function LibStatut($recur, $status, $mode = 0, $alreadypaid = -1, $type = 0)
  1348. {
  1349. // phpcs:enable
  1350. global $langs;
  1351. $langs->load('bills');
  1352. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1353. $statusType = 'status0';
  1354. //print "$recur,$status,$mode,$alreadypaid,$type";
  1355. if ($mode == 0) {
  1356. if ($recur) {
  1357. if ($status == self::STATUS_SUSPENDED) {
  1358. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1359. } else {
  1360. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1361. }
  1362. } else {
  1363. if ($status == self::STATUS_SUSPENDED) {
  1364. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1365. } else {
  1366. $labelStatus = $langs->transnoentitiesnoconv("Draft");
  1367. }
  1368. }
  1369. } elseif ($mode == 1) {
  1370. $prefix = 'Short';
  1371. if ($recur) {
  1372. if ($status == self::STATUS_SUSPENDED) {
  1373. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1374. } else {
  1375. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1376. }
  1377. } else {
  1378. if ($status == self::STATUS_SUSPENDED) {
  1379. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1380. } else {
  1381. $labelStatus = $langs->transnoentitiesnoconv("Draft");
  1382. }
  1383. }
  1384. } elseif ($mode == 2) {
  1385. if ($recur) {
  1386. if ($status == self::STATUS_SUSPENDED) {
  1387. $statusType = 'status6';
  1388. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1389. } else {
  1390. $statusType = 'status4';
  1391. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1392. }
  1393. } else {
  1394. if ($status == self::STATUS_SUSPENDED) {
  1395. $statusType = 'status6';
  1396. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1397. } else {
  1398. $statusType = 'status0';
  1399. $labelStatus = $langs->transnoentitiesnoconv('Draft');
  1400. }
  1401. }
  1402. } elseif ($mode == 3) {
  1403. if ($recur) {
  1404. $prefix = 'Short';
  1405. if ($status == self::STATUS_SUSPENDED) {
  1406. $statusType = 'status6';
  1407. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1408. } else {
  1409. $statusType = 'status4';
  1410. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1411. }
  1412. } else {
  1413. if ($status == self::STATUS_SUSPENDED) {
  1414. $statusType = 'status6';
  1415. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1416. } else {
  1417. $statusType = 'status0';
  1418. $labelStatus = $langs->transnoentitiesnoconv('Draft');
  1419. }
  1420. }
  1421. } elseif ($mode == 4) {
  1422. $prefix = '';
  1423. if ($recur) {
  1424. if ($status == self::STATUS_SUSPENDED) {
  1425. $statusType = 'status6';
  1426. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1427. } else {
  1428. $statusType = 'status4';
  1429. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1430. }
  1431. } else {
  1432. if ($status == self::STATUS_SUSPENDED) {
  1433. $statusType = 'status6';
  1434. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1435. } else {
  1436. $statusType = 'status0';
  1437. $labelStatus = $langs->transnoentitiesnoconv('Draft');
  1438. }
  1439. }
  1440. } elseif ($mode == 5 || $mode == 6) {
  1441. $prefix = '';
  1442. if ($mode == 5) {
  1443. $prefix = 'Short';
  1444. }
  1445. if ($recur) {
  1446. if ($status == self::STATUS_SUSPENDED) {
  1447. $statusType = 'status6';
  1448. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1449. } else {
  1450. $statusType = 'status4';
  1451. $labelStatus = $langs->transnoentitiesnoconv('Active');
  1452. }
  1453. } else {
  1454. if ($status == self::STATUS_SUSPENDED) {
  1455. $statusType = 'status6';
  1456. $labelStatus = $langs->transnoentitiesnoconv('Disabled');
  1457. } else {
  1458. $statusType = 'status0';
  1459. $labelStatus = $langs->transnoentitiesnoconv('Draft');
  1460. }
  1461. }
  1462. }
  1463. $labelStatusShort = $labelStatus;
  1464. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode);
  1465. }
  1466. /**
  1467. * Initialise an instance with random values.
  1468. * Used to build previews or test instances.
  1469. * id must be 0 if object instance is a specimen.
  1470. *
  1471. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  1472. * @return void
  1473. */
  1474. public function initAsSpecimen($option = '')
  1475. {
  1476. global $user, $langs, $conf;
  1477. $now = dol_now();
  1478. $arraynow = dol_getdate($now);
  1479. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  1480. // Load array of products prodids
  1481. $num_prods = 0;
  1482. $prodids = array();
  1483. $sql = "SELECT rowid";
  1484. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  1485. $sql .= " WHERE entity IN (".getEntity('product').")";
  1486. $sql .= $this->db->plimit(100);
  1487. $resql = $this->db->query($sql);
  1488. if ($resql) {
  1489. $num_prods = $this->db->num_rows($resql);
  1490. $i = 0;
  1491. while ($i < $num_prods) {
  1492. $i++;
  1493. $row = $this->db->fetch_row($resql);
  1494. $prodids[$i] = $row[0];
  1495. }
  1496. }
  1497. // Initialize parameters
  1498. $this->id = 0;
  1499. $this->ref = 'SPECIMEN';
  1500. $this->title = 'SPECIMEN';
  1501. $this->specimen = 1;
  1502. $this->socid = 1;
  1503. $this->date = $nownotime;
  1504. $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
  1505. $this->cond_reglement_id = 1;
  1506. $this->cond_reglement_code = 'RECEP';
  1507. $this->date_lim_reglement = $this->calculate_date_lim_reglement();
  1508. $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
  1509. $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
  1510. $this->note_public = 'This is a comment (public)';
  1511. $this->note_private = 'This is a comment (private)';
  1512. $this->note = 'This is a comment (private)';
  1513. $this->fk_incoterms = 0;
  1514. $this->location_incoterms = '';
  1515. if (empty($option) || $option != 'nolines') {
  1516. // Lines
  1517. $nbp = 5;
  1518. $xnbp = 0;
  1519. while ($xnbp < $nbp) {
  1520. $line = new FactureLigne($this->db);
  1521. $line->desc = $langs->trans("Description")." ".$xnbp;
  1522. $line->qty = 1;
  1523. $line->subprice = 100;
  1524. $line->tva_tx = 19.6;
  1525. $line->localtax1_tx = 0;
  1526. $line->localtax2_tx = 0;
  1527. $line->remise_percent = 0;
  1528. if ($xnbp == 1) { // Qty is negative (product line)
  1529. $prodid = mt_rand(1, $num_prods);
  1530. $line->fk_product = $prodids[$prodid];
  1531. $line->qty = -1;
  1532. $line->total_ht = -100;
  1533. $line->total_ttc = -119.6;
  1534. $line->total_tva = -19.6;
  1535. } elseif ($xnbp == 2) { // UP is negative (free line)
  1536. $line->subprice = -100;
  1537. $line->total_ht = -100;
  1538. $line->total_ttc = -119.6;
  1539. $line->total_tva = -19.6;
  1540. $line->remise_percent = 0;
  1541. } elseif ($xnbp == 3) { // Discount is 50% (product line)
  1542. $prodid = mt_rand(1, $num_prods);
  1543. $line->fk_product = $prodids[$prodid];
  1544. $line->total_ht = 50;
  1545. $line->total_ttc = 59.8;
  1546. $line->total_tva = 9.8;
  1547. $line->remise_percent = 50;
  1548. } else // (product line)
  1549. {
  1550. $prodid = mt_rand(1, $num_prods);
  1551. $line->fk_product = $prodids[$prodid];
  1552. $line->total_ht = 100;
  1553. $line->total_ttc = 119.6;
  1554. $line->total_tva = 19.6;
  1555. $line->remise_percent = 00;
  1556. }
  1557. $this->lines[$xnbp] = $line;
  1558. $xnbp++;
  1559. $this->total_ht += $line->total_ht;
  1560. $this->total_tva += $line->total_tva;
  1561. $this->total_ttc += $line->total_ttc;
  1562. }
  1563. $this->revenuestamp = 0;
  1564. // Add a line "offered"
  1565. $line = new FactureLigne($this->db);
  1566. $line->desc = $langs->trans("Description")." (offered line)";
  1567. $line->qty = 1;
  1568. $line->subprice = 100;
  1569. $line->tva_tx = 19.6;
  1570. $line->localtax1_tx = 0;
  1571. $line->localtax2_tx = 0;
  1572. $line->remise_percent = 100;
  1573. $line->total_ht = 0;
  1574. $line->total_ttc = 0; // 90 * 1.196
  1575. $line->total_tva = 0;
  1576. $prodid = mt_rand(1, $num_prods);
  1577. $line->fk_product = $prodids[$prodid];
  1578. $this->lines[$xnbp] = $line;
  1579. $xnbp++;
  1580. }
  1581. $this->usenewprice = 0;
  1582. }
  1583. /**
  1584. * Function used to replace a thirdparty id with another one.
  1585. *
  1586. * @param DoliDB $db Database handler
  1587. * @param int $origin_id Old thirdparty id
  1588. * @param int $dest_id New thirdparty id
  1589. * @return bool
  1590. */
  1591. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  1592. {
  1593. $tables = array(
  1594. 'facture_rec'
  1595. );
  1596. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1597. }
  1598. /**
  1599. * Function used to replace a product id with another one.
  1600. *
  1601. * @param DoliDB $db Database handler
  1602. * @param int $origin_id Old product id
  1603. * @param int $dest_id New product id
  1604. * @return bool
  1605. */
  1606. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  1607. {
  1608. $tables = array(
  1609. 'facturedet_rec'
  1610. );
  1611. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  1612. }
  1613. /**
  1614. * Update frequency and unit
  1615. *
  1616. * @param int $frequency value of frequency
  1617. * @param string $unit unit of frequency (d, m, y)
  1618. * @param int $notrigger Disable the trigger
  1619. * @return int <0 if KO, >0 if OK
  1620. */
  1621. public function setFrequencyAndUnit($frequency, $unit, $notrigger = 0)
  1622. {
  1623. global $user;
  1624. if (!$this->table_element) {
  1625. dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with property table_element not defined", LOG_ERR);
  1626. return -1;
  1627. }
  1628. if (!empty($frequency) && empty($unit)) {
  1629. dol_syslog(get_class($this)."::setFrequencyAndUnit was called on objet with params frequency defined but unit not defined", LOG_ERR);
  1630. return -2;
  1631. }
  1632. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1633. $sql .= ' SET frequency = '.($frequency ? $this->db->escape($frequency) : 'null');
  1634. if (!empty($unit)) {
  1635. $sql .= ', unit_frequency = \''.$this->db->escape($unit).'\'';
  1636. }
  1637. $sql .= " WHERE rowid = ".((int) $this->id);
  1638. dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG);
  1639. if ($this->db->query($sql)) {
  1640. $this->frequency = $frequency;
  1641. if (!empty($unit)) {
  1642. $this->unit_frequency = $unit;
  1643. }
  1644. if (!$notrigger) {
  1645. // Call trigger
  1646. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1647. if ($result < 0) {
  1648. return $result;
  1649. }
  1650. // End call triggers
  1651. }
  1652. return 1;
  1653. } else {
  1654. dol_print_error($this->db);
  1655. return -1;
  1656. }
  1657. }
  1658. /**
  1659. * Update the next date of execution
  1660. *
  1661. * @param datetime $date date of execution
  1662. * @param int $increment_nb_gen_done 0 do nothing more, >0 increment nb_gen_done
  1663. * @param int $notrigger Disable the trigger
  1664. * @return int <0 if KO, >0 if OK
  1665. */
  1666. public function setNextDate($date, $increment_nb_gen_done = 0, $notrigger = 0)
  1667. {
  1668. global $user;
  1669. if (!$this->table_element) {
  1670. dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR);
  1671. return -1;
  1672. }
  1673. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1674. $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null");
  1675. if ($increment_nb_gen_done > 0) {
  1676. $sql .= ', nb_gen_done = nb_gen_done + 1';
  1677. }
  1678. $sql .= " WHERE rowid = ".((int) $this->id);
  1679. dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG);
  1680. if ($this->db->query($sql)) {
  1681. $this->date_when = $date;
  1682. if ($increment_nb_gen_done > 0) {
  1683. $this->nb_gen_done++;
  1684. }
  1685. if (!$notrigger) {
  1686. // Call trigger
  1687. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1688. if ($result < 0) {
  1689. return $result;
  1690. }
  1691. // End call triggers
  1692. }
  1693. return 1;
  1694. } else {
  1695. dol_print_error($this->db);
  1696. return -1;
  1697. }
  1698. }
  1699. /**
  1700. * Update the maximum period
  1701. *
  1702. * @param int $nb number of maximum period
  1703. * @param int $notrigger Disable the trigger
  1704. * @return int <0 if KO, >0 if OK
  1705. */
  1706. public function setMaxPeriod($nb, $notrigger = 0)
  1707. {
  1708. global $user;
  1709. if (!$this->table_element) {
  1710. dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR);
  1711. return -1;
  1712. }
  1713. if (empty($nb)) {
  1714. $nb = 0;
  1715. }
  1716. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1717. $sql .= ' SET nb_gen_max = '.((int) $nb);
  1718. $sql .= " WHERE rowid = ".((int) $this->id);
  1719. dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG);
  1720. if ($this->db->query($sql)) {
  1721. $this->nb_gen_max = $nb;
  1722. if (!$notrigger) {
  1723. // Call trigger
  1724. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1725. if ($result < 0) {
  1726. return $result;
  1727. }
  1728. // End call triggers
  1729. }
  1730. return 1;
  1731. } else {
  1732. dol_print_error($this->db);
  1733. return -1;
  1734. }
  1735. }
  1736. /**
  1737. * Update the auto validate flag of invoice
  1738. *
  1739. * @param int $validate 0 to create in draft, 1 to create and validate invoice
  1740. * @param int $notrigger Disable the trigger
  1741. * @return int <0 if KO, >0 if OK
  1742. */
  1743. public function setAutoValidate($validate, $notrigger = 0)
  1744. {
  1745. global $user;
  1746. if (!$this->table_element) {
  1747. dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR);
  1748. return -1;
  1749. }
  1750. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1751. $sql .= ' SET auto_validate = '.((int) $validate);
  1752. $sql .= " WHERE rowid = ".((int) $this->id);
  1753. dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG);
  1754. if ($this->db->query($sql)) {
  1755. $this->auto_validate = $validate;
  1756. if (!$notrigger) {
  1757. // Call trigger
  1758. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1759. if ($result < 0) {
  1760. return $result;
  1761. }
  1762. // End call triggers
  1763. }
  1764. return 1;
  1765. } else {
  1766. dol_print_error($this->db);
  1767. return -1;
  1768. }
  1769. }
  1770. /**
  1771. * Update the auto generate documents
  1772. *
  1773. * @param int $validate 0 no document, 1 to generate document
  1774. * @param int $notrigger Disable the trigger
  1775. * @return int <0 if KO, >0 if OK
  1776. */
  1777. public function setGeneratePdf($validate, $notrigger = 0)
  1778. {
  1779. global $user;
  1780. if (!$this->table_element) {
  1781. dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR);
  1782. return -1;
  1783. }
  1784. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1785. $sql .= ' SET generate_pdf = '.((int) $validate);
  1786. $sql .= " WHERE rowid = ".((int) $this->id);
  1787. dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG);
  1788. if ($this->db->query($sql)) {
  1789. $this->generate_pdf = $validate;
  1790. if (!$notrigger) {
  1791. // Call trigger
  1792. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1793. if ($result < 0) {
  1794. return $result;
  1795. }
  1796. // End call triggers
  1797. }
  1798. return 1;
  1799. } else {
  1800. dol_print_error($this->db);
  1801. return -1;
  1802. }
  1803. }
  1804. /**
  1805. * Update the model for documents
  1806. *
  1807. * @param string $model model of document generator
  1808. * @param int $notrigger Disable the trigger
  1809. * @return int <0 if KO, >0 if OK
  1810. */
  1811. public function setModelPdf($model, $notrigger = 0)
  1812. {
  1813. global $user;
  1814. if (!$this->table_element) {
  1815. dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR);
  1816. return -1;
  1817. }
  1818. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  1819. $sql .= " SET modelpdf = '".$this->db->escape($model)."'";
  1820. $sql .= " WHERE rowid = ".((int) $this->id);
  1821. dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG);
  1822. if ($this->db->query($sql)) {
  1823. $this->model_pdf = $model;
  1824. if (!$notrigger) {
  1825. // Call trigger
  1826. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  1827. if ($result < 0) {
  1828. return $result;
  1829. }
  1830. // End call triggers
  1831. }
  1832. return 1;
  1833. } else {
  1834. dol_print_error($this->db);
  1835. return -1;
  1836. }
  1837. }
  1838. }
  1839. /**
  1840. * Class to manage invoice lines of templates.
  1841. * Saved into database table llx_facturedet_rec
  1842. */
  1843. class FactureLigneRec extends CommonInvoiceLine
  1844. {
  1845. /**
  1846. * @var string ID to identify managed object
  1847. */
  1848. public $element = 'facturedetrec';
  1849. /**
  1850. * @var string Name of table without prefix where object is stored
  1851. */
  1852. public $table_element = 'facturedet_rec';
  1853. public $fk_product_fournisseur_price;
  1854. public $fk_fournprice; // For backward compatibility
  1855. public $rang;
  1856. public $desc;
  1857. public $description;
  1858. public $fk_product_type; // Use instead product_type
  1859. public $fk_contract_line;
  1860. /**
  1861. * Delete line in database
  1862. *
  1863. * @param User $user Object user
  1864. * @param int $notrigger Disable triggers
  1865. * @return int <0 if KO, >0 if OK
  1866. */
  1867. public function delete(User $user, $notrigger = false)
  1868. {
  1869. $error = 0;
  1870. $this->db->begin();
  1871. if (!$error) {
  1872. if (!$notrigger) {
  1873. // Call triggers
  1874. $result = $this->call_trigger('LINEBILLREC_DELETE', $user);
  1875. if ($result < 0) {
  1876. $error++;
  1877. } // Do also here what you must do to rollback action if trigger fail
  1878. // End call triggers
  1879. }
  1880. }
  1881. if (!$error) {
  1882. $result = $this->deleteExtraFields();
  1883. if ($result < 0) {
  1884. $error++;
  1885. }
  1886. }
  1887. if (!$error) {
  1888. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.((int) $this->id);
  1889. $res = $this->db->query($sql);
  1890. if (!$res) {
  1891. $error++;
  1892. $this->errors[] = $this->db->lasterror();
  1893. }
  1894. }
  1895. // Commit or rollback
  1896. if ($error) {
  1897. $this->db->rollback();
  1898. return -1;
  1899. } else {
  1900. $this->db->commit();
  1901. return 1;
  1902. }
  1903. }
  1904. /**
  1905. * Get line of template invoice
  1906. *
  1907. * @param int $rowid Id of invoice
  1908. * @return int 1 if OK, < 0 if KO
  1909. */
  1910. public function fetch($rowid)
  1911. {
  1912. $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,';
  1913. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
  1914. $sql .= ' l.date_start_fill, l.date_end_fill, l.info_bits, l.total_ht, l.total_tva, l.total_ttc,';
  1915. $sql .= ' l.rang, l.special_code,';
  1916. $sql .= ' l.fk_unit, l.fk_contract_line,';
  1917. $sql .= ' l.import_key, l.fk_multicurrency,';
  1918. $sql .= ' l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  1919. $sql .= ' l.buy_price_ht, l.fk_product_fournisseur_price,';
  1920. $sql .= ' l.fk_user_author, l.fk_user_modif,';
  1921. $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  1922. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
  1923. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  1924. $sql .= ' WHERE l.rowid = '.((int) $rowid);
  1925. $sql .= ' ORDER BY l.rang';
  1926. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  1927. $result = $this->db->query($sql);
  1928. if ($result) {
  1929. $objp = $this->db->fetch_object($result);
  1930. $this->id = $objp->rowid;
  1931. $this->label = $objp->custom_label; // Label line
  1932. $this->desc = $objp->description; // Description line
  1933. $this->description = $objp->description; // Description line
  1934. $this->product_type = $objp->product_type; // Type of line
  1935. $this->ref = $objp->product_ref; // Ref product
  1936. $this->product_ref = $objp->product_ref; // Ref product
  1937. $this->libelle = $objp->product_label; // deprecated
  1938. $this->product_label = $objp->product_label; // Label product
  1939. $this->product_desc = $objp->product_desc; // Description product
  1940. $this->fk_product_type = $objp->fk_product_type; // Type of product
  1941. $this->qty = $objp->qty;
  1942. $this->price = $objp->price;
  1943. $this->subprice = $objp->subprice;
  1944. $this->fk_facture = $objp->fk_facture;
  1945. $this->vat_src_code = $objp->vat_src_code;
  1946. $this->tva_tx = $objp->tva_tx;
  1947. $this->localtax1_tx = $objp->localtax1_tx;
  1948. $this->localtax2_tx = $objp->localtax2_tx;
  1949. $this->localtax1_type = $objp->localtax1_type;
  1950. $this->localtax2_type = $objp->localtax2_type;
  1951. $this->remise_percent = $objp->remise_percent;
  1952. //$this->fk_remise_except = $objp->fk_remise_except;
  1953. $this->fk_product = $objp->fk_product;
  1954. $this->date_start_fill = $objp->date_start_fill;
  1955. $this->date_end_fill = $objp->date_end_fill;
  1956. $this->info_bits = $objp->info_bits;
  1957. $this->total_ht = $objp->total_ht;
  1958. $this->total_tva = $objp->total_tva;
  1959. $this->total_ttc = $objp->total_ttc;
  1960. //$this->code_ventilation = $objp->fk_code_ventilation;
  1961. $this->rang = $objp->rang;
  1962. $this->special_code = $objp->special_code;
  1963. $this->fk_unit = $objp->fk_unit;
  1964. $this->fk_contract_line = $objp->fk_contract_line;
  1965. $this->import_key = $objp->import_key;
  1966. $this->fk_multicurrency = $objp->fk_multicurrency;
  1967. $this->multicurrency_code = $objp->multicurrency_code;
  1968. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  1969. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1970. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1971. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1972. $this->buy_price_ht = $objp->buy_price_ht;
  1973. $this->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
  1974. $this->fk_user_author = $objp->fk_user_author;
  1975. $this->fk_user_modif = $objp->fk_user_modif;
  1976. $this->db->free($result);
  1977. return 1;
  1978. } else {
  1979. $this->error = $this->db->lasterror();
  1980. return -3;
  1981. }
  1982. }
  1983. /**
  1984. * Update a line to invoice_rec.
  1985. *
  1986. * @param User $user User
  1987. * @param int $notrigger No trigger
  1988. * @return int <0 if KO, Id of line if OK
  1989. */
  1990. public function update(User $user, $notrigger = 0)
  1991. {
  1992. global $conf;
  1993. $error = 0;
  1994. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1995. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET";
  1996. $sql .= " fk_facture = ".((int) $this->fk_facture);
  1997. $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  1998. $sql .= ", description='".$this->db->escape($this->desc)."'";
  1999. $sql .= ", price=".price2num($this->price);
  2000. $sql .= ", qty=".price2num($this->qty);
  2001. $sql .= ", tva_tx=".price2num($this->tva_tx);
  2002. $sql .= ", vat_src_code='".$this->db->escape($this->vat_src_code)."'";
  2003. $sql .= ", localtax1_tx=".price2num($this->localtax1_tx);
  2004. $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  2005. $sql .= ", localtax2_tx=".price2num($this->localtax2_tx);
  2006. $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  2007. $sql .= ", fk_product=".($this->fk_product > 0 ? $this->fk_product : "null");
  2008. $sql .= ", product_type=".((int) $this->product_type);
  2009. $sql .= ", remise_percent=".price2num($this->remise_percent);
  2010. $sql .= ", subprice=".price2num($this->subprice);
  2011. $sql .= ", info_bits=".price2num($this->info_bits);
  2012. $sql .= ", date_start_fill=".(int) $this->date_start_fill;
  2013. $sql .= ", date_end_fill=".(int) $this->date_end_fill;
  2014. if (empty($this->skip_update_total)) {
  2015. $sql .= ", total_ht=".price2num($this->total_ht);
  2016. $sql .= ", total_tva=".price2num($this->total_tva);
  2017. $sql .= ", total_localtax1=".price2num($this->total_localtax1);
  2018. $sql .= ", total_localtax2=".price2num($this->total_localtax2);
  2019. $sql .= ", total_ttc=".price2num($this->total_ttc);
  2020. }
  2021. $sql .= ", rang=".((int) $this->rang);
  2022. $sql .= ", special_code=".((int) $this->special_code);
  2023. $sql .= ", fk_unit=".($this->fk_unit ? "'".$this->db->escape($this->fk_unit)."'" : "null");
  2024. $sql .= ", fk_contract_line=".($this->fk_contract_line ? $this->fk_contract_line : "null");
  2025. $sql .= " WHERE rowid = ".((int) $this->id);
  2026. $this->db->begin();
  2027. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  2028. $resql = $this->db->query($sql);
  2029. if ($resql) {
  2030. if (!$error) {
  2031. $result = $this->insertExtraFields();
  2032. if ($result < 0) {
  2033. $error++;
  2034. }
  2035. }
  2036. if (!$error && !$notrigger) {
  2037. // Call trigger
  2038. $result = $this->call_trigger('LINEBILLREC_MODIFY', $user);
  2039. if ($result < 0) {
  2040. $error++;
  2041. }
  2042. // End call triggers
  2043. }
  2044. if ($error) {
  2045. $this->db->rollback();
  2046. return -2;
  2047. } else {
  2048. $this->db->commit();
  2049. return 1;
  2050. }
  2051. } else {
  2052. $this->error = $this->db->lasterror();
  2053. $this->db->rollback();
  2054. return -2;
  2055. }
  2056. }
  2057. }