contrat.class.php 115 KB

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