contrat.class.php 122 KB

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