facture-rec.class.php 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  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'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
  162. 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
  163. 'modelpdf' =>array('type'=>'varchar(255)', 'label'=>'Modelpdf', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  164. 'date_last_gen' =>array('type'=>'varchar(7)', 'label'=>'Last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  165. 'unit_frequency' =>array('type'=>'varchar(2)', 'label'=>'Unit frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  166. 'date_when' =>array('type'=>'datetime', 'label'=>'Date when', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  167. 'date_last_gen' =>array('type'=>'datetime', 'label'=>'Date last gen', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  168. 'nb_gen_done' =>array('type'=>'integer', 'label'=>'Nb gen done', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  169. 'nb_gen_max' =>array('type'=>'integer', 'label'=>'Nb gen max', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  170. 'frequency' =>array('type'=>'integer', 'label'=>'Frequency', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
  171. 'usenewprice' =>array('type'=>'integer', 'label'=>'UseNewPrice', 'enabled'=>1, 'visible'=>0, 'position'=>155),
  172. 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>160, 'isameasure'=>1),
  173. 'auto_validate' =>array('type'=>'integer', 'label'=>'Auto validate', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  174. 'generate_pdf' =>array('type'=>'integer', 'label'=>'Generate pdf', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  175. 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>'$conf->banque->enabled', 'visible'=>-1, 'position'=>175),
  176. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  177. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  178. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency tx', 'enabled'=>1, 'visible'=>-1, 'position'=>190, 'isameasure'=>1),
  179. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ht', 'enabled'=>1, 'visible'=>-1, 'position'=>195, 'isameasure'=>1),
  180. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total tva', 'enabled'=>1, 'visible'=>-1, 'position'=>200, 'isameasure'=>1),
  181. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'Multicurrency total ttc', 'enabled'=>1, 'visible'=>-1, 'position'=>205, 'isameasure'=>1),
  182. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>210),
  183. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>215),
  184. 'suspended' =>array('type'=>'integer', 'label'=>'Suspended', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  185. );
  186. // END MODULEBUILDER PROPERTIES
  187. const STATUS_NOTSUSPENDED = 0;
  188. const STATUS_SUSPENDED = 1;
  189. /**
  190. * Constructor
  191. *
  192. * @param DoliDB $db Database handler
  193. */
  194. public function __construct(DoliDB $db)
  195. {
  196. $this->db = $db;
  197. }
  198. /**
  199. * Create a predefined invoice
  200. *
  201. * @param User $user User object
  202. * @param int $facid Id of source invoice
  203. * @param int $notrigger No trigger
  204. * @return int <0 if KO, id of invoice created if OK
  205. */
  206. public function create($user, $facid, $notrigger = 0)
  207. {
  208. global $conf;
  209. $error = 0;
  210. $now = dol_now();
  211. // Clean parameters
  212. $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated
  213. $this->title = trim($this->title);
  214. $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice;
  215. if (empty($this->suspended)) {
  216. $this->suspended = 0;
  217. }
  218. // No frequency defined then no next date to execution
  219. if (empty($this->frequency)) {
  220. $this->frequency = 0;
  221. $this->date_when = null;
  222. }
  223. $this->frequency = abs($this->frequency);
  224. $this->nb_gen_done = 0;
  225. $this->nb_gen_max = empty($this->nb_gen_max) ? 0 : $this->nb_gen_max;
  226. $this->auto_validate = empty($this->auto_validate) ? 0 : $this->auto_validate;
  227. $this->generate_pdf = empty($this->generate_pdf) ? 0 : $this->generate_pdf;
  228. $this->db->begin();
  229. // Charge facture modele
  230. $facsrc = new Facture($this->db);
  231. $result = $facsrc->fetch($facid);
  232. if ($result > 0) {
  233. // On positionne en mode brouillon la facture
  234. $this->brouillon = 1;
  235. $this->fk_soc = $facsrc->socid;
  236. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_rec (";
  237. $sql .= "titre";
  238. $sql .= ", fk_soc";
  239. $sql .= ", entity";
  240. $sql .= ", datec";
  241. $sql .= ", amount";
  242. $sql .= ", remise";
  243. $sql .= ", note_private";
  244. $sql .= ", note_public";
  245. $sql .= ", modelpdf";
  246. $sql .= ", fk_user_author";
  247. $sql .= ", fk_projet";
  248. $sql .= ", fk_account";
  249. $sql .= ", fk_cond_reglement";
  250. $sql .= ", fk_mode_reglement";
  251. $sql .= ", usenewprice";
  252. $sql .= ", frequency";
  253. $sql .= ", unit_frequency";
  254. $sql .= ", date_when";
  255. $sql .= ", date_last_gen";
  256. $sql .= ", nb_gen_done";
  257. $sql .= ", nb_gen_max";
  258. $sql .= ", auto_validate";
  259. $sql .= ", generate_pdf";
  260. $sql .= ", fk_multicurrency";
  261. $sql .= ", multicurrency_code";
  262. $sql .= ", multicurrency_tx";
  263. $sql .= ", suspended";
  264. $sql .= ") VALUES (";
  265. $sql .= "'".$this->db->escape($this->titre ? $this->titre : $this->title)."'";
  266. $sql .= ", ".((int) $this->fk_soc);
  267. $sql .= ", ".((int) $conf->entity);
  268. $sql .= ", '".$this->db->idate($now)."'";
  269. $sql .= ", ".(!empty($facsrc->total_ttc) ? ((float) $facsrc->total_ttc) : '0');
  270. $sql .= ", ".(!empty($facsrc->remise_absolue) ? ((float) $this->remise_absolue) : '0');
  271. $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
  272. $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
  273. $sql .= ", ".(!empty($this->model_pdf) ? ("'".$this->db->escape($this->model_pdf)."'") : "NULL");
  274. $sql .= ", ".((int) $user->id);
  275. $sql .= ", ".(!empty($this->fk_project) ? ((int) $this->fk_project) : "null");
  276. $sql .= ", ".(!empty($facsrc->fk_account) ? ((int) $facsrc->fk_account) : "null");
  277. $sql .= ", ".($this->cond_reglement_id > 0 ? ((int) $this->cond_reglement_id) : "null");
  278. $sql .= ", ".($this->mode_reglement_id > 0 ? ((int) $this->mode_reglement_id) : "null");
  279. $sql .= ", ".((int) $this->usenewprice);
  280. $sql .= ", ".((int) $this->frequency);
  281. $sql .= ", '".$this->db->escape($this->unit_frequency)."'";
  282. $sql .= ", ".(!empty($this->date_when) ? "'".$this->db->idate($this->date_when)."'" : 'NULL');
  283. $sql .= ", ".(!empty($this->date_last_gen) ? "'".$this->db->idate($this->date_last_gen)."'" : 'NULL');
  284. $sql .= ", ".((int) $this->nb_gen_done);
  285. $sql .= ", ".((int) $this->nb_gen_max);
  286. $sql .= ", ".((int) $this->auto_validate);
  287. $sql .= ", ".((int) $this->generate_pdf);
  288. $sql .= ", ".((int) $facsrc->fk_multicurrency);
  289. $sql .= ", '".$this->db->escape($facsrc->multicurrency_code)."'";
  290. $sql .= ", ".((float) $facsrc->multicurrency_tx);
  291. $sql .= ", ".((int) $this->suspended);
  292. $sql .= ")";
  293. if ($this->db->query($sql)) {
  294. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec");
  295. // Fields used into addline later
  296. $this->fk_multicurrency = $facsrc->fk_multicurrency;
  297. $this->multicurrency_code = $facsrc->multicurrency_code;
  298. $this->multicurrency_tx = $facsrc->multicurrency_tx;
  299. // Add lines
  300. $num = count($facsrc->lines);
  301. for ($i = 0; $i < $num; $i++) {
  302. $tva_tx = $facsrc->lines[$i]->tva_tx;
  303. if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  304. $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')';
  305. }
  306. $default_start_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_START');
  307. $default_end_fill = getDolGlobalInt('INVOICEREC_SET_AUTOFILL_DATE_END');
  308. $result_insert = $this->addline(
  309. $facsrc->lines[$i]->desc,
  310. $facsrc->lines[$i]->subprice,
  311. $facsrc->lines[$i]->qty,
  312. $tva_tx,
  313. $facsrc->lines[$i]->localtax1_tx,
  314. $facsrc->lines[$i]->localtax2_tx,
  315. $facsrc->lines[$i]->fk_product,
  316. $facsrc->lines[$i]->remise_percent,
  317. 'HT',
  318. $facsrc->lines[$i]->info_bits,
  319. '',
  320. 0,
  321. $facsrc->lines[$i]->product_type,
  322. $facsrc->lines[$i]->rang,
  323. $facsrc->lines[$i]->special_code,
  324. $facsrc->lines[$i]->label,
  325. $facsrc->lines[$i]->fk_unit,
  326. $facsrc->lines[$i]->multicurrency_subprice,
  327. $default_start_fill,
  328. $default_end_fill,
  329. null,
  330. $facsrc->lines[$i]->pa_ht
  331. );
  332. if ($result_insert < 0) {
  333. $error++;
  334. } else {
  335. $objectline = new FactureLigneRec($this->db);
  336. $result2 = $objectline->fetch($result_insert);
  337. if ($result2 > 0) {
  338. // Extrafields
  339. if (method_exists($facsrc->lines[$i], 'fetch_optionals')) {
  340. $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->id);
  341. $objectline->array_options = $facsrc->lines[$i]->array_options;
  342. }
  343. $result = $objectline->insertExtraFields();
  344. if ($result < 0) {
  345. $error++;
  346. }
  347. } elseif ($result2 < 0) {
  348. $this->errors[] = $objectline->error;
  349. $error++;
  350. }
  351. }
  352. }
  353. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  354. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  355. }
  356. // Add object linked
  357. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  358. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  359. 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, ...))
  360. foreach ($tmp_origin_id as $origin_id) {
  361. $ret = $this->add_object_linked($origin, $origin_id);
  362. if (!$ret) {
  363. $this->error = $this->db->lasterror();
  364. $error++;
  365. }
  366. }
  367. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  368. {
  369. $origin_id = $tmp_origin_id;
  370. $ret = $this->add_object_linked($origin, $origin_id);
  371. if (!$ret) {
  372. $this->error = $this->db->lasterror();
  373. $error++;
  374. }
  375. }
  376. }
  377. }
  378. if (!$error) {
  379. $result = $this->insertExtraFields();
  380. if ($result < 0) {
  381. $error++;
  382. }
  383. }
  384. if (!$error && !$notrigger) {
  385. // Call trigger
  386. $result = $this->call_trigger('BILLREC_CREATE', $user);
  387. if ($result < 0) {
  388. $this->db->rollback();
  389. return -2;
  390. }
  391. // End call triggers
  392. }
  393. if ($error) {
  394. $this->db->rollback();
  395. return -3;
  396. } else {
  397. $this->db->commit();
  398. return $this->id;
  399. }
  400. } else {
  401. $this->error = $this->db->lasterror();
  402. $this->db->rollback();
  403. return -2;
  404. }
  405. } else {
  406. $this->db->rollback();
  407. return -1;
  408. }
  409. }
  410. /**
  411. * Update a line invoice_rec.
  412. *
  413. * @param User $user User
  414. * @param int $notrigger No trigger
  415. * @return int <0 if KO, Id of line if OK
  416. */
  417. public function update(User $user, $notrigger = 0)
  418. {
  419. $error = 0;
  420. $sql = "UPDATE ".MAIN_DB_PREFIX."facture_rec SET";
  421. $sql .= " entity = ".((int) $this->entity).",";
  422. $sql .= " titre = '".$this->db->escape($this->title)."',";
  423. $sql .= " suspended = ".((int) $this->suspended).",";
  424. $sql .= " fk_soc = ".((int) $this->socid).",";
  425. $sql .= " total_tva = ".((float) $this->total_tva).",";
  426. $sql .= " localtax1 = ".((float) $this->total_localtax1).",";
  427. $sql .= " localtax2 = ".((float) $this->total_localtax2).",";
  428. $sql .= " total_ht = ".((float) $this->total_ht).",";
  429. $sql .= " total_ttc = ".((float) $this->total_ttc).",";
  430. $sql .= " remise_percent = ".((float) $this->remise_percent);
  431. // TODO Add missing fields
  432. $sql .= " WHERE rowid = ".((int) $this->id);
  433. $this->db->begin();
  434. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  435. $resql = $this->db->query($sql);
  436. if ($resql) {
  437. if (!$error) {
  438. $result = $this->insertExtraFields();
  439. if ($result < 0) {
  440. $error++;
  441. }
  442. }
  443. if (!$error && !$notrigger) {
  444. // Call trigger
  445. $result = $this->call_trigger('BILLREC_MODIFY', $user);
  446. if ($result < 0) {
  447. $this->db->rollback();
  448. return -2;
  449. }
  450. // End call triggers
  451. }
  452. $this->db->commit();
  453. return 1;
  454. } else {
  455. $this->error = $this->db->lasterror();
  456. $this->db->rollback();
  457. return -1;
  458. }
  459. }
  460. /**
  461. * Load object and lines
  462. *
  463. * @param int $rowid Id of object to load
  464. * @param string $ref Reference of recurring invoice
  465. * @param string $ref_ext External reference of invoice
  466. * @return int >0 if OK, <0 if KO, 0 if not found
  467. */
  468. public function fetch($rowid, $ref = '', $ref_ext = '')
  469. {
  470. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  471. $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';
  472. $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
  473. $sql .= ', f.date_lim_reglement as dlr';
  474. $sql .= ', f.note_private, f.note_public, f.fk_user_author';
  475. $sql .= ', f.modelpdf as model_pdf';
  476. $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project';
  477. $sql .= ', f.fk_account';
  478. $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';
  479. $sql .= ', f.generate_pdf';
  480. $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  481. $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  482. $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  483. //$sql.= ', el.fk_source';
  484. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as f';
  485. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  486. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  487. //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'";
  488. $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')';
  489. if ($rowid) {
  490. $sql .= ' AND f.rowid = '.((int) $rowid);
  491. } elseif ($ref) {
  492. $sql .= " AND f.titre = '".$this->db->escape($ref)."'";
  493. } else {
  494. $sql .= ' AND f.rowid = 0';
  495. }
  496. /* This field are not used for template invoice
  497. if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  498. */
  499. $result = $this->db->query($sql);
  500. if ($result) {
  501. if ($this->db->num_rows($result)) {
  502. $obj = $this->db->fetch_object($result);
  503. $this->id = $obj->rowid;
  504. $this->entity = $obj->entity;
  505. $this->titre = $obj->title; // deprecated
  506. $this->title = $obj->title;
  507. $this->ref = $obj->title;
  508. $this->suspended = $obj->suspended;
  509. $this->remise_percent = $obj->remise_percent;
  510. $this->remise_absolue = $obj->remise_absolue;
  511. $this->remise = $obj->remise;
  512. $this->total_ht = $obj->total_ht;
  513. $this->total_tva = $obj->total_tva;
  514. $this->total_localtax1 = $obj->localtax1;
  515. $this->total_localtax2 = $obj->localtax2;
  516. $this->total_ttc = $obj->total_ttc;
  517. $this->socid = $obj->fk_soc;
  518. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  519. $this->mode_reglement_id = $obj->fk_mode_reglement;
  520. $this->mode_reglement_code = $obj->mode_reglement_code;
  521. $this->mode_reglement = $obj->mode_reglement_libelle;
  522. $this->cond_reglement_id = $obj->fk_cond_reglement;
  523. $this->cond_reglement_code = $obj->cond_reglement_code;
  524. $this->cond_reglement = $obj->cond_reglement_libelle;
  525. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  526. $this->fk_project = $obj->fk_project;
  527. $this->fk_account = $obj->fk_account;
  528. $this->note_private = $obj->note_private;
  529. $this->note_public = $obj->note_public;
  530. $this->user_author = $obj->fk_user_author;
  531. $this->modelpdf = $obj->model_pdf; // deprecated
  532. $this->model_pdf = $obj->model_pdf;
  533. //$this->special_code = $obj->special_code;
  534. $this->frequency = $obj->frequency;
  535. $this->unit_frequency = $obj->unit_frequency;
  536. $this->date_when = $this->db->jdate($obj->date_when);
  537. $this->date_last_gen = $this->db->jdate($obj->date_last_gen);
  538. $this->nb_gen_done = $obj->nb_gen_done;
  539. $this->nb_gen_max = $obj->nb_gen_max;
  540. $this->usenewprice = $obj->usenewprice;
  541. $this->auto_validate = $obj->auto_validate;
  542. $this->generate_pdf = $obj->generate_pdf;
  543. // Multicurrency
  544. $this->fk_multicurrency = $obj->fk_multicurrency;
  545. $this->multicurrency_code = $obj->multicurrency_code;
  546. $this->multicurrency_tx = $obj->multicurrency_tx;
  547. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  548. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  549. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  550. if ($this->statut == self::STATUS_DRAFT) {
  551. $this->brouillon = 1;
  552. }
  553. // Retrieve all extrafield
  554. // fetch optionals attributes and labels
  555. $this->fetch_optionals();
  556. /*
  557. * Lines
  558. */
  559. $result = $this->fetch_lines();
  560. if ($result < 0) {
  561. $this->error = $this->db->lasterror();
  562. return -3;
  563. }
  564. return 1;
  565. } else {
  566. $this->error = 'Bill with id '.$rowid.' or ref '.$ref.' not found';
  567. dol_syslog('Facture::Fetch Error '.$this->error, LOG_ERR);
  568. return -2;
  569. }
  570. } else {
  571. $this->error = $this->db->error();
  572. return -1;
  573. }
  574. }
  575. /**
  576. * Create an array of invoice lines
  577. *
  578. * @return int >0 if OK, <0 if KO
  579. */
  580. public function getLinesArray()
  581. {
  582. return $this->fetch_lines();
  583. }
  584. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  585. /**
  586. * Get lines of template invoices into this->lines
  587. *
  588. * @return int 1 if OK, < 0 if KO
  589. */
  590. public function fetch_lines()
  591. {
  592. // phpcs:enable
  593. $this->lines = array();
  594. // Retrieve all extrafield for line
  595. // fetch optionals attributes and labels
  596. /*if (!is_object($extrafields)) {
  597. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  598. $extrafields = new ExtraFields($this->db);
  599. }
  600. $extrafields->fetch_name_optionals_label($this->table_element_line, true);
  601. */
  602. dol_syslog('FactureRec::fetch_lines', LOG_DEBUG);
  603. $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, ';
  604. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise, l.remise_percent, l.subprice,';
  605. $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,';
  606. $sql .= ' l.rang, l.special_code,';
  607. $sql .= ' l.fk_unit, l.fk_contract_line,';
  608. $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  609. $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  610. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet_rec as l';
  611. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  612. $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
  613. $sql .= ' ORDER BY l.rang';
  614. $result = $this->db->query($sql);
  615. if ($result) {
  616. $num = $this->db->num_rows($result);
  617. $i = 0;
  618. while ($i < $num) {
  619. $objp = $this->db->fetch_object($result);
  620. $line = new FactureLigneRec($this->db);
  621. $line->id = $objp->rowid;
  622. $line->rowid = $objp->rowid;
  623. $line->desc = $objp->description; // Description line
  624. $line->description = $objp->description; // Description line
  625. $line->ref = $objp->product_ref; // Ref product
  626. $line->product_ref = $objp->product_ref; // Ref product
  627. $line->libelle = $objp->product_label; // deprecated
  628. $line->product_label = $objp->product_label; // Label product
  629. $line->product_desc = $objp->product_desc; // Description product
  630. $line->product_type = $objp->product_type; // Type of line
  631. $line->fk_product_type = $objp->fk_product_type; // Type of product
  632. $line->qty = $objp->qty;
  633. $line->subprice = $objp->subprice;
  634. $line->label = $objp->custom_label; // @deprecated
  635. $line->vat_src_code = $objp->vat_src_code;
  636. $line->tva_tx = $objp->tva_tx;
  637. $line->localtax1_tx = $objp->localtax1_tx;
  638. $line->localtax2_tx = $objp->localtax2_tx;
  639. $line->localtax1_type = $objp->localtax1_type;
  640. $line->localtax2_type = $objp->localtax2_type;
  641. $line->remise_percent = $objp->remise_percent;
  642. //$line->fk_remise_except = $objp->fk_remise_except;
  643. $line->fk_product = $objp->fk_product;
  644. $line->date_start_fill = $objp->date_start_fill;
  645. $line->date_end_fill = $objp->date_end_fill;
  646. $line->info_bits = $objp->info_bits;
  647. $line->total_ht = $objp->total_ht;
  648. $line->total_tva = $objp->total_tva;
  649. $line->total_ttc = $objp->total_ttc;
  650. //$line->code_ventilation = $objp->fk_code_ventilation;
  651. $line->fk_product_fournisseur_price = $objp->fk_product_fournisseur_price;
  652. $line->fk_fournprice = $objp->fk_product_fournisseur_price; // For backward compatibility
  653. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $objp->fk_product_fournisseur_price, $objp->pa_ht);
  654. $line->buyprice = $marginInfos[0];
  655. $line->pa_ht = $marginInfos[0]; // For backward compatibility
  656. $line->marge_tx = $marginInfos[1];
  657. $line->marque_tx = $marginInfos[2];
  658. $line->rang = $objp->rang;
  659. $line->special_code = $objp->special_code;
  660. $line->fk_unit = $objp->fk_unit;
  661. $line->fk_contract_line = $objp->fk_contract_line;
  662. // Ne plus utiliser
  663. $line->price = $objp->price;
  664. $line->remise = $objp->remise;
  665. $line->fetch_optionals();
  666. // Multicurrency
  667. $line->fk_multicurrency = $objp->fk_multicurrency;
  668. $line->multicurrency_code = $objp->multicurrency_code;
  669. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  670. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  671. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  672. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  673. $this->lines[$i] = $line;
  674. $i++;
  675. }
  676. $this->db->free($result);
  677. return 1;
  678. } else {
  679. $this->error = $this->db->lasterror();
  680. return -3;
  681. }
  682. }
  683. /**
  684. * Delete template invoice
  685. *
  686. * @param User $user User that delete.
  687. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  688. * @param int $idwarehouse Id warehouse to use for stock change.
  689. * @return int <0 if KO, >0 if OK
  690. */
  691. public function delete(User $user, $notrigger = 0, $idwarehouse = -1)
  692. {
  693. $rowid = $this->id;
  694. dol_syslog(get_class($this)."::delete rowid=".((int) $rowid), LOG_DEBUG);
  695. $error = 0;
  696. $this->db->begin();
  697. $main = MAIN_DB_PREFIX.'facturedet_rec';
  698. $ef = $main."_extrafields";
  699. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
  700. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".((int) $rowid);
  701. if ($this->db->query($sqlef) && $this->db->query($sql)) {
  702. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".((int) $rowid);
  703. dol_syslog($sql);
  704. if ($this->db->query($sql)) {
  705. // Delete linked object
  706. $res = $this->deleteObjectLinked();
  707. if ($res < 0) {
  708. $error = -3;
  709. }
  710. // Delete extrafields
  711. $res = $this->deleteExtraFields();
  712. if ($res < 0) {
  713. $error = -4;
  714. }
  715. } else {
  716. $this->error = $this->db->lasterror();
  717. $error = -1;
  718. }
  719. } else {
  720. $this->error = $this->db->lasterror();
  721. $error = -2;
  722. }
  723. if (!$error && !$notrigger) {
  724. // Call trigger
  725. $result = $this->call_trigger('BILLREC_DELETE', $user);
  726. if ($result < 0) {
  727. $error++;
  728. }
  729. // End call triggers
  730. }
  731. if (!$error) {
  732. $this->db->commit();
  733. return 1;
  734. } else {
  735. $this->db->rollback();
  736. return $error;
  737. }
  738. }
  739. /**
  740. * Add a line to invoice
  741. *
  742. * @param string $desc Description de la ligne
  743. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  744. * @param double $qty Quantite
  745. * @param double $txtva Taux de tva force, sinon -1
  746. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  747. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  748. * @param int $fk_product Product/Service ID predefined
  749. * @param double $remise_percent Percentage discount of the line
  750. * @param string $price_base_type HT or TTC
  751. * @param int $info_bits VAT npr or not ?
  752. * @param int $fk_remise_except Id remise
  753. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  754. * @param int $type Type of line (0=product, 1=service)
  755. * @param int $rang Position of line
  756. * @param int $special_code Special code
  757. * @param string $label Label of the line
  758. * @param string $fk_unit Unit
  759. * @param double $pu_ht_devise Unit price in currency
  760. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  761. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  762. * @param int $fk_fournprice Supplier price id (to calculate margin) or ''
  763. * @param int $pa_ht Buying price of line (to calculate margin) or ''
  764. * @return int <0 if KO, Id of line if OK
  765. */
  766. 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)
  767. {
  768. global $mysoc;
  769. $facid = $this->id;
  770. 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);
  771. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  772. // Check parameters
  773. if ($type < 0) {
  774. return -1;
  775. }
  776. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  777. // Clean vat code
  778. $reg = array();
  779. $vat_src_code = '';
  780. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  781. $vat_src_code = $reg[1];
  782. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  783. }
  784. if ($this->brouillon) {
  785. // Clean parameters
  786. $remise_percent = price2num($remise_percent);
  787. if (empty($remise_percent)) {
  788. $remise_percent = 0;
  789. }
  790. $qty = price2num($qty);
  791. $pu_ht = price2num($pu_ht);
  792. $pu_ttc = price2num($pu_ttc);
  793. if (!preg_match('/\((.*)\)/', $txtva)) {
  794. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  795. }
  796. $txlocaltax1 = price2num($txlocaltax1);
  797. $txlocaltax2 = price2num($txlocaltax2);
  798. if (empty($txtva)) {
  799. $txtva = 0;
  800. }
  801. if (empty($txlocaltax1)) {
  802. $txlocaltax1 = 0;
  803. }
  804. if (empty($txlocaltax2)) {
  805. $txlocaltax2 = 0;
  806. }
  807. if (empty($info_bits)) {
  808. $info_bits = 0;
  809. }
  810. if ($price_base_type == 'HT') {
  811. $pu = $pu_ht;
  812. } else {
  813. $pu = $pu_ttc;
  814. }
  815. // Calcul du total TTC et de la TVA pour la ligne a partir de
  816. // qty, pu, remise_percent et txtva
  817. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  818. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  819. $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);
  820. $total_ht = $tabprice[0];
  821. $total_tva = $tabprice[1];
  822. $total_ttc = $tabprice[2];
  823. $total_localtax1 = $tabprice[9];
  824. $total_localtax2 = $tabprice[10];
  825. $pu_ht = $tabprice[3];
  826. // MultiCurrency
  827. $multicurrency_total_ht = $tabprice[16];
  828. $multicurrency_total_tva = $tabprice[17];
  829. $multicurrency_total_ttc = $tabprice[18];
  830. $pu_ht_devise = $tabprice[19];
  831. $product_type = $type;
  832. if ($fk_product) {
  833. $product = new Product($this->db);
  834. $result = $product->fetch($fk_product);
  835. $product_type = $product->type;
  836. }
  837. // Rank to use
  838. $ranktouse = $rang;
  839. if ($ranktouse == -1) {
  840. $rangmax = $this->line_max(0);
  841. $ranktouse = $rangmax + 1;
  842. }
  843. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facturedet_rec (";
  844. $sql .= "fk_facture";
  845. $sql .= ", label";
  846. $sql .= ", description";
  847. $sql .= ", price";
  848. $sql .= ", qty";
  849. $sql .= ", tva_tx";
  850. $sql .= ", vat_src_code";
  851. $sql .= ", localtax1_tx";
  852. $sql .= ", localtax1_type";
  853. $sql .= ", localtax2_tx";
  854. $sql .= ", localtax2_type";
  855. $sql .= ", fk_product";
  856. $sql .= ", product_type";
  857. $sql .= ", remise_percent";
  858. $sql .= ", subprice";
  859. $sql .= ", remise";
  860. $sql .= ", total_ht";
  861. $sql .= ", total_tva";
  862. $sql .= ", total_localtax1";
  863. $sql .= ", total_localtax2";
  864. $sql .= ", total_ttc";
  865. $sql .= ", date_start_fill";
  866. $sql .= ", date_end_fill";
  867. $sql .= ", fk_product_fournisseur_price";
  868. $sql .= ", buy_price_ht";
  869. $sql .= ", info_bits";
  870. $sql .= ", rang";
  871. $sql .= ", special_code";
  872. $sql .= ", fk_unit";
  873. $sql .= ', fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  874. $sql .= ") VALUES (";
  875. $sql .= " ".((int) $facid);
  876. $sql .= ", ".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
  877. $sql .= ", '".$this->db->escape($desc)."'";
  878. $sql .= ", ".price2num($pu_ht);
  879. $sql .= ", ".price2num($qty);
  880. $sql .= ", ".price2num($txtva);
  881. $sql .= ", '".$this->db->escape($vat_src_code)."'";
  882. $sql .= ", ".price2num($txlocaltax1);
  883. $sql .= ", '".$this->db->escape(isset($localtaxes_type[0]) ? $localtaxes_type[0] : '')."'";
  884. $sql .= ", ".price2num($txlocaltax2);
  885. $sql .= ", '".$this->db->escape(isset($localtaxes_type[2]) ? $localtaxes_type[2] : '')."'";
  886. $sql .= ", ".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
  887. $sql .= ", ".((int) $product_type);
  888. $sql .= ", ".price2num($remise_percent);
  889. $sql .= ", ".price2num($pu_ht);
  890. $sql .= ", null";
  891. $sql .= ", ".price2num($total_ht);
  892. $sql .= ", ".price2num($total_tva);
  893. $sql .= ", ".price2num($total_localtax1);
  894. $sql .= ", ".price2num($total_localtax2);
  895. $sql .= ", ".price2num($total_ttc);
  896. $sql .= ", ".(int) $date_start_fill;
  897. $sql .= ", ".(int) $date_end_fill;
  898. $sql .= ", ".($fk_fournprice > 0 ? $fk_fournprice : 'null');
  899. $sql .= ", ".($pa_ht ? price2num($pa_ht) : 0);
  900. $sql .= ", ".((int) $info_bits);
  901. $sql .= ", ".((int) $ranktouse);
  902. $sql .= ", ".((int) $special_code);
  903. $sql .= ", ".($fk_unit ? ((int) $fk_unit) : "null");
  904. $sql .= ", ".(int) $this->fk_multicurrency;
  905. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  906. $sql .= ", ".price2num($pu_ht_devise, 'CU');
  907. $sql .= ", ".price2num($multicurrency_total_ht, 'CT');
  908. $sql .= ", ".price2num($multicurrency_total_tva, 'CT');
  909. $sql .= ", ".price2num($multicurrency_total_ttc, 'CT');
  910. $sql .= ")";
  911. dol_syslog(get_class($this)."::addline", LOG_DEBUG);
  912. if ($this->db->query($sql)) {
  913. $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec");
  914. $this->id = $facid;
  915. $this->update_price();
  916. return $lineId;
  917. } else {
  918. $this->error = $this->db->lasterror();
  919. return -1;
  920. }
  921. }
  922. }
  923. /**
  924. * Update a line to invoice
  925. *
  926. * @param int $rowid Id of line to update
  927. * @param string $desc Description de la ligne
  928. * @param double $pu_ht Prix unitaire HT (> 0 even for credit note)
  929. * @param double $qty Quantite
  930. * @param double $txtva Taux de tva force, sinon -1
  931. * @param double $txlocaltax1 Local tax 1 rate (deprecated)
  932. * @param double $txlocaltax2 Local tax 2 rate (deprecated)
  933. * @param int $fk_product Product/Service ID predefined
  934. * @param double $remise_percent Percentage discount of the line
  935. * @param string $price_base_type HT or TTC
  936. * @param int $info_bits Bits of type of lines
  937. * @param int $fk_remise_except Id remise
  938. * @param double $pu_ttc Prix unitaire TTC (> 0 even for credit note)
  939. * @param int $type Type of line (0=product, 1=service)
  940. * @param int $rang Position of line
  941. * @param int $special_code Special code
  942. * @param string $label Label of the line
  943. * @param string $fk_unit Unit
  944. * @param double $pu_ht_devise Unit price in currency
  945. * @param int $notrigger disable line update trigger
  946. * @param int $date_start_fill 1=Flag to fill start date when generating invoice
  947. * @param int $date_end_fill 1=Flag to fill end date when generating invoice
  948. * @param int $fk_fournprice Id of origin supplier price
  949. * @param int $pa_ht Price (without tax) of product for margin calculation
  950. * @return int <0 if KO, Id of line if OK
  951. */
  952. 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)
  953. {
  954. global $mysoc;
  955. $facid = $this->id;
  956. 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);
  957. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  958. // Clean parameters
  959. if (empty($remise_percent)) {
  960. $remise_percent = 0;
  961. }
  962. // Check parameters
  963. if ($type < 0) {
  964. return -1;
  965. }
  966. if ($this->brouillon) {
  967. // Clean parameters
  968. $remise_percent = price2num($remise_percent);
  969. $qty = price2num($qty);
  970. if (empty($info_bits)) {
  971. $info_bits = 0;
  972. }
  973. $pu_ht = price2num($pu_ht);
  974. $pu_ttc = price2num($pu_ttc);
  975. $pu_ht_devise = price2num($pu_ht_devise);
  976. if (!preg_match('/\((.*)\)/', $txtva)) {
  977. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  978. }
  979. $txlocaltax1 = price2num($txlocaltax1);
  980. $txlocaltax2 = price2num($txlocaltax2);
  981. if (empty($txlocaltax1)) {
  982. $txlocaltax1 = 0;
  983. }
  984. if (empty($txlocaltax2)) {
  985. $txlocaltax2 = 0;
  986. }
  987. if (empty($this->multicurrency_subprice)) {
  988. $this->multicurrency_subprice = 0;
  989. }
  990. if (empty($this->multicurrency_total_ht)) {
  991. $this->multicurrency_total_ht = 0;
  992. }
  993. if (empty($this->multicurrency_total_tva)) {
  994. $this->multicurrency_total_tva = 0;
  995. }
  996. if (empty($this->multicurrency_total_ttc)) {
  997. $this->multicurrency_total_ttc = 0;
  998. }
  999. if ($price_base_type == 'HT') {
  1000. $pu = $pu_ht;
  1001. } else {
  1002. $pu = $pu_ttc;
  1003. }
  1004. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  1005. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1006. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1007. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  1008. // Clean vat code
  1009. $vat_src_code = '';
  1010. $reg = array();
  1011. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  1012. $vat_src_code = $reg[1];
  1013. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  1014. }
  1015. $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);
  1016. $total_ht = $tabprice[0];
  1017. $total_tva = $tabprice[1];
  1018. $total_ttc = $tabprice[2];
  1019. $total_localtax1 = $tabprice[9];
  1020. $total_localtax2 = $tabprice[10];
  1021. $pu_ht = $tabprice[3];
  1022. $pu_tva = $tabprice[4];
  1023. $pu_ttc = $tabprice[5];
  1024. // MultiCurrency
  1025. $multicurrency_total_ht = $tabprice[16];
  1026. $multicurrency_total_tva = $tabprice[17];
  1027. $multicurrency_total_ttc = $tabprice[18];
  1028. $pu_ht_devise = $tabprice[19];
  1029. $product_type = $type;
  1030. if ($fk_product) {
  1031. $product = new Product($this->db);
  1032. $result = $product->fetch($fk_product);
  1033. $product_type = $product->type;
  1034. }
  1035. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet_rec SET ";
  1036. $sql .= "fk_facture = ".((int) $facid);
  1037. $sql .= ", label=".(!empty($label) ? "'".$this->db->escape($label)."'" : "null");
  1038. $sql .= ", description='".$this->db->escape($desc)."'";
  1039. $sql .= ", price=".price2num($pu_ht);
  1040. $sql .= ", qty=".price2num($qty);
  1041. $sql .= ", tva_tx=".price2num($txtva);
  1042. $sql .= ", vat_src_code='".$this->db->escape($vat_src_code)."'";
  1043. $sql .= ", localtax1_tx=".((float) $txlocaltax1);
  1044. $sql .= ", localtax1_type='".$this->db->escape($localtaxes_type[0])."'";
  1045. $sql .= ", localtax2_tx=".((float) $txlocaltax2);
  1046. $sql .= ", localtax2_type='".$this->db->escape($localtaxes_type[2])."'";
  1047. $sql .= ", fk_product=".(!empty($fk_product) ? "'".$this->db->escape($fk_product)."'" : "null");
  1048. $sql .= ", product_type=".((int) $product_type);
  1049. $sql .= ", remise_percent='".price2num($remise_percent)."'";
  1050. $sql .= ", subprice='".price2num($pu_ht)."'";
  1051. $sql .= ", total_ht='".price2num($total_ht)."'";
  1052. $sql .= ", total_tva='".price2num($total_tva)."'";
  1053. $sql .= ", total_localtax1='".price2num($total_localtax1)."'";
  1054. $sql .= ", total_localtax2='".price2num($total_localtax2)."'";
  1055. $sql .= ", total_ttc='".price2num($total_ttc)."'";
  1056. $sql .= ", date_start_fill=".((int) $date_start_fill);
  1057. $sql .= ", date_end_fill=".((int) $date_end_fill);
  1058. $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : 'null');
  1059. $sql .= ", buy_price_ht=".($pa_ht ? price2num($pa_ht) : 0);
  1060. $sql .= ", info_bits=".((int) $info_bits);
  1061. $sql .= ", rang=".((int) $rang);
  1062. $sql .= ", special_code=".((int) $special_code);
  1063. $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
  1064. $sql .= ', multicurrency_subprice = '.price2num($pu_ht_devise);
  1065. $sql .= ', multicurrency_total_ht = '.price2num($multicurrency_total_ht);
  1066. $sql .= ', multicurrency_total_tva = '.price2num($multicurrency_total_tva);
  1067. $sql .= ', multicurrency_total_ttc = '.price2num($multicurrency_total_ttc);
  1068. $sql .= " WHERE rowid = ".((int) $rowid);
  1069. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  1070. if ($this->db->query($sql)) {
  1071. $this->id = $facid;
  1072. $this->update_price();
  1073. return 1;
  1074. } else {
  1075. $this->error = $this->db->lasterror();
  1076. return -1;
  1077. }
  1078. }
  1079. }
  1080. /**
  1081. * Return the next date of
  1082. *
  1083. * @return int|false false if KO, timestamp if OK
  1084. */
  1085. public function getNextDate()
  1086. {
  1087. if (empty($this->date_when)) {
  1088. return false;
  1089. }
  1090. return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency);
  1091. }
  1092. /**
  1093. * Return if maximum number of generation is reached
  1094. *
  1095. * @return boolean False by default, True if maximum number of generation is reached
  1096. */
  1097. public function isMaxNbGenReached()
  1098. {
  1099. $ret = false;
  1100. if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) {
  1101. $ret = true;
  1102. }
  1103. return $ret;
  1104. }
  1105. /**
  1106. * Format string to output with by striking the string if max number of generation was reached
  1107. *
  1108. * @param string $ret Default value to output
  1109. * @return boolean False by default, True if maximum number of generation is reached
  1110. */
  1111. public function strikeIfMaxNbGenReached($ret)
  1112. {
  1113. // Special case to strike the date
  1114. return ($this->isMaxNbGenReached() ? '<strike>' : '').$ret.($this->isMaxNbGenReached() ? '</strike>' : '');
  1115. }
  1116. /**
  1117. * Create all recurrents invoices (for all entities if multicompany is used).
  1118. * A result may also be provided into this->output.
  1119. *
  1120. * WARNING: This method change temporarly context $conf->entity to be in correct context for each recurring invoice found.
  1121. *
  1122. * @param int $restrictioninvoiceid 0=All qualified template invoices found. > 0 = restrict action on invoice ID
  1123. * @param int $forcevalidation 1=Force validation of invoice whatever is template auto_validate flag.
  1124. * @param int $notrigger Disable the trigger
  1125. * @return int 0 if OK, < 0 if KO (this function is used also by cron so only 0 is OK)
  1126. */
  1127. public function createRecurringInvoices($restrictioninvoiceid = 0, $forcevalidation = 0, $notrigger = 0)
  1128. {
  1129. global $conf, $langs, $db, $user, $hookmanager;
  1130. $error = 0;
  1131. $nb_create = 0;
  1132. // Load translation files required by the page
  1133. $langs->loadLangs(array("main", "bills"));
  1134. $now = dol_now();
  1135. $tmparray = dol_getdate($now);
  1136. $today = dol_mktime(23, 59, 59, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); // Today is last second of current day
  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. }