contrat.class.php 86 KB

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