contrat.class.php 123 KB

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