contrat.class.php 130 KB

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