facture-rec.class.php 85 KB

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