contrat.class.php 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417
  1. <?php
  2. /* Copyright (C) 2003 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Destailleur Laurent <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2008 Raphael Bertrand <raphael.bertrand@resultic.fr>
  7. * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. * Copyright (C) 2015-2018 Ferran Marcet <fmarcet@2byte.es>
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 3 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  27. */
  28. /**
  29. * \file htdocs/contrat/class/contrat.class.php
  30. * \ingroup contrat
  31. * \brief File of class to manage contracts
  32. */
  33. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  34. require_once DOL_DOCUMENT_ROOT."/core/class/commonobjectline.class.php";
  35. require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  36. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  37. /**
  38. * Class to manage contracts
  39. */
  40. class Contrat extends CommonObject
  41. {
  42. /**
  43. * @var string ID to identify managed object
  44. */
  45. public $element = 'contrat';
  46. /**
  47. * @var string Name of table without prefix where object is stored
  48. */
  49. public $table_element = 'contrat';
  50. /**
  51. * @var string Name of subtable line
  52. */
  53. public $table_element_line = 'contratdet';
  54. /**
  55. * @var string Fieldname with ID of parent key if this field has a parent
  56. */
  57. public $fk_element = 'fk_contrat';
  58. /**
  59. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  60. */
  61. public $picto = 'contract';
  62. /**
  63. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  64. * @var int
  65. */
  66. public $ismultientitymanaged = 1;
  67. /**
  68. * @var int Does object support extrafields ? 0=No, 1=Yes
  69. */
  70. public $isextrafieldmanaged = 1;
  71. /**
  72. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  73. * @var integer
  74. */
  75. public $restrictiononfksoc = 1;
  76. /**
  77. * {@inheritdoc}
  78. */
  79. protected $table_ref_field = 'ref';
  80. /**
  81. * Customer reference of the contract
  82. * @var string
  83. */
  84. public $ref_customer;
  85. /**
  86. * Supplier reference of the contract
  87. * @var string
  88. */
  89. public $ref_supplier;
  90. /**
  91. * Entity of the contract
  92. * @var int
  93. */
  94. public $entity;
  95. /**
  96. * Client id linked to the contract
  97. * @var int
  98. */
  99. public $socid;
  100. public $societe; // Objet societe
  101. /**
  102. * Status of the contract
  103. * @var int
  104. */
  105. public $statut = 0; // 0=Draft,
  106. public $product;
  107. /**
  108. * @var int Id of user author of the contract
  109. */
  110. public $fk_user_author;
  111. /**
  112. * TODO: Which is the correct one?
  113. * Author of the contract
  114. * @var int
  115. */
  116. public $user_author_id;
  117. /**
  118. * @var User Object user that create the contract. Set by the info method.
  119. */
  120. public $user_creation;
  121. /**
  122. * @var User Object user that close the contract. Set by the info method.
  123. */
  124. public $user_cloture;
  125. /**
  126. * @var integer|string Date of creation
  127. */
  128. public $date_creation;
  129. /**
  130. * @var integer|string Date of last modification. Not filled until you call ->info()
  131. */
  132. public $date_modification;
  133. /**
  134. * @var integer|string Date of validation
  135. */
  136. public $date_validation;
  137. /**
  138. * @var integer|string Date when contract was signed
  139. */
  140. public $date_contrat;
  141. public $commercial_signature_id;
  142. public $commercial_suivi_id;
  143. /**
  144. * @deprecated Use fk_project instead
  145. * @see $fk_project
  146. */
  147. public $fk_projet;
  148. public $extraparams = array();
  149. /**
  150. * @var ContratLigne[] Contract lines
  151. */
  152. public $lines = array();
  153. public $nbofservices;
  154. public $nbofserviceswait;
  155. public $nbofservicesopened;
  156. public $nbofservicesexpired;
  157. //public $lower_planned_end_date;
  158. //public $higher_planner_end_date;
  159. /**
  160. * Maps ContratLigne IDs to $this->lines indexes
  161. * @var int[]
  162. */
  163. protected $lines_id_index_mapper = array();
  164. /**
  165. * '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')
  166. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  167. * 'label' the translation key.
  168. * 'enabled' is a condition when the field must be managed.
  169. * 'position' is the sort order of field.
  170. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  171. * '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)
  172. * 'noteditable' says if field is not editable (1 or 0)
  173. * '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.
  174. * 'index' if we want an index in database.
  175. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  176. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  177. * '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).
  178. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  179. * 'help' is a string visible as a tooltip on field
  180. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  181. * '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.
  182. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  183. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  184. *
  185. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  186. */
  187. // BEGIN MODULEBUILDER PROPERTIES
  188. /**
  189. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  190. */
  191. public $fields = array(
  192. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  193. 'ref' =>array('type'=>'varchar(50)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'showoncombobox'=>1, 'position'=>15),
  194. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>20),
  195. 'ref_supplier' =>array('type'=>'varchar(50)', 'label'=>'Ref supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>25),
  196. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>30, 'index'=>1),
  197. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
  198. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  199. 'date_contrat' =>array('type'=>'datetime', 'label'=>'Date contrat', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  200. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>70),
  201. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk projet', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  202. 'fk_commercial_signature' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk commercial signature', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  203. 'fk_commercial_suivi' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk commercial suivi', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  204. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>90),
  205. 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>105),
  206. 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>110),
  207. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>115),
  208. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>120),
  209. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  210. 'ref_customer' =>array('type'=>'varchar(50)', 'label'=>'Ref customer', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  211. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>135),
  212. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'Last main doc', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  213. 'statut' =>array('type'=>'smallint(6)', 'label'=>'Statut', 'enabled'=>1, 'visible'=>-1, 'position'=>500, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed'))
  214. );
  215. // END MODULEBUILDER PROPERTIES
  216. const STATUS_DRAFT = 0;
  217. const STATUS_VALIDATED = 1;
  218. const STATUS_CLOSED = 2;
  219. /**
  220. * Constructor
  221. *
  222. * @param DoliDB $db Database handler
  223. */
  224. public function __construct($db)
  225. {
  226. $this->db = $db;
  227. }
  228. /**
  229. * Return next contract ref
  230. *
  231. * @param Societe $soc Thirdparty object
  232. * @return string free reference for contract
  233. */
  234. public function getNextNumRef($soc)
  235. {
  236. global $db, $langs, $conf;
  237. $langs->load("contracts");
  238. if (!empty($conf->global->CONTRACT_ADDON)) {
  239. $mybool = false;
  240. $file = $conf->global->CONTRACT_ADDON.".php";
  241. $classname = $conf->global->CONTRACT_ADDON;
  242. // Include file with class
  243. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  244. foreach ($dirmodels as $reldir) {
  245. $dir = dol_buildpath($reldir."core/modules/contract/");
  246. // Load file with numbering class (if found)
  247. $mybool |= @include_once $dir.$file;
  248. }
  249. if (!$mybool) {
  250. dol_print_error('', "Failed to include file ".$file);
  251. return '';
  252. }
  253. $obj = new $classname();
  254. $numref = $obj->getNextValue($soc, $this);
  255. if ($numref != "") {
  256. return $numref;
  257. } else {
  258. $this->error = $obj->error;
  259. dol_print_error($db, get_class($this)."::getNextValue ".$obj->error);
  260. return "";
  261. }
  262. } else {
  263. $langs->load("errors");
  264. print $langs->trans("Error")." ".$langs->trans("ErrorModuleSetupNotComplete", $langs->transnoentitiesnoconv("Contract"));
  265. return "";
  266. }
  267. }
  268. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  269. /**
  270. * Activate a contract line
  271. *
  272. * @param User $user Objet User who activate contract
  273. * @param int $line_id Id of line to activate
  274. * @param int $date Opening date
  275. * @param int|string $date_end Expected end date
  276. * @param string $comment A comment typed by user
  277. * @return int <0 if KO, >0 if OK
  278. */
  279. public function active_line($user, $line_id, $date, $date_end = '', $comment = '')
  280. {
  281. // phpcs:enable
  282. $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment);
  283. if ($result < 0) {
  284. $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
  285. $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
  286. }
  287. return $result;
  288. }
  289. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  290. /**
  291. * Close a contract line
  292. *
  293. * @param User $user Objet User who close contract
  294. * @param int $line_id Id of line to close
  295. * @param int $date_end End date
  296. * @param string $comment A comment typed by user
  297. * @return int <0 if KO, >0 if OK
  298. */
  299. public function close_line($user, $line_id, $date_end, $comment = '')
  300. {
  301. // phpcs:enable
  302. $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment);
  303. if ($result < 0) {
  304. $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error;
  305. $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors;
  306. }
  307. return $result;
  308. }
  309. /**
  310. * Open all lines of a contract
  311. *
  312. * @param User $user Object User making action
  313. * @param int|string $date_start Date start (now if empty)
  314. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  315. * @param string $comment Comment
  316. * @return int <0 if KO, >0 if OK
  317. * @see ()
  318. */
  319. public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '')
  320. {
  321. if (empty($date_start)) {
  322. $date_start = dol_now();
  323. }
  324. $this->db->begin();
  325. $error = 0;
  326. // Load lines
  327. $this->fetch_lines();
  328. foreach ($this->lines as $contratline) {
  329. // Open lines not already open
  330. if ($contratline->statut != ContratLigne::STATUS_OPEN) {
  331. $contratline->context = $this->context;
  332. $result = $contratline->active_line($user, $date_start, -1, $comment); // This call trigger LINECONTRACT_ACTIVATE
  333. if ($result < 0) {
  334. $error++;
  335. $this->error = $contratline->error;
  336. $this->errors = $contratline->errors;
  337. break;
  338. }
  339. }
  340. }
  341. if (!$error && $this->statut == 0) {
  342. $result = $this->validate($user, '', $notrigger);
  343. if ($result < 0) {
  344. $error++;
  345. }
  346. }
  347. if (!$error) {
  348. $this->db->commit();
  349. return 1;
  350. } else {
  351. $this->db->rollback();
  352. return -1;
  353. }
  354. }
  355. /**
  356. * Close all lines of a contract
  357. *
  358. * @param User $user Object User making action
  359. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  360. * @param string $comment Comment
  361. * @return int <0 if KO, >0 if OK
  362. * @see activateAll()
  363. */
  364. public function closeAll(User $user, $notrigger = 0, $comment = '')
  365. {
  366. $this->db->begin();
  367. // Load lines
  368. $this->fetch_lines();
  369. $now = dol_now();
  370. $error = 0;
  371. foreach ($this->lines as $contratline) {
  372. // Close lines not already closed
  373. if ($contratline->statut != ContratLigne::STATUS_CLOSED) {
  374. $contratline->date_end_real = $now;
  375. $contratline->date_cloture = $now; // For backward compatibility
  376. $contratline->fk_user_cloture = $user->id;
  377. $contratline->statut = ContratLigne::STATUS_CLOSED;
  378. $result = $contratline->close_line($user, $now, $comment, $notrigger);
  379. if ($result < 0) {
  380. $error++;
  381. $this->error = $contratline->error;
  382. $this->errors = $contratline->errors;
  383. break;
  384. }
  385. }
  386. }
  387. if (!$error && $this->statut == 0) {
  388. $result = $this->validate($user, '', $notrigger);
  389. if ($result < 0) {
  390. $error++;
  391. }
  392. }
  393. if (!$error) {
  394. $this->db->commit();
  395. return 1;
  396. } else {
  397. $this->db->rollback();
  398. return -1;
  399. }
  400. }
  401. /**
  402. * Validate a contract
  403. *
  404. * @param User $user Objet User
  405. * @param string $force_number Reference to force on contract (not implemented yet)
  406. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  407. * @return int <0 if KO, >0 if OK
  408. */
  409. public function validate(User $user, $force_number = '', $notrigger = 0)
  410. {
  411. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  412. global $langs, $conf;
  413. $now = dol_now();
  414. $error = 0;
  415. dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number);
  416. $this->db->begin();
  417. $this->fetch_thirdparty();
  418. // A contract is validated so we can move thirdparty to status customer
  419. if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) {
  420. $result = $this->thirdparty->set_as_client();
  421. }
  422. // Define new ref
  423. if ($force_number) {
  424. $num = $force_number;
  425. } elseif (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  426. $num = $this->getNextNumRef($this->thirdparty);
  427. } else {
  428. $num = $this->ref;
  429. }
  430. $this->newref = dol_sanitizeFileName($num);
  431. if ($num) {
  432. $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1";
  433. //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'";
  434. $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 0";
  435. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  436. $resql = $this->db->query($sql);
  437. if (!$resql) {
  438. dol_print_error($this->db);
  439. $error++;
  440. $this->error = $this->db->lasterror();
  441. }
  442. // Trigger calls
  443. if (!$error && !$notrigger) {
  444. // Call trigger
  445. $result = $this->call_trigger('CONTRACT_VALIDATE', $user);
  446. if ($result < 0) {
  447. $error++;
  448. }
  449. // End call triggers
  450. }
  451. if (!$error) {
  452. $this->oldref = $this->ref;
  453. // Rename directory if dir was a temporary ref
  454. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  455. // Now we rename also files into index
  456. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'contract/".$this->db->escape($this->newref)."'";
  457. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  458. $resql = $this->db->query($sql);
  459. if (!$resql) {
  460. $error++; $this->error = $this->db->lasterror();
  461. }
  462. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  463. $oldref = dol_sanitizeFileName($this->ref);
  464. $newref = dol_sanitizeFileName($num);
  465. $dirsource = $conf->contract->dir_output.'/'.$oldref;
  466. $dirdest = $conf->contract->dir_output.'/'.$newref;
  467. if (!$error && file_exists($dirsource)) {
  468. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  469. if (@rename($dirsource, $dirdest)) {
  470. dol_syslog("Rename ok");
  471. // Rename docs starting with $oldref with $newref
  472. $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  473. foreach ($listoffiles as $fileentry) {
  474. $dirsource = $fileentry['name'];
  475. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  476. $dirsource = $fileentry['path'].'/'.$dirsource;
  477. $dirdest = $fileentry['path'].'/'.$dirdest;
  478. @rename($dirsource, $dirdest);
  479. }
  480. }
  481. }
  482. }
  483. }
  484. // Set new ref and define current statut
  485. if (!$error) {
  486. $this->ref = $num;
  487. $this->statut = 1;
  488. $this->brouillon = 0;
  489. $this->date_validation = $now;
  490. }
  491. } else {
  492. $error++;
  493. }
  494. if (!$error) {
  495. $this->db->commit();
  496. return 1;
  497. } else {
  498. $this->db->rollback();
  499. return -1;
  500. }
  501. }
  502. /**
  503. * Unvalidate a contract
  504. *
  505. * @param User $user Object User
  506. * @param int $notrigger 1=Does not execute triggers, 0=execute triggers
  507. * @return int <0 if KO, >0 if OK
  508. */
  509. public function reopen($user, $notrigger = 0)
  510. {
  511. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  512. global $langs, $conf;
  513. $now = dol_now();
  514. $error = 0;
  515. dol_syslog(get_class($this).'::reopen user='.$user->id);
  516. $this->db->begin();
  517. $this->fetch_thirdparty();
  518. $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET statut = 0";
  519. //$sql.= ", fk_user_valid = null, date_valid = null";
  520. $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = 1";
  521. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  522. $resql = $this->db->query($sql);
  523. if (!$resql) {
  524. dol_print_error($this->db);
  525. $error++;
  526. $this->error = $this->db->lasterror();
  527. }
  528. // Trigger calls
  529. if (!$error && !$notrigger) {
  530. // Call trigger
  531. $result = $this->call_trigger('CONTRACT_REOPEN', $user);
  532. if ($result < 0) {
  533. $error++;
  534. }
  535. // End call triggers
  536. }
  537. // Set new ref and define current status
  538. if (!$error) {
  539. $this->statut = 0;
  540. $this->brouillon = 1;
  541. $this->date_validation = $now;
  542. }
  543. if (!$error) {
  544. $this->db->commit();
  545. return 1;
  546. } else {
  547. $this->db->rollback();
  548. return -1;
  549. }
  550. }
  551. /**
  552. * Load a contract from database
  553. *
  554. * @param int $id Id of contract to load
  555. * @param string $ref Ref
  556. * @param string $ref_customer Customer ref
  557. * @param string $ref_supplier Supplier ref
  558. * @return int <0 if KO, 0 if not found or if two records found for same ref, Id of contract if OK
  559. */
  560. public function fetch($id, $ref = '', $ref_customer = '', $ref_supplier = '')
  561. {
  562. $sql = "SELECT rowid, statut, ref, fk_soc,";
  563. $sql .= " ref_supplier, ref_customer,";
  564. $sql .= " ref_ext,";
  565. $sql .= " entity,";
  566. $sql .= " date_contrat as datecontrat,";
  567. $sql .= " fk_user_author,";
  568. $sql .= " fk_projet as fk_project,";
  569. $sql .= " fk_commercial_signature, fk_commercial_suivi,";
  570. $sql .= " note_private, note_public, model_pdf, extraparams";
  571. $sql .= " FROM ".MAIN_DB_PREFIX."contrat";
  572. if (!$id) {
  573. $sql .= " WHERE entity IN (".getEntity('contract').")";
  574. } else {
  575. $sql .= " WHERE rowid=".(int) $id;
  576. }
  577. if ($ref_customer) {
  578. $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'";
  579. }
  580. if ($ref_supplier) {
  581. $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'";
  582. }
  583. if ($ref) {
  584. $sql .= " AND ref='".$this->db->escape($ref)."'";
  585. }
  586. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  587. $resql = $this->db->query($sql);
  588. if ($resql) {
  589. $num = $this->db->num_rows($resql);
  590. if ($num > 1) {
  591. $this->error = 'Fetch found several records.';
  592. dol_syslog($this->error, LOG_ERR);
  593. $result = -2;
  594. } elseif ($num) { // $num = 1
  595. $obj = $this->db->fetch_object($resql);
  596. if ($obj) {
  597. $this->id = $obj->rowid;
  598. $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref;
  599. $this->ref_customer = $obj->ref_customer;
  600. $this->ref_supplier = $obj->ref_supplier;
  601. $this->ref_ext = $obj->ref_ext;
  602. $this->entity = $obj->entity;
  603. $this->statut = $obj->statut;
  604. $this->date_contrat = $this->db->jdate($obj->datecontrat);
  605. $this->date_creation = $this->db->jdate($obj->datecontrat);
  606. $this->user_author_id = $obj->fk_user_author;
  607. $this->commercial_signature_id = $obj->fk_commercial_signature;
  608. $this->commercial_suivi_id = $obj->fk_commercial_suivi;
  609. $this->note_private = $obj->note_private;
  610. $this->note_public = $obj->note_public;
  611. $this->model_pdf = $obj->model_pdf;
  612. $this->modelpdf = $obj->model_pdf; // deprecated
  613. $this->fk_projet = $obj->fk_project; // deprecated
  614. $this->fk_project = $obj->fk_project;
  615. $this->socid = $obj->fk_soc;
  616. $this->fk_soc = $obj->fk_soc;
  617. $this->extraparams = (array) json_decode($obj->extraparams, true);
  618. $this->db->free($resql);
  619. // Retrieve all extrafields
  620. // fetch optionals attributes and labels
  621. $this->fetch_optionals();
  622. // Lines
  623. $result = $this->fetch_lines();
  624. if ($result < 0) {
  625. $this->error = $this->db->lasterror();
  626. return -3;
  627. }
  628. return $this->id;
  629. }
  630. } else {
  631. dol_syslog(get_class($this)."::fetch Contract not found");
  632. $this->error = "Contract not found";
  633. return 0;
  634. }
  635. } else {
  636. dol_syslog(get_class($this)."::fetch Error searching contract");
  637. $this->error = $this->db->error();
  638. return -1;
  639. }
  640. }
  641. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  642. /**
  643. * Load lines array into this->lines.
  644. * This set also nbofserviceswait, nbofservicesopened, nbofservicesexpired and nbofservicesclosed
  645. *
  646. * @param int $only_product Return only physical products
  647. * @param int $loadalsotranslation Return translation for products
  648. *
  649. * @return ContratLigne[] Return array of contract lines
  650. */
  651. public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
  652. {
  653. // phpcs:enable
  654. global $langs, $conf, $extrafields;
  655. $this->nbofservices = 0;
  656. $this->nbofserviceswait = 0;
  657. $this->nbofservicesopened = 0;
  658. $this->nbofservicesexpired = 0;
  659. $this->nbofservicesclosed = 0;
  660. $total_ttc = 0;
  661. $total_vat = 0;
  662. $total_ht = 0;
  663. $now = dol_now();
  664. if (!is_object($extrafields)) {
  665. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  666. $extrafields = new ExtraFields($this->db);
  667. }
  668. $line = new ContratLigne($this->db);
  669. $extrafields->fetch_name_optionals_label($line->table_element, true);
  670. $this->lines = array();
  671. $pos = 0;
  672. // Selects contract lines related to a product
  673. $sql = "SELECT p.label as product_label, p.description as product_desc, p.ref as product_ref, p.fk_product_type as product_type,";
  674. $sql .= " d.rowid, d.fk_contrat, d.statut, d.description, d.price_ht, d.vat_src_code, d.tva_tx, d.localtax1_tx, d.localtax2_tx, d.localtax1_type, d.localtax2_type, d.qty, d.remise_percent, d.subprice, d.fk_product_fournisseur_price as fk_fournprice, d.buy_price_ht as pa_ht,";
  675. $sql .= " d.total_ht,";
  676. $sql .= " d.total_tva,";
  677. $sql .= " d.total_localtax1,";
  678. $sql .= " d.total_localtax2,";
  679. $sql .= " d.total_ttc,";
  680. $sql .= " d.info_bits, d.fk_product,";
  681. $sql .= " d.date_ouverture_prevue, d.date_ouverture,";
  682. $sql .= " d.date_fin_validite, d.date_cloture,";
  683. $sql .= " d.fk_user_author,";
  684. $sql .= " d.fk_user_ouverture,";
  685. $sql .= " d.fk_user_cloture,";
  686. $sql .= " d.fk_unit,";
  687. $sql .= " d.product_type as type";
  688. $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as d LEFT JOIN ".MAIN_DB_PREFIX."product as p ON d.fk_product = p.rowid";
  689. $sql .= " WHERE d.fk_contrat = ".((int) $this->id);
  690. $sql .= " ORDER by d.rowid ASC";
  691. dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG);
  692. $result = $this->db->query($sql);
  693. if ($result) {
  694. $num = $this->db->num_rows($result);
  695. $i = 0;
  696. while ($i < $num) {
  697. $objp = $this->db->fetch_object($result);
  698. $line = new ContratLigne($this->db);
  699. $line->id = $objp->rowid;
  700. $line->ref = $objp->rowid;
  701. $line->fk_contrat = $objp->fk_contrat;
  702. $line->desc = $objp->description; // Description line
  703. $line->qty = $objp->qty;
  704. $line->vat_src_code = $objp->vat_src_code;
  705. $line->tva_tx = $objp->tva_tx;
  706. $line->localtax1_tx = $objp->localtax1_tx;
  707. $line->localtax2_tx = $objp->localtax2_tx;
  708. $line->localtax1_type = $objp->localtax1_type;
  709. $line->localtax2_type = $objp->localtax2_type;
  710. $line->subprice = $objp->subprice;
  711. $line->statut = $objp->statut;
  712. $line->remise_percent = $objp->remise_percent;
  713. $line->price_ht = $objp->price_ht;
  714. $line->price = $objp->price_ht; // For backward compatibility
  715. $line->total_ht = $objp->total_ht;
  716. $line->total_tva = $objp->total_tva;
  717. $line->total_localtax1 = $objp->total_localtax1;
  718. $line->total_localtax2 = $objp->total_localtax2;
  719. $line->total_ttc = $objp->total_ttc;
  720. $line->fk_product = (($objp->fk_product > 0) ? $objp->fk_product : 0);
  721. $line->info_bits = $objp->info_bits;
  722. $line->type = $objp->type;
  723. $line->fk_fournprice = $objp->fk_fournprice;
  724. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  725. $line->pa_ht = $marginInfos[0];
  726. $line->fk_user_author = $objp->fk_user_author;
  727. $line->fk_user_ouverture = $objp->fk_user_ouverture;
  728. $line->fk_user_cloture = $objp->fk_user_cloture;
  729. $line->fk_unit = $objp->fk_unit;
  730. $line->ref = $objp->product_ref; // deprecated
  731. $line->product_ref = $objp->product_ref; // Product Ref
  732. $line->product_type = $objp->product_type; // Product Type
  733. $line->product_desc = $objp->product_desc; // Product Description
  734. $line->product_label = $objp->product_label; // Product Label
  735. $line->description = $objp->description;
  736. $line->date_start = $this->db->jdate($objp->date_ouverture_prevue);
  737. $line->date_start_real = $this->db->jdate($objp->date_ouverture);
  738. $line->date_end = $this->db->jdate($objp->date_fin_validite);
  739. $line->date_end_real = $this->db->jdate($objp->date_cloture);
  740. // For backward compatibility
  741. $line->date_ouverture_prevue = $this->db->jdate($objp->date_ouverture_prevue);
  742. $line->date_ouverture = $this->db->jdate($objp->date_ouverture);
  743. $line->date_fin_validite = $this->db->jdate($objp->date_fin_validite);
  744. $line->date_cloture = $this->db->jdate($objp->date_cloture);
  745. $line->date_debut_prevue = $this->db->jdate($objp->date_ouverture_prevue);
  746. $line->date_debut_reel = $this->db->jdate($objp->date_ouverture);
  747. $line->date_fin_prevue = $this->db->jdate($objp->date_fin_validite);
  748. $line->date_fin_reel = $this->db->jdate($objp->date_cloture);
  749. // Retrieve all extrafields for contract
  750. // fetch optionals attributes and labels
  751. $line->fetch_optionals();
  752. // multilangs
  753. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
  754. $line = new Product($this->db);
  755. $line->fetch($objp->fk_product);
  756. $line->getMultiLangs();
  757. }
  758. $this->lines[$pos] = $line;
  759. $this->lines_id_index_mapper[$line->id] = $pos;
  760. //dol_syslog("1 ".$line->desc);
  761. //dol_syslog("2 ".$line->product_desc);
  762. if ($line->statut == ContratLigne::STATUS_INITIAL) {
  763. $this->nbofserviceswait++;
  764. }
  765. if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) {
  766. $this->nbofservicesopened++;
  767. }
  768. if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) {
  769. $this->nbofservicesexpired++;
  770. }
  771. if ($line->statut == ContratLigne::STATUS_CLOSED) {
  772. $this->nbofservicesclosed++;
  773. }
  774. $total_ttc += $objp->total_ttc; // TODO Not saved into database
  775. $total_vat += $objp->total_tva;
  776. $total_ht += $objp->total_ht;
  777. $i++;
  778. $pos++;
  779. }
  780. $this->db->free($result);
  781. } else {
  782. dol_syslog(get_class($this)."::Fetch Error when reading lines of contracts linked to products");
  783. return -3;
  784. }
  785. // Now set the global properties on contract not stored into database.
  786. $this->nbofservices = count($this->lines);
  787. $this->total_ttc = price2num($total_ttc);
  788. $this->total_tva = price2num($total_vat);
  789. $this->total_ht = price2num($total_ht);
  790. return $this->lines;
  791. }
  792. /**
  793. * Create a contract into database
  794. *
  795. * @param User $user User that create
  796. * @return int <0 if KO, id of contract if OK
  797. */
  798. public function create($user)
  799. {
  800. global $conf, $langs, $mysoc;
  801. // Check parameters
  802. $paramsok = 1;
  803. if ($this->commercial_signature_id <= 0) {
  804. $langs->load("commercial");
  805. $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature"));
  806. $paramsok = 0;
  807. }
  808. if ($this->commercial_suivi_id <= 0) {
  809. $langs->load("commercial");
  810. $this->error .= ($this->error ? "<br>" : '');
  811. $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp"));
  812. $paramsok = 0;
  813. }
  814. if (!$paramsok) {
  815. return -1;
  816. }
  817. $this->db->begin();
  818. $now = dol_now();
  819. // Insert contract
  820. $sql = "INSERT INTO ".MAIN_DB_PREFIX."contrat (datec, fk_soc, fk_user_author, date_contrat,";
  821. $sql .= " fk_commercial_signature, fk_commercial_suivi, fk_projet,";
  822. $sql .= " ref, entity, note_private, note_public, ref_customer, ref_supplier, ref_ext)";
  823. $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->socid).", ".((int) $user->id);
  824. $sql .= ", ".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : "NULL");
  825. $sql .= ",".($this->commercial_signature_id > 0 ? ((int) $this->commercial_signature_id) : "NULL");
  826. $sql .= ",".($this->commercial_suivi_id > 0 ? ((int) $this->commercial_suivi_id) : "NULL");
  827. $sql .= ",".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL");
  828. $sql .= ", ".(dol_strlen($this->ref) <= 0 ? "null" : "'".$this->db->escape($this->ref)."'");
  829. $sql .= ", ".((int) $conf->entity);
  830. $sql .= ", ".(!empty($this->note_private) ? ("'".$this->db->escape($this->note_private)."'") : "NULL");
  831. $sql .= ", ".(!empty($this->note_public) ? ("'".$this->db->escape($this->note_public)."'") : "NULL");
  832. $sql .= ", ".(!empty($this->ref_customer) ? ("'".$this->db->escape($this->ref_customer)."'") : "NULL");
  833. $sql .= ", ".(!empty($this->ref_supplier) ? ("'".$this->db->escape($this->ref_supplier)."'") : "NULL");
  834. $sql .= ", ".(!empty($this->ref_ext) ? ("'".$this->db->escape($this->ref_ext)."'") : "NULL");
  835. $sql .= ")";
  836. $resql = $this->db->query($sql);
  837. if ($resql) {
  838. $error = 0;
  839. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat");
  840. // Load object modContract
  841. $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
  842. if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
  843. $module = substr($module, 0, dol_strlen($module) - 4);
  844. }
  845. $result = dol_include_once('/core/modules/contract/'.$module.'.php');
  846. if ($result > 0) {
  847. $modCodeContract = new $module();
  848. if (!empty($modCodeContract->code_auto)) {
  849. // Force the ref to a draft value if numbering module is an automatic numbering
  850. $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".((int) $this->id);
  851. if ($this->db->query($sql)) {
  852. if ($this->id) {
  853. $this->ref = "(PROV".$this->id.")";
  854. }
  855. }
  856. }
  857. }
  858. if (!$error) {
  859. $result = $this->insertExtraFields();
  860. if ($result < 0) {
  861. $error++;
  862. }
  863. }
  864. // Insert business contacts ('SALESREPSIGN','contrat')
  865. if (!$error) {
  866. $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal');
  867. if ($result < 0) {
  868. $error++;
  869. }
  870. }
  871. // Insert business contacts ('SALESREPFOLL','contrat')
  872. if (!$error) {
  873. $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal');
  874. if ($result < 0) {
  875. $error++;
  876. }
  877. }
  878. if (!$error) {
  879. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  880. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  881. }
  882. // Add object linked
  883. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  884. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  885. 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, ...))
  886. foreach ($tmp_origin_id as $origin_id) {
  887. $ret = $this->add_object_linked($origin, $origin_id);
  888. if (!$ret) {
  889. $this->error = $this->db->lasterror();
  890. $error++;
  891. }
  892. }
  893. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  894. {
  895. $origin_id = $tmp_origin_id;
  896. $ret = $this->add_object_linked($origin, $origin_id);
  897. if (!$ret) {
  898. $this->error = $this->db->lasterror();
  899. $error++;
  900. }
  901. }
  902. }
  903. }
  904. if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
  905. $originforcontact = $this->origin;
  906. $originidforcontact = $this->origin_id;
  907. if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
  908. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  909. $exp = new Expedition($this->db);
  910. $exp->fetch($this->origin_id);
  911. $exp->fetchObjectLinked();
  912. if (count($exp->linkedObjectsIds['commande']) > 0) {
  913. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  914. $originforcontact = 'commande';
  915. $originidforcontact = $value->id;
  916. break; // We take first one
  917. }
  918. }
  919. }
  920. $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  921. $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
  922. $resqlcontact = $this->db->query($sqlcontact);
  923. if ($resqlcontact) {
  924. while ($objcontact = $this->db->fetch_object($resqlcontact)) {
  925. if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) {
  926. continue; // ignore this, already forced previously
  927. }
  928. //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
  929. $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
  930. }
  931. } else {
  932. dol_print_error($resqlcontact);
  933. }
  934. }
  935. }
  936. if (!$error) {
  937. // Call trigger
  938. $result = $this->call_trigger('CONTRACT_CREATE', $user);
  939. if ($result < 0) {
  940. $error++;
  941. }
  942. // End call triggers
  943. if (!$error) {
  944. $this->db->commit();
  945. return $this->id;
  946. } else {
  947. dol_syslog(get_class($this)."::create - 30 - ".$this->error, LOG_ERR);
  948. $this->db->rollback();
  949. return -3;
  950. }
  951. } else {
  952. $this->error = "Failed to add contract";
  953. dol_syslog(get_class($this)."::create - 20 - ".$this->error, LOG_ERR);
  954. $this->db->rollback();
  955. return -2;
  956. }
  957. } else {
  958. $this->error = $langs->trans("UnknownError: ".$this->db->error()." -", LOG_DEBUG);
  959. $this->db->rollback();
  960. return -1;
  961. }
  962. }
  963. /**
  964. * Delete object
  965. *
  966. * @param User $user User that deletes
  967. * @return int < 0 if KO, > 0 if OK
  968. */
  969. public function delete($user)
  970. {
  971. global $conf, $langs;
  972. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  973. $error = 0;
  974. $this->db->begin();
  975. // Call trigger
  976. $result = $this->call_trigger('CONTRACT_DELETE', $user);
  977. if ($result < 0) {
  978. $error++;
  979. }
  980. // End call triggers
  981. if (!$error) {
  982. // Delete linked contacts
  983. $res = $this->delete_linked_contact();
  984. if ($res < 0) {
  985. dol_syslog(get_class($this)."::delete error", LOG_ERR);
  986. $error++;
  987. }
  988. }
  989. if (!$error) {
  990. // Delete linked object
  991. $res = $this->deleteObjectLinked();
  992. if ($res < 0) {
  993. $error++;
  994. }
  995. }
  996. if (!$error) {
  997. // Delete contratdet_log
  998. /*
  999. $sql = "DELETE cdl";
  1000. $sql.= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
  1001. $sql.= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
  1002. */
  1003. $sql = "SELECT cdl.rowid as cdlrowid ";
  1004. $sql .= " FROM ".MAIN_DB_PREFIX."contratdet_log as cdl, ".MAIN_DB_PREFIX."contratdet as cd";
  1005. $sql .= " WHERE cdl.fk_contratdet=cd.rowid AND cd.fk_contrat=".((int) $this->id);
  1006. dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
  1007. $resql = $this->db->query($sql);
  1008. if (!$resql) {
  1009. $this->error = $this->db->error();
  1010. $error++;
  1011. }
  1012. $numressql = $this->db->num_rows($resql);
  1013. if (!$error && $numressql) {
  1014. $tab_resql = array();
  1015. for ($i = 0; $i < $numressql; $i++) {
  1016. $objresql = $this->db->fetch_object($resql);
  1017. $tab_resql[] = $objresql->cdlrowid;
  1018. }
  1019. $this->db->free($resql);
  1020. $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet_log ";
  1021. $sql .= " WHERE ".MAIN_DB_PREFIX."contratdet_log.rowid IN (".$this->db->sanitize(implode(",", $tab_resql)).")";
  1022. dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG);
  1023. $resql = $this->db->query($sql);
  1024. if (!$resql) {
  1025. $this->error = $this->db->error();
  1026. $error++;
  1027. }
  1028. }
  1029. }
  1030. // Delete lines
  1031. if (!$error) {
  1032. // Delete contratdet extrafields
  1033. $main = MAIN_DB_PREFIX.'contratdet';
  1034. $ef = $main."_extrafields";
  1035. $sql = "DELETE FROM ".$ef." WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_contrat = ".((int) $this->id).")";
  1036. dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG);
  1037. $resql = $this->db->query($sql);
  1038. if (!$resql) {
  1039. $this->error = $this->db->error();
  1040. $error++;
  1041. }
  1042. }
  1043. if (!$error) {
  1044. // Delete contratdet
  1045. $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet";
  1046. $sql .= " WHERE fk_contrat=".((int) $this->id);
  1047. dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG);
  1048. $resql = $this->db->query($sql);
  1049. if (!$resql) {
  1050. $this->error = $this->db->error();
  1051. $error++;
  1052. }
  1053. }
  1054. // Delete llx_ecm_files
  1055. if (!$error) {
  1056. $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? "" : "@".$this->module))."' AND src_object_id = ".((int) $this->id);
  1057. $resql = $this->db->query($sql);
  1058. if (!$resql) {
  1059. $this->error = $this->db->lasterror();
  1060. $this->errors[] = $this->error;
  1061. $error++;
  1062. }
  1063. }
  1064. // Delete contract
  1065. if (!$error) {
  1066. $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat";
  1067. $sql .= " WHERE rowid=".((int) $this->id);
  1068. dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG);
  1069. $resql = $this->db->query($sql);
  1070. if (!$resql) {
  1071. $this->error = $this->db->error();
  1072. $error++;
  1073. }
  1074. }
  1075. // Removed extrafields
  1076. if (!$error) {
  1077. $result = $this->deleteExtraFields();
  1078. if ($result < 0) {
  1079. $error++;
  1080. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  1081. }
  1082. }
  1083. if (!$error) {
  1084. // We remove directory
  1085. $ref = dol_sanitizeFileName($this->ref);
  1086. if ($conf->contrat->dir_output) {
  1087. $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref;
  1088. if (file_exists($dir)) {
  1089. $res = @dol_delete_dir_recursive($dir);
  1090. if (!$res) {
  1091. $this->error = 'ErrorFailToDeleteDir';
  1092. $error++;
  1093. }
  1094. }
  1095. }
  1096. }
  1097. if (!$error) {
  1098. $this->db->commit();
  1099. return 1;
  1100. } else {
  1101. $this->error = $this->db->lasterror();
  1102. $this->db->rollback();
  1103. return -1;
  1104. }
  1105. }
  1106. /**
  1107. * Update object into database
  1108. *
  1109. * @param User $user User that modifies
  1110. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1111. * @return int <0 if KO, >0 if OK
  1112. */
  1113. public function update($user, $notrigger = 0)
  1114. {
  1115. global $conf, $langs;
  1116. $error = 0;
  1117. // Clean parameters
  1118. if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) {
  1119. $this->fk_commercial_signature = $this->commercial_signature_id;
  1120. }
  1121. if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) {
  1122. $this->fk_commercial_suivi = $this->commercial_suivi_id;
  1123. }
  1124. if (empty($this->fk_soc) && $this->socid > 0) {
  1125. $this->fk_soc = (int) $this->socid;
  1126. }
  1127. if (empty($this->fk_project) && $this->projet > 0) {
  1128. $this->fk_project = (int) $this->projet;
  1129. }
  1130. if (isset($this->ref)) {
  1131. $this->ref = trim($this->ref);
  1132. }
  1133. if (isset($this->ref_customer)) {
  1134. $this->ref_customer = trim($this->ref_customer);
  1135. }
  1136. if (isset($this->ref_supplier)) {
  1137. $this->ref_supplier = trim($this->ref_supplier);
  1138. }
  1139. if (isset($this->ref_ext)) {
  1140. $this->ref_ext = trim($this->ref_ext);
  1141. }
  1142. if (isset($this->entity)) {
  1143. $this->entity = (int) $this->entity;
  1144. }
  1145. if (isset($this->statut)) {
  1146. $this->statut = (int) $this->statut;
  1147. }
  1148. if (isset($this->fk_soc)) {
  1149. $this->fk_soc = (int) $this->fk_soc;
  1150. }
  1151. if (isset($this->fk_commercial_signature)) {
  1152. $this->fk_commercial_signature = trim($this->fk_commercial_signature);
  1153. }
  1154. if (isset($this->fk_commercial_suivi)) {
  1155. $this->fk_commercial_suivi = trim($this->fk_commercial_suivi);
  1156. }
  1157. if (isset($this->note_private)) {
  1158. $this->note_private = trim($this->note_private);
  1159. }
  1160. if (isset($this->note_public)) {
  1161. $this->note_public = trim($this->note_public);
  1162. }
  1163. if (isset($this->import_key)) {
  1164. $this->import_key = trim($this->import_key);
  1165. }
  1166. //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams);
  1167. // Check parameters
  1168. // Put here code to add a control on parameters values
  1169. // Update request
  1170. $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET";
  1171. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  1172. $sql .= " ref_customer=".(isset($this->ref_customer) ? "'".$this->db->escape($this->ref_customer)."'" : "null").",";
  1173. $sql .= " ref_supplier=".(isset($this->ref_supplier) ? "'".$this->db->escape($this->ref_supplier)."'" : "null").",";
  1174. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  1175. $sql .= " entity=".$conf->entity.",";
  1176. $sql .= " date_contrat=".(dol_strlen($this->date_contrat) != 0 ? "'".$this->db->idate($this->date_contrat)."'" : 'null').",";
  1177. $sql .= " statut=".(isset($this->statut) ? $this->statut : "null").",";
  1178. $sql .= " fk_soc=".($this->fk_soc > 0 ? $this->fk_soc : "null").",";
  1179. $sql .= " fk_projet=".($this->fk_project > 0 ? $this->fk_project : "null").",";
  1180. $sql .= " fk_commercial_signature=".(isset($this->fk_commercial_signature) ? $this->fk_commercial_signature : "null").",";
  1181. $sql .= " fk_commercial_suivi=".(isset($this->fk_commercial_suivi) ? $this->fk_commercial_suivi : "null").",";
  1182. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  1183. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  1184. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
  1185. //$sql.= " extraparams=".(isset($this->extraparams)?"'".$this->db->escape($this->extraparams)."'":"null")."";
  1186. $sql .= " WHERE rowid=".((int) $this->id);
  1187. $this->db->begin();
  1188. $resql = $this->db->query($sql);
  1189. if (!$resql) {
  1190. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  1191. }
  1192. if (!$error) {
  1193. $result = $this->insertExtraFields();
  1194. if ($result < 0) {
  1195. $error++;
  1196. }
  1197. }
  1198. if (!$error && !$notrigger) {
  1199. // Call triggers
  1200. $result = $this->call_trigger('CONTRACT_MODIFY', $user);
  1201. if ($result < 0) {
  1202. $error++;
  1203. }
  1204. // End call triggers
  1205. }
  1206. // Commit or rollback
  1207. if ($error) {
  1208. foreach ($this->errors as $errmsg) {
  1209. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1210. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1211. }
  1212. $this->db->rollback();
  1213. return -1 * $error;
  1214. } else {
  1215. $this->db->commit();
  1216. return 1;
  1217. }
  1218. }
  1219. /**
  1220. * Ajoute une ligne de contrat en base
  1221. *
  1222. * @param string $desc Description of line
  1223. * @param float $pu_ht Unit price net
  1224. * @param int $qty Quantity
  1225. * @param float $txtva Vat rate
  1226. * @param float $txlocaltax1 Local tax 1 rate
  1227. * @param float $txlocaltax2 Local tax 2 rate
  1228. * @param int $fk_product Id produit
  1229. * @param float $remise_percent Percentage discount of the line
  1230. * @param int $date_start Date de debut prevue
  1231. * @param int $date_end Date de fin prevue
  1232. * @param string $price_base_type HT or TTC
  1233. * @param float $pu_ttc Prix unitaire TTC
  1234. * @param int $info_bits Bits of type of lines
  1235. * @param int $fk_fournprice Fourn price id
  1236. * @param int $pa_ht Buying price HT
  1237. * @param array $array_options extrafields array
  1238. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1239. * @param string $rang Position
  1240. * @return int <0 if KO, >0 if OK
  1241. */
  1242. public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0)
  1243. {
  1244. global $user, $langs, $conf, $mysoc;
  1245. $error = 0;
  1246. dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang");
  1247. // Check parameters
  1248. if ($fk_product <= 0 && empty($desc)) {
  1249. $this->error = "ErrorDescRequiredForFreeProductLines";
  1250. return -1;
  1251. }
  1252. if ($this->statut >= 0) {
  1253. // Clean parameters
  1254. $pu_ht = price2num($pu_ht);
  1255. $pu_ttc = price2num($pu_ttc);
  1256. $pa_ht = price2num($pa_ht);
  1257. // Clean vat code
  1258. $reg = array();
  1259. $vat_src_code = '';
  1260. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  1261. $vat_src_code = $reg[1];
  1262. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  1263. }
  1264. $txtva = price2num($txtva);
  1265. $txlocaltax1 = price2num($txlocaltax1);
  1266. $txlocaltax2 = price2num($txlocaltax2);
  1267. $remise_percent = price2num($remise_percent);
  1268. $qty = price2num($qty);
  1269. if (empty($qty)) {
  1270. $qty = 1;
  1271. }
  1272. if (empty($info_bits)) {
  1273. $info_bits = 0;
  1274. }
  1275. if (empty($pu_ht) || !is_numeric($pu_ht)) {
  1276. $pu_ht = 0;
  1277. }
  1278. if (empty($pu_ttc)) {
  1279. $pu_ttc = 0;
  1280. }
  1281. if (empty($txtva) || !is_numeric($txtva)) {
  1282. $txtva = 0;
  1283. }
  1284. if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) {
  1285. $txlocaltax1 = 0;
  1286. }
  1287. if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) {
  1288. $txlocaltax2 = 0;
  1289. }
  1290. if ($price_base_type == 'HT') {
  1291. $pu = $pu_ht;
  1292. } else {
  1293. $pu = $pu_ttc;
  1294. }
  1295. // Check parameters
  1296. if (empty($remise_percent)) {
  1297. $remise_percent = 0;
  1298. }
  1299. if ($date_start && $date_end && $date_start > $date_end) {
  1300. $langs->load("errors");
  1301. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  1302. return -1;
  1303. }
  1304. $this->db->begin();
  1305. $localtaxes_type = getLocalTaxesFromRate($txtva.($vat_src_code ? ' ('.$vat_src_code.')' : ''), 0, $this->societe, $mysoc);
  1306. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1307. // qty, pu, remise_percent et txtva
  1308. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1309. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1310. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
  1311. $total_ht = $tabprice[0];
  1312. $total_tva = $tabprice[1];
  1313. $total_ttc = $tabprice[2];
  1314. $total_localtax1 = $tabprice[9];
  1315. $total_localtax2 = $tabprice[10];
  1316. $localtax1_type = $localtaxes_type[0];
  1317. $localtax2_type = $localtaxes_type[2];
  1318. // TODO A virer
  1319. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  1320. $remise = 0;
  1321. $price = price2num(round($pu_ht, 2));
  1322. if (dol_strlen($remise_percent) > 0) {
  1323. $remise = round(($pu_ht * $remise_percent / 100), 2);
  1324. $price = $pu_ht - $remise;
  1325. }
  1326. if (empty($pa_ht)) {
  1327. $pa_ht = 0;
  1328. }
  1329. // if buy price not defined, define buyprice as configured in margin admin
  1330. if ($this->pa_ht == 0) {
  1331. if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) {
  1332. return $result;
  1333. } else {
  1334. $pa_ht = $result;
  1335. }
  1336. }
  1337. // Insertion dans la base
  1338. $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
  1339. $sql .= " (fk_contrat, label, description, fk_product, qty, tva_tx, vat_src_code,";
  1340. $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
  1341. $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
  1342. $sql .= " info_bits,";
  1343. $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
  1344. if ($date_start > 0) {
  1345. $sql .= ",date_ouverture_prevue";
  1346. }
  1347. if ($date_end > 0) {
  1348. $sql .= ",date_fin_validite";
  1349. }
  1350. $sql .= ", fk_unit";
  1351. $sql .= ") VALUES (";
  1352. $sql .= $this->id.", '', '".$this->db->escape($desc)."',";
  1353. $sql .= ($fk_product > 0 ? $fk_product : "null").",";
  1354. $sql .= " ".((float) $qty).",";
  1355. $sql .= " ".((float) $txtva).",";
  1356. $sql .= " ".($vat_src_code ? "'".$this->db->escape($vat_src_code)."'" : "null").",";
  1357. $sql .= " ".((float) $txlocaltax1).",";
  1358. $sql .= " ".((float) $txlocaltax2).",";
  1359. $sql .= " '".$this->db->escape($localtax1_type)."',";
  1360. $sql .= " '".$this->db->escape($localtax2_type)."',";
  1361. $sql .= " ".price2num($remise_percent).",";
  1362. $sql .= " ".price2num($pu_ht).",";
  1363. $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).",";
  1364. $sql .= " '".$this->db->escape($info_bits)."',";
  1365. $sql .= " ".price2num($price).",".price2num($remise).",";
  1366. if (isset($fk_fournprice)) {
  1367. $sql .= ' '.((int) $fk_fournprice).',';
  1368. } else {
  1369. $sql .= ' null,';
  1370. }
  1371. if (isset($pa_ht)) {
  1372. $sql .= ' '.price2num($pa_ht);
  1373. } else {
  1374. $sql .= ' null';
  1375. }
  1376. if ($date_start > 0) {
  1377. $sql .= ",'".$this->db->idate($date_start)."'";
  1378. }
  1379. if ($date_end > 0) {
  1380. $sql .= ",'".$this->db->idate($date_end)."'";
  1381. }
  1382. $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null");
  1383. $sql .= ")";
  1384. $resql = $this->db->query($sql);
  1385. if ($resql) {
  1386. $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet");
  1387. if (!$error) {
  1388. $contractline = new ContratLigne($this->db);
  1389. $contractline->array_options = $array_options;
  1390. $contractline->id = $contractlineid;
  1391. $result = $contractline->insertExtraFields();
  1392. if ($result < 0) {
  1393. $this->error[] = $contractline->error;
  1394. $error++;
  1395. }
  1396. }
  1397. if (empty($error)) {
  1398. // Call trigger
  1399. $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
  1400. if ($result < 0) {
  1401. $error++;
  1402. }
  1403. // End call triggers
  1404. }
  1405. if ($error) {
  1406. $this->db->rollback();
  1407. return -1;
  1408. } else {
  1409. $this->db->commit();
  1410. return $contractlineid;
  1411. }
  1412. } else {
  1413. $this->db->rollback();
  1414. $this->error = $this->db->error()." sql=".$sql;
  1415. return -1;
  1416. }
  1417. } else {
  1418. dol_syslog(get_class($this)."::addline ErrorTryToAddLineOnValidatedContract", LOG_ERR);
  1419. return -2;
  1420. }
  1421. }
  1422. /**
  1423. * Mets a jour une ligne de contrat
  1424. *
  1425. * @param int $rowid Id de la ligne de facture
  1426. * @param string $desc Description de la ligne
  1427. * @param float $pu Prix unitaire
  1428. * @param int $qty Quantite
  1429. * @param float $remise_percent Percentage discount of the line
  1430. * @param int $date_start Date de debut prevue
  1431. * @param int $date_end Date de fin prevue
  1432. * @param float $tvatx Taux TVA
  1433. * @param float $localtax1tx Local tax 1 rate
  1434. * @param float $localtax2tx Local tax 2 rate
  1435. * @param int|string $date_debut_reel Date de debut reelle
  1436. * @param int|string $date_fin_reel Date de fin reelle
  1437. * @param string $price_base_type HT or TTC
  1438. * @param int $info_bits Bits of type of lines
  1439. * @param int $fk_fournprice Fourn price id
  1440. * @param int $pa_ht Buying price HT
  1441. * @param array $array_options extrafields array
  1442. * @param string $fk_unit Code of the unit to use. Null to use the default one
  1443. * @return int < 0 si erreur, > 0 si ok
  1444. */
  1445. public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_debut_reel = '', $date_fin_reel = '', $price_base_type = 'HT', $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null)
  1446. {
  1447. global $user, $conf, $langs, $mysoc;
  1448. $error = 0;
  1449. // Clean parameters
  1450. $qty = trim($qty);
  1451. $desc = trim($desc);
  1452. $desc = trim($desc);
  1453. $price = price2num($pu);
  1454. $tvatx = price2num($tvatx);
  1455. $localtax1tx = price2num($localtax1tx);
  1456. $localtax2tx = price2num($localtax2tx);
  1457. $pa_ht = price2num($pa_ht);
  1458. if (empty($fk_fournprice)) {
  1459. $fk_fournprice = 0;
  1460. }
  1461. $subprice = $price;
  1462. $remise = 0;
  1463. if (dol_strlen($remise_percent) > 0) {
  1464. $remise = round(($pu * $remise_percent / 100), 2);
  1465. $price = $pu - $remise;
  1466. } else {
  1467. $remise_percent = 0;
  1468. }
  1469. if ($date_start && $date_end && $date_start > $date_end) {
  1470. $langs->load("errors");
  1471. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  1472. return -1;
  1473. }
  1474. dol_syslog(get_class($this)."::updateline $rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $date_debut_reel, $date_fin_reel, $tvatx, $localtax1tx, $localtax2tx, $price_base_type, $info_bits");
  1475. $this->db->begin();
  1476. // Calcul du total TTC et de la TVA pour la ligne a partir de
  1477. // qty, pu, remise_percent et tvatx
  1478. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  1479. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  1480. $localtaxes_type = getLocalTaxesFromRate($tvatx, 0, $this->societe, $mysoc);
  1481. $tvatx = preg_replace('/\s*\(.*\)/', '', $tvatx); // Remove code into vatrate.
  1482. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $tvatx, $localtax1tx, $localtax2tx, 0, $price_base_type, $info_bits, 1, $mysoc, $localtaxes_type);
  1483. $total_ht = $tabprice[0];
  1484. $total_tva = $tabprice[1];
  1485. $total_ttc = $tabprice[2];
  1486. $total_localtax1 = $tabprice[9];
  1487. $total_localtax2 = $tabprice[10];
  1488. $localtax1_type = $localtaxes_type[0];
  1489. $localtax2_type = $localtaxes_type[2];
  1490. // TODO A virer
  1491. // Anciens indicateurs: $price, $remise (a ne plus utiliser)
  1492. $remise = 0;
  1493. $price = price2num(round($pu, 2));
  1494. if (dol_strlen($remise_percent) > 0) {
  1495. $remise = round(($pu * $remise_percent / 100), 2);
  1496. $price = $pu - $remise;
  1497. }
  1498. if (empty($pa_ht)) {
  1499. $pa_ht = 0;
  1500. }
  1501. // if buy price not defined, define buyprice as configured in margin admin
  1502. if ($this->pa_ht == 0) {
  1503. if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) {
  1504. return $result;
  1505. } else {
  1506. $pa_ht = $result;
  1507. }
  1508. }
  1509. $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet set description = '".$this->db->escape($desc)."'";
  1510. $sql .= ",price_ht = ".((float) price2num($price));
  1511. $sql .= ",subprice = ".((float) price2num($subprice));
  1512. $sql .= ",remise = ".((float) price2num($remise));
  1513. $sql .= ",remise_percent = ".((float) price2num($remise_percent));
  1514. $sql .= ",qty = ".((float) $qty);
  1515. $sql .= ",tva_tx = ".((float) price2num($tvatx));
  1516. $sql .= ",localtax1_tx = ".((float) price2num($localtax1tx));
  1517. $sql .= ",localtax2_tx = ".((float) price2num($localtax2tx));
  1518. $sql .= ",localtax1_type='".$this->db->escape($localtax1_type);
  1519. $sql .= ",localtax2_type='".$this->db->escape($localtax2_type);
  1520. $sql .= ", total_ht = ".((float) price2num($total_ht));
  1521. $sql .= ", total_tva = ".((float) price2num($total_tva));
  1522. $sql .= ", total_localtax1 = ".((float) price2num($total_localtax1));
  1523. $sql .= ", total_localtax2 = ".((float) price2num($total_localtax2));
  1524. $sql .= ", total_ttc = ".((float) price2num($total_ttc));
  1525. $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null");
  1526. $sql .= ", buy_price_ht = ".((float) price2num($pa_ht));
  1527. if ($date_start > 0) {
  1528. $sql .= ",date_ouverture_prevue = '".$this->db->idate($date_start)."'";
  1529. } else {
  1530. $sql .= ",date_ouverture_prevue = null";
  1531. }
  1532. if ($date_end > 0) {
  1533. $sql .= ",date_fin_validite = '".$this->db->idate($date_end)."'";
  1534. } else {
  1535. $sql .= ",date_fin_validite = null";
  1536. }
  1537. if ($date_debut_reel > 0) {
  1538. $sql .= ",date_ouverture = '".$this->db->idate($date_debut_reel)."'";
  1539. } else {
  1540. $sql .= ",date_ouverture = null";
  1541. }
  1542. if ($date_fin_reel > 0) {
  1543. $sql .= ",date_cloture = '".$this->db->idate($date_fin_reel)."'";
  1544. } else {
  1545. $sql .= ",date_cloture = null";
  1546. }
  1547. $sql .= ", fk_unit = ".($fk_unit > 0 ? ((int) $fk_unit) : "null");
  1548. $sql .= " WHERE rowid = ".((int) $rowid);
  1549. dol_syslog(get_class($this)."::updateline", LOG_DEBUG);
  1550. $result = $this->db->query($sql);
  1551. if ($result) {
  1552. if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used
  1553. $contractline = new ContratLigne($this->db);
  1554. $contractline->fetch($rowid);
  1555. // We replace values in $contractline->array_options only for entries defined into $array_options
  1556. foreach ($array_options as $key => $value) {
  1557. $contractline->array_options[$key] = $array_options[$key];
  1558. }
  1559. $result = $contractline->insertExtraFields();
  1560. if ($result < 0) {
  1561. $this->error[] = $contractline->error;
  1562. $error++;
  1563. }
  1564. }
  1565. if (empty($error)) {
  1566. // Call trigger
  1567. $result = $this->call_trigger('LINECONTRACT_UPDATE', $user);
  1568. if ($result < 0) {
  1569. $this->db->rollback();
  1570. return -3;
  1571. }
  1572. // End call triggers
  1573. $this->db->commit();
  1574. return 1;
  1575. }
  1576. } else {
  1577. $this->db->rollback();
  1578. $this->error = $this->db->error();
  1579. dol_syslog(get_class($this)."::updateline Erreur -1");
  1580. return -1;
  1581. }
  1582. }
  1583. /**
  1584. * Delete a contract line
  1585. *
  1586. * @param int $idline Id of line to delete
  1587. * @param User $user User that delete
  1588. * @return int >0 if OK, <0 if KO
  1589. */
  1590. public function deleteline($idline, User $user)
  1591. {
  1592. global $conf, $langs;
  1593. $error = 0;
  1594. if ($this->statut >= 0) {
  1595. // Call trigger
  1596. $result = $this->call_trigger('LINECONTRACT_DELETE', $user);
  1597. if ($result < 0) {
  1598. return -1;
  1599. }
  1600. // End call triggers
  1601. $this->db->begin();
  1602. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element_line;
  1603. $sql .= " WHERE rowid = ".((int) $idline);
  1604. dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
  1605. $resql = $this->db->query($sql);
  1606. if (!$resql) {
  1607. $this->error = "Error ".$this->db->lasterror();
  1608. $error++;
  1609. }
  1610. if (!$error) {
  1611. // Remove extrafields
  1612. $contractline = new ContratLigne($this->db);
  1613. $contractline->id = $idline;
  1614. $result = $contractline->deleteExtraFields();
  1615. if ($result < 0) {
  1616. $error++;
  1617. $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error;
  1618. }
  1619. }
  1620. if (empty($error)) {
  1621. $this->db->commit();
  1622. return 1;
  1623. } else {
  1624. dol_syslog(get_class($this)."::deleteline ERROR:".$this->error, LOG_ERR);
  1625. $this->db->rollback();
  1626. return -1;
  1627. }
  1628. } else {
  1629. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  1630. return -2;
  1631. }
  1632. }
  1633. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1634. /**
  1635. * Update statut of contract according to services
  1636. *
  1637. * @param User $user Object user
  1638. * @return int <0 if KO, >0 if OK
  1639. * @deprecated This function will never be used. Status of a contract is status of its lines.
  1640. */
  1641. public function update_statut($user)
  1642. {
  1643. // phpcs:enable
  1644. dol_syslog(__METHOD__." is deprecated", LOG_WARNING);
  1645. // If draft, we keep it (should not happen)
  1646. if ($this->statut == 0) {
  1647. return 1;
  1648. }
  1649. // Load $this->lines array
  1650. // $this->fetch_lines();
  1651. // $newstatut=1;
  1652. // foreach($this->lines as $key => $contractline)
  1653. // {
  1654. // // if ($contractline) // Loop on each service
  1655. // }
  1656. return 1;
  1657. }
  1658. /**
  1659. * Return label of a contract status
  1660. *
  1661. * @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, 7=Same than 6 with fixed length
  1662. * @return string Label
  1663. */
  1664. public function getLibStatut($mode)
  1665. {
  1666. return $this->LibStatut($this->statut, $mode);
  1667. }
  1668. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1669. /**
  1670. * Renvoi label of a given contrat status
  1671. *
  1672. * @param int $status Id status
  1673. * @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, 7=Same than 6 with fixed length
  1674. * @return string Label
  1675. */
  1676. public function LibStatut($status, $mode)
  1677. {
  1678. // phpcs:enable
  1679. global $langs;
  1680. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  1681. global $langs;
  1682. $langs->load("contracts");
  1683. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
  1684. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
  1685. $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
  1686. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft');
  1687. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ContractStatusValidated');
  1688. $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('ContractStatusClosed');
  1689. }
  1690. $statusType = 'status'.$status;
  1691. if ($status == self::STATUS_VALIDATED) {
  1692. $statusType = 'status6';
  1693. }
  1694. if ($mode == 4 || $mode == 6 || $mode == 7) {
  1695. $text = '';
  1696. if ($mode == 4) {
  1697. $text = '<span class="hideonsmartphone">';
  1698. $text .= ($this->nbofserviceswait + $this->nbofservicesopened + $this->nbofservicesexpired + $this->nbofservicesclosed);
  1699. $text .= ' '.$langs->trans("Services");
  1700. $text .= ': &nbsp; &nbsp; ';
  1701. $text .= '</span>';
  1702. }
  1703. $text .= ($mode == 7 ? '<span class="nowraponall">' : '');
  1704. $text .= ($mode != 7 || $this->nbofserviceswait > 0) ? ($this->nbofserviceswait.ContratLigne::LibStatut(0, 3, -1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesopened || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
  1705. $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
  1706. $text .= ($mode != 7 || $this->nbofservicesopened > 0) ? ($this->nbofservicesopened.ContratLigne::LibStatut(4, 3, 0, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesexpired || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
  1707. $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
  1708. $text .= ($mode != 7 || $this->nbofservicesexpired > 0) ? ($this->nbofservicesexpired.ContratLigne::LibStatut(4, 3, 1, 'class="marginleft2"')).(($mode != 7 || $this->nbofservicesclosed) ? ' &nbsp; ' : '') : '';
  1709. $text .= ($mode == 7 ? '</span><span class="nowraponall">' : '');
  1710. $text .= ($mode != 7 || $this->nbofservicesclosed > 0) ? ($this->nbofservicesclosed.ContratLigne::LibStatut(5, 3, -1, 'class="marginleft2"')) : '';
  1711. $text .= ($mode == 7 ? '</span>' : '');
  1712. return $text;
  1713. } else {
  1714. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  1715. }
  1716. }
  1717. /**
  1718. * Return clicable name (with picto eventually)
  1719. *
  1720. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  1721. * @param int $maxlength Max length of ref
  1722. * @param int $notooltip 1=Disable tooltip
  1723. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1724. * @return string Chaine avec URL
  1725. */
  1726. public function getNomUrl($withpicto = 0, $maxlength = 0, $notooltip = 0, $save_lastsearch_value = -1)
  1727. {
  1728. global $conf, $langs, $user, $hookmanager;
  1729. $result = '';
  1730. $url = DOL_URL_ROOT.'/contrat/card.php?id='.$this->id;
  1731. //if ($option !== 'nolink')
  1732. //{
  1733. // Add param to save lastsearch_values or not
  1734. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1735. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1736. $add_save_lastsearch_values = 1;
  1737. }
  1738. if ($add_save_lastsearch_values) {
  1739. $url .= '&save_lastsearch_values=1';
  1740. }
  1741. //}
  1742. $label = '';
  1743. if ($user->rights->contrat->lire) {
  1744. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Contract").'</u>';
  1745. /* Status of a contract is status of all services, so disabled
  1746. if (isset($this->statut)) {
  1747. $label .= ' '.$this->getLibStatut(5);
  1748. }*/
  1749. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.($this->ref ? $this->ref : $this->id);
  1750. $ref_customer = (!empty($this->ref_customer) ? $this->ref_customer : (empty($this->ref_client) ? '' : $this->ref_client));
  1751. $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$ref_customer;
  1752. $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
  1753. if (!empty($this->total_ht)) {
  1754. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1755. }
  1756. if (!empty($this->total_tva)) {
  1757. $label .= '<br><b>'.$langs->trans('VAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1758. }
  1759. if (!empty($this->total_ttc)) {
  1760. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1761. }
  1762. }
  1763. $linkclose = '';
  1764. if (empty($notooltip) && $user->rights->contrat->lire) {
  1765. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1766. $label = $langs->trans("ShowOrder");
  1767. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1768. }
  1769. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1770. $linkclose .= ' class="classfortooltip"';
  1771. }
  1772. $linkstart = '<a href="'.$url.'"';
  1773. $linkstart .= $linkclose.'>';
  1774. $linkend = '</a>';
  1775. $result .= $linkstart;
  1776. if ($withpicto) {
  1777. $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1778. }
  1779. if ($withpicto != 2) {
  1780. $result .= ($this->ref ? $this->ref : $this->id);
  1781. }
  1782. $result .= $linkend;
  1783. global $action;
  1784. $hookmanager->initHooks(array('contractdao'));
  1785. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1786. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1787. if ($reshook > 0) {
  1788. $result = $hookmanager->resPrint;
  1789. } else {
  1790. $result .= $hookmanager->resPrint;
  1791. }
  1792. return $result;
  1793. }
  1794. /**
  1795. * Charge les informations d'ordre info dans l'objet contrat
  1796. *
  1797. * @param int $id id du contrat a charger
  1798. * @return void
  1799. */
  1800. public function info($id)
  1801. {
  1802. $sql = "SELECT c.rowid, c.ref, c.datec,";
  1803. $sql .= " c.tms as date_modification,";
  1804. $sql .= " fk_user_author";
  1805. $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
  1806. $sql .= " WHERE c.rowid = ".((int) $id);
  1807. $result = $this->db->query($sql);
  1808. if ($result) {
  1809. if ($this->db->num_rows($result)) {
  1810. $obj = $this->db->fetch_object($result);
  1811. $this->id = $obj->rowid;
  1812. if ($obj->fk_user_author) {
  1813. $cuser = new User($this->db);
  1814. $cuser->fetch($obj->fk_user_author);
  1815. $this->user_creation = $cuser;
  1816. }
  1817. $this->ref = (!$obj->ref) ? $obj->rowid : $obj->ref;
  1818. $this->date_creation = $this->db->jdate($obj->datec);
  1819. $this->date_modification = $this->db->jdate($obj->date_modification);
  1820. }
  1821. $this->db->free($result);
  1822. } else {
  1823. dol_print_error($this->db);
  1824. }
  1825. }
  1826. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1827. /**
  1828. * Return list of line rowid
  1829. *
  1830. * @param int $status Status of lines to get
  1831. * @return array|int Array of line's rowid or <0 if error
  1832. */
  1833. public function array_detail($status = -1)
  1834. {
  1835. // phpcs:enable
  1836. $tab = array();
  1837. $sql = "SELECT cd.rowid";
  1838. $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
  1839. $sql .= " WHERE fk_contrat =".((int) $this->id);
  1840. if ($status >= 0) {
  1841. $sql .= " AND statut = ".((int) $status);
  1842. }
  1843. dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG);
  1844. $resql = $this->db->query($sql);
  1845. if ($resql) {
  1846. $num = $this->db->num_rows($resql);
  1847. $i = 0;
  1848. while ($i < $num) {
  1849. $obj = $this->db->fetch_object($resql);
  1850. $tab[$i] = $obj->rowid;
  1851. $i++;
  1852. }
  1853. return $tab;
  1854. } else {
  1855. $this->error = $this->db->error();
  1856. return -1;
  1857. }
  1858. }
  1859. /**
  1860. * Return list of other contracts for same company than current contract
  1861. *
  1862. * @param string $option 'all' or 'others'
  1863. * @return array|int Array of contracts id or <0 if error
  1864. */
  1865. public function getListOfContracts($option = 'all')
  1866. {
  1867. $tab = array();
  1868. $sql = "SELECT c.rowid, c.ref";
  1869. $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
  1870. $sql .= " WHERE fk_soc =".((int) $this->socid);
  1871. if ($option == 'others') {
  1872. $sql .= " AND c.rowid <> ".((int) $this->id);
  1873. }
  1874. dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG);
  1875. $resql = $this->db->query($sql);
  1876. if ($resql) {
  1877. $num = $this->db->num_rows($resql);
  1878. $i = 0;
  1879. while ($i < $num) {
  1880. $obj = $this->db->fetch_object($resql);
  1881. $contrat = new Contrat($this->db);
  1882. $contrat->fetch($obj->rowid);
  1883. $tab[] = $contrat;
  1884. $i++;
  1885. }
  1886. return $tab;
  1887. } else {
  1888. $this->error = $this->db->error();
  1889. return -1;
  1890. }
  1891. }
  1892. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1893. /**
  1894. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1895. *
  1896. * @param User $user Objet user
  1897. * @param string $mode "inactive" pour services a activer, "expired" pour services expires
  1898. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1899. */
  1900. public function load_board($user, $mode)
  1901. {
  1902. // phpcs:enable
  1903. global $conf, $langs;
  1904. $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c";
  1905. $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd";
  1906. $this->from .= ", ".MAIN_DB_PREFIX."societe as s";
  1907. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1908. $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1909. }
  1910. if ($mode == 'inactive') {
  1911. $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin";
  1912. $sql .= $this->from;
  1913. $sql .= " WHERE c.statut = 1";
  1914. $sql .= " AND c.rowid = cd.fk_contrat";
  1915. $sql .= " AND cd.statut = 0";
  1916. } elseif ($mode == 'expired') {
  1917. $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
  1918. $sql .= $this->from;
  1919. $sql .= " WHERE c.statut = 1";
  1920. $sql .= " AND c.rowid = cd.fk_contrat";
  1921. $sql .= " AND cd.statut = 4";
  1922. $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'";
  1923. } elseif ($mode == 'active') {
  1924. $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin";
  1925. $sql .= $this->from;
  1926. $sql .= " WHERE c.statut = 1";
  1927. $sql .= " AND c.rowid = cd.fk_contrat";
  1928. $sql .= " AND cd.statut = 4";
  1929. //$datetouse = dol_now();
  1930. //$sql.= " AND cd.date_fin_validite < '".$this->db->idate($datetouse)."'";
  1931. }
  1932. $sql .= " AND c.fk_soc = s.rowid";
  1933. $sql .= " AND c.entity = ".((int) $conf->entity);
  1934. if ($user->socid) {
  1935. $sql .= " AND c.fk_soc = ".((int) $user->socid);
  1936. }
  1937. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1938. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1939. }
  1940. $resql = $this->db->query($sql);
  1941. if ($resql) {
  1942. $langs->load("contracts");
  1943. $now = dol_now();
  1944. if ($mode == 'inactive') {
  1945. $warning_delay = $conf->contrat->services->inactifs->warning_delay;
  1946. $label = $langs->trans("BoardNotActivatedServices");
  1947. $labelShort = $langs->trans("BoardNotActivatedServicesShort");
  1948. $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=0&sortfield=cd.date_fin_validite&sortorder=asc';
  1949. } elseif ($mode == 'expired') {
  1950. $warning_delay = $conf->contrat->services->expires->warning_delay;
  1951. $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&filter=expired&sortfield=cd.date_fin_validite&sortorder=asc';
  1952. $label = $langs->trans("BoardExpiredServices");
  1953. $labelShort = $langs->trans("BoardExpiredServicesShort");
  1954. } else {
  1955. $warning_delay = $conf->contrat->services->expires->warning_delay;
  1956. $url = DOL_URL_ROOT.'/contrat/services_list.php?mainmenu=commercial&leftmenu=contracts&mode=4&sortfield=cd.date_fin_validite&sortorder=asc';
  1957. //$url.= '&op2day='.$arraydatetouse['mday'].'&op2month='.$arraydatetouse['mon'].'&op2year='.$arraydatetouse['year'];
  1958. //if ($warning_delay >= 0) $url.='&amp;filter=expired';
  1959. $label = $langs->trans("BoardRunningServices");
  1960. $labelShort = $langs->trans("BoardRunningServicesShort");
  1961. }
  1962. $response = new WorkboardResponse();
  1963. $response->warning_delay = $warning_delay / 60 / 60 / 24;
  1964. $response->label = $label;
  1965. $response->labelShort = $labelShort;
  1966. $response->url = $url;
  1967. $response->img = img_object('', "contract");
  1968. while ($obj = $this->db->fetch_object($resql)) {
  1969. $response->nbtodo++;
  1970. if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) {
  1971. $response->nbtodolate++;
  1972. }
  1973. }
  1974. return $response;
  1975. } else {
  1976. dol_print_error($this->db);
  1977. $this->error = $this->db->error();
  1978. return -1;
  1979. }
  1980. }
  1981. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1982. /**
  1983. * Charge indicateurs this->nb de tableau de bord
  1984. *
  1985. * @return int <0 si ko, >0 si ok
  1986. */
  1987. public function load_state_board()
  1988. {
  1989. // phpcs:enable
  1990. global $conf, $user;
  1991. $this->nb = array();
  1992. $clause = "WHERE";
  1993. $sql = "SELECT count(c.rowid) as nb";
  1994. $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c";
  1995. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid";
  1996. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1997. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  1998. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  1999. $clause = "AND";
  2000. }
  2001. $sql .= " ".$clause." c.entity = ".$conf->entity;
  2002. $resql = $this->db->query($sql);
  2003. if ($resql) {
  2004. while ($obj = $this->db->fetch_object($resql)) {
  2005. $this->nb["contracts"] = $obj->nb;
  2006. }
  2007. $this->db->free($resql);
  2008. return 1;
  2009. } else {
  2010. dol_print_error($this->db);
  2011. $this->error = $this->db->error();
  2012. return -1;
  2013. }
  2014. }
  2015. /* gestion des contacts d'un contrat */
  2016. /**
  2017. * Return id des contacts clients de facturation
  2018. *
  2019. * @return array Liste des id contacts facturation
  2020. */
  2021. public function getIdBillingContact()
  2022. {
  2023. return $this->getIdContact('external', 'BILLING');
  2024. }
  2025. /**
  2026. * Return id des contacts clients de prestation
  2027. *
  2028. * @return array Liste des id contacts prestation
  2029. */
  2030. public function getIdServiceContact()
  2031. {
  2032. return $this->getIdContact('external', 'SERVICE');
  2033. }
  2034. /**
  2035. * Initialise an instance with random values.
  2036. * Used to build previews or test instances.
  2037. * id must be 0 if object instance is a specimen.
  2038. *
  2039. * @return void
  2040. */
  2041. public function initAsSpecimen()
  2042. {
  2043. global $user, $langs, $conf;
  2044. // Load array of products prodids
  2045. $num_prods = 0;
  2046. $prodids = array();
  2047. $sql = "SELECT rowid";
  2048. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  2049. $sql .= " WHERE entity IN (".getEntity('product').")";
  2050. $sql .= " AND tosell = 1";
  2051. $sql .= $this->db->plimit(100);
  2052. $resql = $this->db->query($sql);
  2053. if ($resql) {
  2054. $num_prods = $this->db->num_rows($resql);
  2055. $i = 0;
  2056. while ($i < $num_prods) {
  2057. $i++;
  2058. $row = $this->db->fetch_row($resql);
  2059. $prodids[$i] = $row[0];
  2060. }
  2061. }
  2062. // Initialise parametres
  2063. $this->id = 0;
  2064. $this->specimen = 1;
  2065. $this->ref = 'SPECIMEN';
  2066. $this->ref_customer = 'SPECIMENCUST';
  2067. $this->ref_supplier = 'SPECIMENSUPP';
  2068. $this->socid = 1;
  2069. $this->statut = 0;
  2070. $this->date_creation = (dol_now() - 3600 * 24 * 7);
  2071. $this->date_contrat = dol_now();
  2072. $this->commercial_signature_id = 1;
  2073. $this->commercial_suivi_id = 1;
  2074. $this->note_private = 'This is a comment (private)';
  2075. $this->note_public = 'This is a comment (public)';
  2076. $this->fk_projet = 0;
  2077. // Lines
  2078. $nbp = 5;
  2079. $xnbp = 0;
  2080. while ($xnbp < $nbp) {
  2081. $line = new ContratLigne($this->db);
  2082. $line->qty = 1;
  2083. $line->subprice = 100;
  2084. $line->price = 100;
  2085. $line->tva_tx = 19.6;
  2086. $line->remise_percent = 10;
  2087. $line->total_ht = 90;
  2088. $line->total_ttc = 107.64; // 90 * 1.196
  2089. $line->total_tva = 17.64;
  2090. $line->date_start = dol_now() - 500000;
  2091. $line->date_start_real = dol_now() - 200000;
  2092. $line->date_end = dol_now() + 500000;
  2093. $line->date_end_real = dol_now() - 100000;
  2094. if ($num_prods > 0) {
  2095. $prodid = mt_rand(1, $num_prods);
  2096. $line->fk_product = $prodids[$prodid];
  2097. }
  2098. $this->lines[$xnbp] = $line;
  2099. $xnbp++;
  2100. }
  2101. }
  2102. /**
  2103. * Create an array of order lines
  2104. *
  2105. * @return int >0 if OK, <0 if KO
  2106. */
  2107. public function getLinesArray()
  2108. {
  2109. return $this->fetch_lines();
  2110. }
  2111. /**
  2112. * Create a document onto disk according to template module.
  2113. *
  2114. * @param string $modele Force model to use ('' to not force)
  2115. * @param Translate $outputlangs Object langs to use for output
  2116. * @param int $hidedetails Hide details of lines
  2117. * @param int $hidedesc Hide description
  2118. * @param int $hideref Hide ref
  2119. * @param null|array $moreparams Array to provide more information
  2120. * @return int 0 if KO, 1 if OK
  2121. */
  2122. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  2123. {
  2124. global $conf, $langs;
  2125. $langs->load("contracts");
  2126. $outputlangs->load("products");
  2127. if (!dol_strlen($modele)) {
  2128. $modele = 'strato';
  2129. if (!empty($this->model_pdf)) {
  2130. $modele = $this->model_pdf;
  2131. } elseif (!empty($this->modelpdf)) { // deprecated
  2132. $modele = $this->modelpdf;
  2133. } elseif (!empty($conf->global->CONTRACT_ADDON_PDF)) {
  2134. $modele = $conf->global->CONTRACT_ADDON_PDF;
  2135. }
  2136. }
  2137. $modelpath = "core/modules/contract/doc/";
  2138. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  2139. }
  2140. /**
  2141. * Function used to replace a thirdparty id with another one.
  2142. *
  2143. * @param DoliDB $db Database handler
  2144. * @param int $origin_id Old thirdparty id
  2145. * @param int $dest_id New thirdparty id
  2146. * @return bool
  2147. */
  2148. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  2149. {
  2150. $tables = array(
  2151. 'contrat'
  2152. );
  2153. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  2154. }
  2155. /**
  2156. * Load an object from its id and create a new one in database
  2157. *
  2158. * @param User $user User making the clone
  2159. * @param int $socid Id of thirdparty
  2160. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2161. * @return int New id of clone
  2162. */
  2163. public function createFromClone(User $user, $socid = 0, $notrigger = 0)
  2164. {
  2165. global $db, $langs, $conf, $hookmanager, $extrafields;
  2166. dol_include_once('/projet/class/project.class.php');
  2167. $error = 0;
  2168. $this->fetch($this->id);
  2169. // Load dest object
  2170. $clonedObj = clone $this;
  2171. $clonedObj->socid = $socid;
  2172. $this->db->begin();
  2173. $objsoc = new Societe($this->db);
  2174. $objsoc->fetch($clonedObj->socid);
  2175. // Clean data
  2176. $clonedObj->statut = 0;
  2177. // Clean extrafields
  2178. if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) {
  2179. $extrafields->fetch_name_optionals_label($this->table_element);
  2180. foreach ($clonedObj->array_options as $key => $option) {
  2181. $shortkey = preg_replace('/options_/', '', $key);
  2182. //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]);
  2183. if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
  2184. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  2185. unset($clonedObj->array_options[$key]);
  2186. }
  2187. }
  2188. }
  2189. if (empty($conf->global->CONTRACT_ADDON) || !is_readable(DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.".php")) {
  2190. $this->error = 'ErrorSetupNotComplete';
  2191. dol_syslog($this->error);
  2192. return -1;
  2193. }
  2194. // Set ref
  2195. require_once DOL_DOCUMENT_ROOT."/core/modules/contract/".$conf->global->CONTRACT_ADDON.'.php';
  2196. $obj = $conf->global->CONTRACT_ADDON;
  2197. $modContract = new $obj();
  2198. $clonedObj->ref = $modContract->getNextValue($objsoc, $clonedObj);
  2199. // get extrafields so they will be clone
  2200. foreach ($this->lines as $line) {
  2201. $line->fetch_optionals($line->id);
  2202. }
  2203. // Create clone
  2204. $clonedObj->context['createfromclone'] = 'createfromclone';
  2205. $result = $clonedObj->create($user);
  2206. if ($result < 0) {
  2207. $error++;
  2208. $this->error = $clonedObj->error;
  2209. $this->errors[] = $clonedObj->error;
  2210. } else {
  2211. // copy external contacts if same company
  2212. if ($this->socid == $clonedObj->socid) {
  2213. if ($clonedObj->copy_linked_contact($this, 'external') < 0) {
  2214. $error++;
  2215. }
  2216. }
  2217. }
  2218. if (!$error) {
  2219. foreach ($this->lines as $line) {
  2220. $result = $clonedObj->addline($line->description, $line->subprice, $line->qty, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, $line->fk_product, $line->remise_percent, $line->date_ouverture, $line->date_cloture, 'HT', 0, $line->info_bits, $line->fk_fournprice, $line->pa_ht, $line->array_options, $line->fk_unit);
  2221. if ($result < 0) {
  2222. $error++;
  2223. $this->error = $clonedObj->error;
  2224. $this->errors[] = $clonedObj->error;
  2225. }
  2226. }
  2227. }
  2228. if (!$error) {
  2229. // Hook of thirdparty module
  2230. if (is_object($hookmanager)) {
  2231. $parameters = array(
  2232. 'objFrom' => $this,
  2233. 'clonedObj' => $clonedObj
  2234. );
  2235. $action = '';
  2236. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks
  2237. if ($reshook < 0) {
  2238. $error++;
  2239. }
  2240. }
  2241. }
  2242. unset($clonedObj->context['createfromclone']);
  2243. // End
  2244. if (!$error) {
  2245. $this->db->commit();
  2246. return $clonedObj->id;
  2247. } else {
  2248. $this->db->rollback();
  2249. return -1;
  2250. }
  2251. }
  2252. }
  2253. /**
  2254. * Class to manage lines of contracts
  2255. */
  2256. class ContratLigne extends CommonObjectLine
  2257. {
  2258. /**
  2259. * @var string ID to identify managed object
  2260. */
  2261. public $element = 'contratdet';
  2262. /**
  2263. * @var string Name of table without prefix where object is stored
  2264. */
  2265. public $table_element = 'contratdet';
  2266. /**
  2267. * @var int ID
  2268. */
  2269. public $id;
  2270. /**
  2271. * @var string Ref
  2272. */
  2273. public $ref;
  2274. public $tms;
  2275. /**
  2276. * @var int ID
  2277. */
  2278. public $fk_contrat;
  2279. /**
  2280. * @var int ID
  2281. */
  2282. public $fk_product;
  2283. public $statut; // 0 inactive, 4 active, 5 closed
  2284. public $type; // 0 for product, 1 for service
  2285. /**
  2286. * @var string
  2287. * @deprecated
  2288. */
  2289. public $label;
  2290. /**
  2291. * @var string
  2292. * @deprecated
  2293. */
  2294. public $libelle;
  2295. /**
  2296. * @var string description
  2297. */
  2298. public $description;
  2299. public $product_type; // 0 for product, 1 for service
  2300. public $product_ref;
  2301. public $product_label;
  2302. public $date_commande;
  2303. public $date_start; // date start planned
  2304. public $date_start_real; // date start real
  2305. public $date_end; // date end planned
  2306. public $date_end_real; // date end real
  2307. // For backward compatibility
  2308. /**
  2309. * @deprecated Use date_start
  2310. */
  2311. public $date_ouverture_prevue; // date start planned
  2312. /**
  2313. * @deprecated Use date_start_real
  2314. */
  2315. public $date_ouverture; // date start real
  2316. /**
  2317. * @deprecated Use date_end
  2318. */
  2319. public $date_fin_validite; // date end planned
  2320. /**
  2321. * @deprecated Use date_end_real
  2322. */
  2323. public $date_cloture; // date end real
  2324. public $tva_tx;
  2325. public $localtax1_tx;
  2326. public $localtax2_tx;
  2327. public $localtax1_type; // Local tax 1 type
  2328. public $localtax2_type; // Local tax 2 type
  2329. public $qty;
  2330. public $remise_percent;
  2331. public $remise;
  2332. /**
  2333. * @var int ID
  2334. */
  2335. public $fk_remise_except;
  2336. public $subprice; // Unit price HT
  2337. /**
  2338. * @var float
  2339. * @deprecated Use $price_ht instead
  2340. * @see $price_ht
  2341. */
  2342. public $price;
  2343. public $price_ht;
  2344. public $total_ht;
  2345. public $total_tva;
  2346. public $total_localtax1;
  2347. public $total_localtax2;
  2348. public $total_ttc;
  2349. /**
  2350. * @var int ID
  2351. */
  2352. public $fk_fournprice;
  2353. public $pa_ht;
  2354. public $info_bits;
  2355. /**
  2356. * @var int ID
  2357. */
  2358. public $fk_user_author;
  2359. /**
  2360. * @var int ID
  2361. */
  2362. public $fk_user_ouverture;
  2363. /**
  2364. * @var int ID
  2365. */
  2366. public $fk_user_cloture;
  2367. public $commentaire;
  2368. const STATUS_INITIAL = 0;
  2369. const STATUS_OPEN = 4;
  2370. const STATUS_CLOSED = 5;
  2371. /**
  2372. * Constructor
  2373. *
  2374. * @param DoliDb $db Database handler
  2375. */
  2376. public function __construct($db)
  2377. {
  2378. $this->db = $db;
  2379. }
  2380. /**
  2381. * Return label of this contract line status
  2382. *
  2383. * @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
  2384. * @return string Label of status
  2385. */
  2386. public function getLibStatut($mode)
  2387. {
  2388. return $this->LibStatut($this->statut, $mode, ((!empty($this->date_fin_validite)) ? ($this->date_fin_validite < dol_now() ? 1 : 0) : -1));
  2389. }
  2390. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2391. /**
  2392. * Return label of a contract line status
  2393. *
  2394. * @param int $status Id status
  2395. * @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
  2396. * @param int $expired 0=Not expired, 1=Expired, -1=Both or unknown
  2397. * @param string $moreatt More attribute
  2398. * @return string Label of status
  2399. */
  2400. public static function LibStatut($status, $mode, $expired = -1, $moreatt = '')
  2401. {
  2402. // phpcs:enable
  2403. global $langs;
  2404. $langs->load("contracts");
  2405. if ($status == self::STATUS_INITIAL) {
  2406. $labelStatus = $langs->transnoentities("ServiceStatusInitial");
  2407. $labelStatusShort = $langs->transnoentities("ServiceStatusInitial");
  2408. } elseif ($status == self::STATUS_OPEN && $expired == -1) {
  2409. $labelStatus = $langs->transnoentities("ServiceStatusRunning");
  2410. $labelStatusShort = $langs->transnoentities("ServiceStatusRunning");
  2411. } elseif ($status == self::STATUS_OPEN && $expired == 0) {
  2412. $labelStatus = $langs->transnoentities("ServiceStatusNotLate");
  2413. $labelStatusShort = $langs->transnoentities("ServiceStatusNotLateShort");
  2414. } elseif ($status == self::STATUS_OPEN && $expired == 1) {
  2415. $labelStatus = $langs->transnoentities("ServiceStatusLate");
  2416. $labelStatusShort = $langs->transnoentities("ServiceStatusLateShort");
  2417. } elseif ($status == self::STATUS_CLOSED) {
  2418. $labelStatus = $langs->transnoentities("ServiceStatusClosed");
  2419. $labelStatusShort = $langs->transnoentities("ServiceStatusClosed");
  2420. }
  2421. $statusType = 'status'.$status;
  2422. if ($status == self::STATUS_OPEN && $expired == 1) {
  2423. $statusType = 'status1';
  2424. }
  2425. if ($status == self::STATUS_CLOSED) {
  2426. $statusType = 'status6';
  2427. }
  2428. $params = array(); $reg = array();
  2429. if (preg_match('/class="(.*)"/', $moreatt, $reg)) {
  2430. $params = array('badgeParams'=>array('css' => $reg[1]));
  2431. }
  2432. return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params);
  2433. }
  2434. /**
  2435. * Return clicable name (with picto eventually)
  2436. *
  2437. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  2438. * @param int $maxlength Max length
  2439. * @return string Chaine avec URL
  2440. */
  2441. public function getNomUrl($withpicto = 0, $maxlength = 0)
  2442. {
  2443. global $langs;
  2444. $result = '';
  2445. $label = $langs->trans("ShowContractOfService").': '.$this->label;
  2446. if (empty($label)) {
  2447. $label = $this->description;
  2448. }
  2449. $link = '<a href="'.DOL_URL_ROOT.'/contrat/card.php?id='.$this->fk_contrat.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  2450. $linkend = '</a>';
  2451. $picto = 'service';
  2452. if ($this->type == 0) {
  2453. $picto = 'product';
  2454. }
  2455. if ($withpicto) {
  2456. $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
  2457. }
  2458. if ($withpicto && $withpicto != 2) {
  2459. $result .= ' ';
  2460. }
  2461. if ($withpicto != 2) {
  2462. $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend;
  2463. }
  2464. return $result;
  2465. }
  2466. /**
  2467. * Load object in memory from database
  2468. *
  2469. * @param int $id Id object
  2470. * @param string $ref Ref of contract line
  2471. * @return int <0 if KO, >0 if OK
  2472. */
  2473. public function fetch($id, $ref = '')
  2474. {
  2475. // Check parameters
  2476. if (empty($id) && empty($ref)) {
  2477. return -1;
  2478. }
  2479. $sql = "SELECT";
  2480. $sql .= " t.rowid,";
  2481. $sql .= " t.tms,";
  2482. $sql .= " t.fk_contrat,";
  2483. $sql .= " t.fk_product,";
  2484. $sql .= " t.statut,";
  2485. $sql .= " t.label,"; // This field is not used. Only label of product
  2486. $sql .= " p.ref as product_ref,";
  2487. $sql .= " p.label as product_label,";
  2488. $sql .= " p.description as product_desc,";
  2489. $sql .= " p.fk_product_type as product_type,";
  2490. $sql .= " t.description,";
  2491. $sql .= " t.date_commande,";
  2492. $sql .= " t.date_ouverture_prevue as date_ouverture_prevue,";
  2493. $sql .= " t.date_ouverture as date_ouverture,";
  2494. $sql .= " t.date_fin_validite as date_fin_validite,";
  2495. $sql .= " t.date_cloture as date_cloture,";
  2496. $sql .= " t.tva_tx,";
  2497. $sql .= " t.vat_src_code,";
  2498. $sql .= " t.localtax1_tx,";
  2499. $sql .= " t.localtax2_tx,";
  2500. $sql .= " t.localtax1_type,";
  2501. $sql .= " t.localtax2_type,";
  2502. $sql .= " t.qty,";
  2503. $sql .= " t.remise_percent,";
  2504. $sql .= " t.remise,";
  2505. $sql .= " t.fk_remise_except,";
  2506. $sql .= " t.subprice,";
  2507. $sql .= " t.price_ht,";
  2508. $sql .= " t.total_ht,";
  2509. $sql .= " t.total_tva,";
  2510. $sql .= " t.total_localtax1,";
  2511. $sql .= " t.total_localtax2,";
  2512. $sql .= " t.total_ttc,";
  2513. $sql .= " t.fk_product_fournisseur_price as fk_fournprice,";
  2514. $sql .= " t.buy_price_ht as pa_ht,";
  2515. $sql .= " t.info_bits,";
  2516. $sql .= " t.fk_user_author,";
  2517. $sql .= " t.fk_user_ouverture,";
  2518. $sql .= " t.fk_user_cloture,";
  2519. $sql .= " t.commentaire,";
  2520. $sql .= " t.fk_unit";
  2521. $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product";
  2522. if ($id) {
  2523. $sql .= " WHERE t.rowid = ".((int) $id);
  2524. }
  2525. if ($ref) {
  2526. $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'";
  2527. }
  2528. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  2529. $resql = $this->db->query($sql);
  2530. if ($resql) {
  2531. if ($this->db->num_rows($resql)) {
  2532. $obj = $this->db->fetch_object($resql);
  2533. $this->id = $obj->rowid;
  2534. $this->ref = $obj->rowid;
  2535. $this->tms = $this->db->jdate($obj->tms);
  2536. $this->fk_contrat = $obj->fk_contrat;
  2537. $this->fk_product = $obj->fk_product;
  2538. $this->statut = $obj->statut;
  2539. $this->product_ref = $obj->product_ref;
  2540. $this->product_label = $obj->product_label;
  2541. $this->product_description = $obj->product_description;
  2542. $this->product_type = $obj->product_type;
  2543. $this->label = $obj->label; // deprecated. We do not use this field. Only ref and label of product, and description of contract line
  2544. $this->description = $obj->description;
  2545. $this->date_commande = $this->db->jdate($obj->date_commande);
  2546. $this->date_start = $this->db->jdate($obj->date_ouverture_prevue);
  2547. $this->date_start_real = $this->db->jdate($obj->date_ouverture);
  2548. $this->date_end = $this->db->jdate($obj->date_fin_validite);
  2549. $this->date_end_real = $this->db->jdate($obj->date_cloture);
  2550. // For backward compatibility
  2551. $this->date_ouverture_prevue = $this->db->jdate($obj->date_ouverture_prevue);
  2552. $this->date_ouverture = $this->db->jdate($obj->date_ouverture);
  2553. $this->date_fin_validite = $this->db->jdate($obj->date_fin_validite);
  2554. $this->date_cloture = $this->db->jdate($obj->date_cloture);
  2555. $this->tva_tx = $obj->tva_tx;
  2556. $this->vat_src_code = $obj->vat_src_code;
  2557. $this->localtax1_tx = $obj->localtax1_tx;
  2558. $this->localtax2_tx = $obj->localtax2_tx;
  2559. $this->localtax1_type = $obj->localtax1_type;
  2560. $this->localtax2_type = $obj->localtax2_type;
  2561. $this->qty = $obj->qty;
  2562. $this->remise_percent = $obj->remise_percent;
  2563. $this->remise = $obj->remise;
  2564. $this->fk_remise_except = $obj->fk_remise_except;
  2565. $this->subprice = $obj->subprice;
  2566. $this->price_ht = $obj->price_ht;
  2567. $this->total_ht = $obj->total_ht;
  2568. $this->total_tva = $obj->total_tva;
  2569. $this->total_localtax1 = $obj->total_localtax1;
  2570. $this->total_localtax2 = $obj->total_localtax2;
  2571. $this->total_ttc = $obj->total_ttc;
  2572. $this->info_bits = $obj->info_bits;
  2573. $this->fk_user_author = $obj->fk_user_author;
  2574. $this->fk_user_ouverture = $obj->fk_user_ouverture;
  2575. $this->fk_user_cloture = $obj->fk_user_cloture;
  2576. $this->commentaire = $obj->commentaire;
  2577. $this->fk_fournprice = $obj->fk_fournprice;
  2578. $marginInfos = getMarginInfos($obj->subprice, $obj->remise_percent, $obj->tva_tx, $obj->localtax1_tx, $obj->localtax2_tx, $this->fk_fournprice, $obj->pa_ht);
  2579. $this->pa_ht = $marginInfos[0];
  2580. $this->fk_unit = $obj->fk_unit;
  2581. $this->fetch_optionals();
  2582. }
  2583. $this->db->free($resql);
  2584. return 1;
  2585. } else {
  2586. $this->error = "Error ".$this->db->lasterror();
  2587. return -1;
  2588. }
  2589. }
  2590. /**
  2591. * Update database for contract line
  2592. *
  2593. * @param User $user User that modify
  2594. * @param int $notrigger 0=no, 1=yes (no update trigger)
  2595. * @return int <0 if KO, >0 if OK
  2596. */
  2597. public function update($user, $notrigger = 0)
  2598. {
  2599. global $conf, $langs, $mysoc;
  2600. $error = 0;
  2601. // Clean parameters
  2602. $this->fk_contrat = (int) $this->fk_contrat;
  2603. $this->fk_product = (int) $this->fk_product;
  2604. $this->statut = (int) $this->statut;
  2605. $this->label = trim($this->label);
  2606. $this->description = trim($this->description);
  2607. $this->vat_src_code = trim($this->vat_src_code);
  2608. $this->tva_tx = trim($this->tva_tx);
  2609. $this->localtax1_tx = trim($this->localtax1_tx);
  2610. $this->localtax2_tx = trim($this->localtax2_tx);
  2611. $this->qty = trim($this->qty);
  2612. $this->remise_percent = trim($this->remise_percent);
  2613. $this->remise = trim($this->remise);
  2614. $this->fk_remise_except = (int) $this->fk_remise_except;
  2615. $this->subprice = price2num($this->subprice);
  2616. $this->price_ht = price2num($this->price_ht);
  2617. $this->total_ht = trim($this->total_ht);
  2618. $this->total_tva = trim($this->total_tva);
  2619. $this->total_localtax1 = trim($this->total_localtax1);
  2620. $this->total_localtax2 = trim($this->total_localtax2);
  2621. $this->total_ttc = trim($this->total_ttc);
  2622. $this->info_bits = trim($this->info_bits);
  2623. $this->fk_user_author = (int) $this->fk_user_author;
  2624. $this->fk_user_ouverture = (int) $this->fk_user_ouverture;
  2625. $this->fk_user_cloture = (int) $this->fk_user_cloture;
  2626. $this->commentaire = trim($this->commentaire);
  2627. //if (empty($this->subprice)) $this->subprice = 0;
  2628. if (empty($this->price_ht)) {
  2629. $this->price_ht = 0;
  2630. }
  2631. if (empty($this->total_ht)) {
  2632. $this->total_ht = 0;
  2633. }
  2634. if (empty($this->total_tva)) {
  2635. $this->total_tva = 0;
  2636. }
  2637. if (empty($this->total_ttc)) {
  2638. $this->total_ttc = 0;
  2639. }
  2640. if (empty($this->localtax1_tx)) {
  2641. $this->localtax1_tx = 0;
  2642. }
  2643. if (empty($this->localtax2_tx)) {
  2644. $this->localtax2_tx = 0;
  2645. }
  2646. if (empty($this->remise_percent)) {
  2647. $this->remise_percent = 0;
  2648. }
  2649. // For backward compatibility
  2650. if (empty($this->date_start)) {
  2651. $this->date_start = $this->date_ouverture_prevue;
  2652. }
  2653. if (empty($this->date_start_real)) {
  2654. $this->date_start = $this->date_ouverture;
  2655. }
  2656. if (empty($this->date_end)) {
  2657. $this->date_start = $this->date_fin_validite;
  2658. }
  2659. if (empty($this->date_end_real)) {
  2660. $this->date_start = $this->date_cloture;
  2661. }
  2662. // Check parameters
  2663. // Put here code to add control on parameters values
  2664. // Calcul du total TTC et de la TVA pour la ligne a partir de
  2665. // qty, pu, remise_percent et txtva
  2666. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2667. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2668. $localtaxes_type = getLocalTaxesFromRate($this->txtva, 0, $this->societe, $mysoc);
  2669. $tabprice = calcul_price_total($this->qty, $this->price_ht, $this->remise_percent, $this->tva_tx, $this->localtax1_tx, $this->localtax2_tx, 0, 'HT', 0, 1, $mysoc, $localtaxes_type);
  2670. $this->total_ht = $tabprice[0];
  2671. $this->total_tva = $tabprice[1];
  2672. $this->total_ttc = $tabprice[2];
  2673. $this->total_localtax1 = $tabprice[9];
  2674. $this->total_localtax2 = $tabprice[10];
  2675. if (empty($this->pa_ht)) {
  2676. $this->pa_ht = 0;
  2677. }
  2678. // if buy price not defined, define buyprice as configured in margin admin
  2679. if ($this->pa_ht == 0) {
  2680. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
  2681. return $result;
  2682. } else {
  2683. $this->pa_ht = $result;
  2684. }
  2685. }
  2686. $this->db->begin();
  2687. $this->oldcopy = new ContratLigne($this->db);
  2688. $this->oldcopy->fetch($this->id);
  2689. // Update request
  2690. $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
  2691. $sql .= " fk_contrat=".((int) $this->fk_contrat).",";
  2692. $sql .= " fk_product=".($this->fk_product ? "'".$this->db->escape($this->fk_product)."'" : 'null').",";
  2693. $sql .= " statut=".((int) $this->statut).",";
  2694. $sql .= " label='".$this->db->escape($this->label)."',";
  2695. $sql .= " description='".$this->db->escape($this->description)."',";
  2696. $sql .= " date_commande=".($this->date_commande != '' ? "'".$this->db->idate($this->date_commande)."'" : "null").",";
  2697. $sql .= " date_ouverture_prevue=".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null").",";
  2698. $sql .= " date_ouverture=".($this->date_ouverture != '' ? "'".$this->db->idate($this->date_ouverture)."'" : "null").",";
  2699. $sql .= " date_fin_validite=".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null").",";
  2700. $sql .= " date_cloture=".($this->date_cloture != '' ? "'".$this->db->idate($this->date_cloture)."'" : "null").",";
  2701. $sql .= " vat_src_code='".$this->db->escape($this->vat_src_code)."',";
  2702. $sql .= " tva_tx=".price2num($this->tva_tx).",";
  2703. $sql .= " localtax1_tx=".price2num($this->localtax1_tx).",";
  2704. $sql .= " localtax2_tx=".price2num($this->localtax2_tx).",";
  2705. $sql .= " qty=".price2num($this->qty).",";
  2706. $sql .= " remise_percent=".price2num($this->remise_percent).",";
  2707. $sql .= " remise=".($this->remise ?price2num($this->remise) : "null").",";
  2708. $sql .= " fk_remise_except=".($this->fk_remise_except > 0 ? $this->fk_remise_except : "null").",";
  2709. $sql .= " subprice=".($this->subprice != '' ? $this->subprice : "null").",";
  2710. $sql .= " price_ht=".($this->price_ht != '' ? $this->price_ht : "null").",";
  2711. $sql .= " total_ht=".$this->total_ht.",";
  2712. $sql .= " total_tva=".$this->total_tva.",";
  2713. $sql .= " total_localtax1=".$this->total_localtax1.",";
  2714. $sql .= " total_localtax2=".$this->total_localtax2.",";
  2715. $sql .= " total_ttc=".$this->total_ttc.",";
  2716. $sql .= " fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? $this->fk_fournprice : "NULL").",";
  2717. $sql .= " buy_price_ht='".price2num($this->pa_ht)."',";
  2718. $sql .= " info_bits='".$this->db->escape($this->info_bits)."',";
  2719. $sql .= " fk_user_author=".($this->fk_user_author >= 0 ? $this->fk_user_author : "NULL").",";
  2720. $sql .= " fk_user_ouverture=".($this->fk_user_ouverture > 0 ? $this->fk_user_ouverture : "NULL").",";
  2721. $sql .= " fk_user_cloture=".($this->fk_user_cloture > 0 ? $this->fk_user_cloture : "NULL").",";
  2722. $sql .= " commentaire='".$this->db->escape($this->commentaire)."',";
  2723. $sql .= " fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  2724. $sql .= " WHERE rowid=".((int) $this->id);
  2725. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  2726. $resql = $this->db->query($sql);
  2727. if (!$resql) {
  2728. $this->error = "Error ".$this->db->lasterror();
  2729. $error++;
  2730. }
  2731. if (!$error) { // For avoid conflicts if trigger used
  2732. $result = $this->insertExtraFields();
  2733. if ($result < 0) {
  2734. $error++;
  2735. }
  2736. }
  2737. // If we change a planned date (start or end), sync dates for all services
  2738. if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) {
  2739. if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) {
  2740. $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
  2741. $sql .= " date_ouverture_prevue = ".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null");
  2742. $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
  2743. $resql = $this->db->query($sql);
  2744. if (!$resql) {
  2745. $error++;
  2746. $this->error = "Error ".$this->db->lasterror();
  2747. }
  2748. }
  2749. if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) {
  2750. $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET';
  2751. $sql .= " date_fin_validite = ".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null");
  2752. $sql .= " WHERE fk_contrat = ".((int) $this->fk_contrat);
  2753. $resql = $this->db->query($sql);
  2754. if (!$resql) {
  2755. $error++;
  2756. $this->error = "Error ".$this->db->lasterror();
  2757. }
  2758. }
  2759. }
  2760. if (!$error && !$notrigger) {
  2761. // Call trigger
  2762. $result = $this->call_trigger('LINECONTRACT_UPDATE', $user);
  2763. if ($result < 0) {
  2764. $error++;
  2765. $this->db->rollback();
  2766. }
  2767. // End call triggers
  2768. }
  2769. if (!$error) {
  2770. $this->db->commit();
  2771. return 1;
  2772. } else {
  2773. $this->db->rollback();
  2774. $this->errors[] = $this->error;
  2775. return -1;
  2776. }
  2777. }
  2778. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2779. /**
  2780. * Mise a jour en base des champs total_xxx de ligne
  2781. * Used by migration process
  2782. *
  2783. * @return int <0 if KO, >0 if OK
  2784. */
  2785. public function update_total()
  2786. {
  2787. // phpcs:enable
  2788. $this->db->begin();
  2789. // Mise a jour ligne en base
  2790. $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET";
  2791. $sql .= " total_ht=".price2num($this->total_ht, 'MT')."";
  2792. $sql .= ",total_tva=".price2num($this->total_tva, 'MT')."";
  2793. $sql .= ",total_localtax1=".price2num($this->total_localtax1, 'MT')."";
  2794. $sql .= ",total_localtax2=".price2num($this->total_localtax2, 'MT')."";
  2795. $sql .= ",total_ttc=".price2num($this->total_ttc, 'MT')."";
  2796. $sql .= " WHERE rowid = ".((int) $this->id);
  2797. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  2798. $resql = $this->db->query($sql);
  2799. if ($resql) {
  2800. $this->db->commit();
  2801. return 1;
  2802. } else {
  2803. $this->error = $this->db->error();
  2804. $this->db->rollback();
  2805. return -2;
  2806. }
  2807. }
  2808. /**
  2809. * Inserts a contrat line into database
  2810. *
  2811. * @param int $notrigger Set to 1 if you don't want triggers to be fired
  2812. * @return int <0 if KO, >0 if OK
  2813. */
  2814. public function insert($notrigger = 0)
  2815. {
  2816. global $conf, $user;
  2817. $error = 0;
  2818. // Insertion dans la base
  2819. $sql = "INSERT INTO ".MAIN_DB_PREFIX."contratdet";
  2820. $sql .= " (fk_contrat, label, description, fk_product, qty, vat_src_code, tva_tx,";
  2821. $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, remise_percent, subprice,";
  2822. $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,";
  2823. $sql .= " info_bits,";
  2824. $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht";
  2825. if ($this->date_ouverture_prevue > 0) {
  2826. $sql .= ",date_ouverture_prevue";
  2827. }
  2828. if ($this->date_fin_validite > 0) {
  2829. $sql .= ",date_fin_validite";
  2830. }
  2831. $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',";
  2832. $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").",";
  2833. $sql .= " '".$this->db->escape($this->qty)."',";
  2834. $sql .= " '".$this->db->escape($this->vat_src_code)."',";
  2835. $sql .= " '".$this->db->escape($this->tva_tx)."',";
  2836. $sql .= " '".$this->db->escape($this->localtax1_tx)."',";
  2837. $sql .= " '".$this->db->escape($this->localtax2_tx)."',";
  2838. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  2839. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  2840. $sql .= " ".price2num($this->remise_percent).",".price2num($this->subprice).",";
  2841. $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).",";
  2842. $sql .= " '".$this->db->escape($this->info_bits)."',";
  2843. $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).",";
  2844. if ($this->fk_fournprice > 0) {
  2845. $sql .= ' '.((int) $this->fk_fournprice).',';
  2846. } else {
  2847. $sql .= ' null,';
  2848. }
  2849. if ($this->pa_ht > 0) {
  2850. $sql .= ' '.((float) price2num($this->pa_ht));
  2851. } else {
  2852. $sql .= ' null';
  2853. }
  2854. if ($this->date_ouverture > 0) {
  2855. $sql .= ",'".$this->db->idate($this->date_ouverture)."'";
  2856. }
  2857. if ($this->date_cloture > 0) {
  2858. $sql .= ",'".$this->db->idate($this->date_cloture)."'";
  2859. }
  2860. $sql .= ")";
  2861. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  2862. $resql = $this->db->query($sql);
  2863. if ($resql) {
  2864. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet');
  2865. // Insert of extrafields
  2866. if (!$error) {
  2867. $result = $this->insertExtraFields();
  2868. if ($result < 0) {
  2869. $this->db->rollback();
  2870. return -1;
  2871. }
  2872. }
  2873. if (!$notrigger) {
  2874. // Call trigger
  2875. $result = $this->call_trigger('LINECONTRACT_INSERT', $user);
  2876. if ($result < 0) {
  2877. $this->db->rollback();
  2878. return -1;
  2879. }
  2880. // End call triggers
  2881. }
  2882. $this->db->commit();
  2883. return 1;
  2884. } else {
  2885. $this->db->rollback();
  2886. $this->error = $this->db->error()." sql=".$sql;
  2887. return -1;
  2888. }
  2889. }
  2890. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2891. /**
  2892. * Activate a contract line
  2893. *
  2894. * @param User $user Objet User who activate contract
  2895. * @param int $date Date activation
  2896. * @param int|string $date_end Date planned end. Use '-1' to keep it unchanged.
  2897. * @param string $comment A comment typed by user
  2898. * @return int <0 if KO, >0 if OK
  2899. */
  2900. public function active_line($user, $date, $date_end = '', $comment = '')
  2901. {
  2902. // phpcs:enable
  2903. global $langs, $conf;
  2904. $error = 0;
  2905. $this->db->begin();
  2906. $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".ContratLigne::STATUS_OPEN.",";
  2907. $sql .= " date_ouverture = ".(dol_strlen($date) != 0 ? "'".$this->db->idate($date)."'" : "null").",";
  2908. if ($date_end >= 0) {
  2909. $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").",";
  2910. }
  2911. $sql .= " fk_user_ouverture = ".((int) $user->id).",";
  2912. $sql .= " date_cloture = null,";
  2913. $sql .= " commentaire = '".$this->db->escape($comment)."'";
  2914. $sql .= " WHERE rowid = ".((int) $this->id)." AND (statut = ".ContratLigne::STATUS_INITIAL." OR statut = ".ContratLigne::STATUS_CLOSED.")";
  2915. dol_syslog(get_class($this)."::active_line", LOG_DEBUG);
  2916. $resql = $this->db->query($sql);
  2917. if ($resql) {
  2918. // Call trigger
  2919. $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user);
  2920. if ($result < 0) {
  2921. $error++;
  2922. }
  2923. // End call triggers
  2924. if (!$error) {
  2925. $this->statut = ContratLigne::STATUS_OPEN;
  2926. $this->date_ouverture = $date;
  2927. $this->date_fin_validite = $date_end;
  2928. $this->fk_user_ouverture = $user->id;
  2929. $this->date_cloture = null;
  2930. $this->commentaire = $comment;
  2931. $this->db->commit();
  2932. return 1;
  2933. } else {
  2934. $this->db->rollback();
  2935. return -1;
  2936. }
  2937. } else {
  2938. $this->error = $this->db->lasterror();
  2939. $this->db->rollback();
  2940. return -1;
  2941. }
  2942. }
  2943. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2944. /**
  2945. * Close a contract line
  2946. *
  2947. * @param User $user Objet User who close contract
  2948. * @param int $date_end Date end
  2949. * @param string $comment A comment typed by user
  2950. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  2951. * @return int <0 if KO, >0 if OK
  2952. */
  2953. public function close_line($user, $date_end, $comment = '', $notrigger = 0)
  2954. {
  2955. // phpcs:enable
  2956. global $langs, $conf;
  2957. // Update object
  2958. $this->date_cloture = $date_end;
  2959. $this->fk_user_cloture = $user->id;
  2960. $this->commentaire = $comment;
  2961. $error = 0;
  2962. // statut actif : 4
  2963. $this->db->begin();
  2964. $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".((int) ContratLigne::STATUS_CLOSED).",";
  2965. $sql .= " date_cloture = '".$this->db->idate($date_end)."',";
  2966. $sql .= " fk_user_cloture = ".((int) $user->id).",";
  2967. $sql .= " commentaire = '".$this->db->escape($comment)."'";
  2968. $sql .= " WHERE rowid = ".((int) $this->id)." AND statut = ".((int) ContratLigne::STATUS_OPEN);
  2969. $resql = $this->db->query($sql);
  2970. if ($resql) {
  2971. if (!$notrigger) {
  2972. // Call trigger
  2973. $result = $this->call_trigger('LINECONTRACT_CLOSE', $user);
  2974. if ($result < 0) {
  2975. $error++;
  2976. $this->db->rollback();
  2977. return -1;
  2978. }
  2979. // End call triggers
  2980. }
  2981. $this->db->commit();
  2982. return 1;
  2983. } else {
  2984. $this->error = $this->db->lasterror();
  2985. $this->db->rollback();
  2986. return -1;
  2987. }
  2988. }
  2989. }