fournisseur.facture-rec.class.php 84 KB

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