fournisseur.facture-rec.class.php 85 KB

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