contrat.class.php 98 KB

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