card.php 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  1. <?php
  2. /* Copyright (C) 2003-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2019 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2010-2017 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
  8. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  9. * Copyright (C) 2014-2020 Ferran Marcet <fmarcet@2byte.es>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/contrat/card.php
  29. * \ingroup contrat
  30. * \brief Page of a contract
  31. */
  32. require "../main.inc.php";
  33. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/lib/contract.lib.php';
  36. require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  42. if (!empty($conf->propal->enabled)) {
  43. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  44. }
  45. if (!empty($conf->projet->enabled)) {
  46. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  47. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  48. }
  49. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  50. // Load translation files required by the page
  51. $langs->loadLangs(array("contracts", "orders", "companies", "bills", "products", 'compta'));
  52. $action = GETPOST('action', 'aZ09');
  53. $confirm = GETPOST('confirm', 'alpha');
  54. $cancel = GETPOST('cancel', 'alpha');
  55. $socid = GETPOST('socid', 'int');
  56. $id = GETPOST('id', 'int');
  57. $ref = GETPOST('ref', 'alpha');
  58. $origin = GETPOST('origin', 'alpha');
  59. $originid = GETPOST('originid', 'int');
  60. $datecontrat = '';
  61. $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  62. // Security check
  63. if ($user->socid) {
  64. $socid = $user->socid;
  65. }
  66. $result = restrictedArea($user, 'contrat', $id);
  67. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  68. $hookmanager->initHooks(array('contractcard', 'globalcard'));
  69. $object = new Contrat($db);
  70. $extrafields = new ExtraFields($db);
  71. // Load object
  72. if ($id > 0 || !empty($ref) && $action != 'add') {
  73. $ret = $object->fetch($id, $ref);
  74. if ($ret > 0) {
  75. $ret = $object->fetch_thirdparty();
  76. }
  77. if ($ret < 0) {
  78. dol_print_error('', $object->error);
  79. }
  80. }
  81. // fetch optionals attributes and labels
  82. $extrafields->fetch_name_optionals_label($object->table_element);
  83. // fetch optionals attributes lines and labels
  84. $extralabelslines = $extrafields->fetch_name_optionals_label($object->table_element_line);
  85. $permissionnote = $user->rights->contrat->creer; // Used by the include of actions_setnotes.inc.php
  86. $permissiondellink = $user->rights->contrat->creer; // Used by the include of actions_dellink.inc.php
  87. $error = 0;
  88. /*
  89. * Actions
  90. */
  91. $parameters = array('socid' => $socid);
  92. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  93. if ($reshook < 0) {
  94. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  95. }
  96. if (empty($reshook)) {
  97. $backurlforlist = DOL_URL_ROOT.'/contrat/list.php';
  98. if (empty($backtopage) || ($cancel && empty($id))) {
  99. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  100. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  101. $backtopage = $backurlforlist;
  102. } else {
  103. $backtopage = DOL_URL_ROOT.'/contrat/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  104. }
  105. }
  106. }
  107. if ($cancel) {
  108. if (!empty($backtopageforcancel)) {
  109. header("Location: ".$backtopageforcancel);
  110. exit;
  111. } elseif (!empty($backtopage)) {
  112. header("Location: ".$backtopage);
  113. exit;
  114. }
  115. $action = '';
  116. }
  117. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once
  118. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  119. if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) {
  120. $result = $object->active_line($user, GETPOST('ligne', 'int'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment'));
  121. if ($result > 0) {
  122. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  123. exit;
  124. } else {
  125. setEventMessages($object->error, $object->errors, 'errors');
  126. }
  127. } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) {
  128. if (!GETPOST('dateend')) {
  129. $error++;
  130. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors');
  131. }
  132. if (!$error) {
  133. $result = $object->close_line($user, GETPOST('ligne', 'int'), GETPOST('dateend'), urldecode(GETPOST('comment')));
  134. if ($result > 0) {
  135. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  136. exit;
  137. } else {
  138. setEventMessages($object->error, $object->errors, 'errors');
  139. }
  140. }
  141. }
  142. // Si ajout champ produit predefini
  143. if (GETPOST('mode') == 'predefined') {
  144. $date_start = '';
  145. $date_end = '';
  146. if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) {
  147. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  148. }
  149. if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) {
  150. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  151. }
  152. }
  153. // Param dates
  154. $date_start_update = '';
  155. $date_end_update = '';
  156. $date_start_real_update = '';
  157. $date_end_real_update = '';
  158. if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) {
  159. $date_start_update = dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear'));
  160. }
  161. if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) {
  162. $date_end_update = dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear'));
  163. }
  164. if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) {
  165. $date_start_real_update = dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear'));
  166. }
  167. if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) {
  168. $date_end_real_update = dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear'));
  169. }
  170. if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) {
  171. $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  172. }
  173. // Add contract
  174. if ($action == 'add' && $user->rights->contrat->creer) {
  175. // Check
  176. if (empty($datecontrat)) {
  177. $error++;
  178. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  179. $action = 'create';
  180. }
  181. if ($socid < 1) {
  182. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors');
  183. $action = 'create';
  184. $error++;
  185. }
  186. // Fill array 'array_options' with data from add form
  187. $ret = $extrafields->setOptionalsFromPost(null, $object);
  188. if ($ret < 0) {
  189. $error++;
  190. $action = 'create';
  191. }
  192. if (!$error) {
  193. $object->socid = $socid;
  194. $object->date_contrat = $datecontrat;
  195. $object->commercial_suivi_id = GETPOST('commercial_suivi_id', 'int');
  196. $object->commercial_signature_id = GETPOST('commercial_signature_id', 'int');
  197. $object->note_private = GETPOST('note_private', 'alpha');
  198. $object->note_public = GETPOST('note_public', 'alpha');
  199. $object->fk_project = GETPOST('projectid', 'int');
  200. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  201. $object->ref = GETPOST('ref', 'alpha');
  202. $object->ref_customer = GETPOST('ref_customer', 'alpha');
  203. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  204. // If creation from another object of another module (Example: origin=propal, originid=1)
  205. if (!empty($origin) && !empty($originid)) {
  206. // Parse element/subelement (ex: project_task)
  207. $element = $subelement = $origin;
  208. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  209. $element = $regs[1];
  210. $subelement = $regs[2];
  211. }
  212. // For compatibility
  213. if ($element == 'order') {
  214. $element = $subelement = 'commande';
  215. }
  216. if ($element == 'propal') {
  217. $element = 'comm/propal'; $subelement = 'propal';
  218. }
  219. if ($element == 'invoice' || $element == 'facture') {
  220. $element = 'compta/facture';
  221. $subelement = 'facture';
  222. }
  223. $object->origin = $origin;
  224. $object->origin_id = $originid;
  225. // Possibility to add external linked objects with hooks
  226. $object->linked_objects[$object->origin] = $object->origin_id;
  227. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  228. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  229. }
  230. $id = $object->create($user);
  231. if ($id < 0) {
  232. setEventMessages($object->error, $object->errors, 'errors');
  233. }
  234. if ($id > 0) {
  235. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  236. $classname = ucfirst($subelement);
  237. $srcobject = new $classname($db);
  238. dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
  239. $result = $srcobject->fetch($object->origin_id);
  240. if ($result > 0) {
  241. $srcobject->fetch_thirdparty();
  242. $lines = $srcobject->lines;
  243. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  244. $srcobject->fetch_lines();
  245. $lines = $srcobject->lines;
  246. }
  247. $fk_parent_line = 0;
  248. $num = count($lines);
  249. for ($i = 0; $i < $num; $i++) {
  250. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  251. if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee
  252. // service prédéfini
  253. if ($lines[$i]->fk_product > 0) {
  254. $product_static = new Product($db);
  255. // Define output language
  256. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  257. $prod = new Product($db);
  258. $prod->id = $lines[$i]->fk_product;
  259. $prod->getMultiLangs();
  260. $outputlangs = $langs;
  261. $newlang = '';
  262. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  263. $newlang = GETPOST('lang_id', 'aZ09');
  264. }
  265. if (empty($newlang)) {
  266. $newlang = $srcobject->thirdparty->default_lang;
  267. }
  268. if (!empty($newlang)) {
  269. $outputlangs = new Translate("", $conf);
  270. $outputlangs->setDefaultLang($newlang);
  271. }
  272. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
  273. } else {
  274. $label = $lines[$i]->product_label;
  275. }
  276. $desc = ($lines[$i]->desc && $lines[$i]->desc != $lines[$i]->libelle) ?dol_htmlentitiesbr($lines[$i]->desc) : '';
  277. } else {
  278. $desc = dol_htmlentitiesbr($lines[$i]->desc);
  279. }
  280. // Extrafields
  281. $array_options = array();
  282. // For avoid conflicts if trigger used
  283. if (method_exists($lines[$i], 'fetch_optionals')) {
  284. $lines[$i]->fetch_optionals();
  285. $array_options = $lines[$i]->array_options;
  286. }
  287. $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx.' ('.$lines[$i]->vat_src_code.')' : $lines[$i]->tva_tx;
  288. // View third's localtaxes for now
  289. $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
  290. $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
  291. $result = $object->addline(
  292. $desc,
  293. $lines[$i]->subprice,
  294. $lines[$i]->qty,
  295. $txtva,
  296. $localtax1_tx,
  297. $localtax2_tx,
  298. $lines[$i]->fk_product,
  299. $lines[$i]->remise_percent,
  300. $lines[$i]->date_start,
  301. $lines[$i]->date_end,
  302. 'HT',
  303. 0,
  304. $lines[$i]->info_bits,
  305. $lines[$i]->fk_fournprice,
  306. $lines[$i]->pa_ht,
  307. $array_options,
  308. $lines[$i]->fk_unit
  309. );
  310. if ($result < 0) {
  311. $error++;
  312. break;
  313. }
  314. }
  315. }
  316. } else {
  317. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  318. $error++;
  319. }
  320. // Hooks
  321. $parameters = array('objFrom' => $srcobject);
  322. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  323. // modified by hook
  324. if ($reshook < 0) {
  325. $error++;
  326. }
  327. } else {
  328. setEventMessages($object->error, $object->errors, 'errors');
  329. $error++;
  330. }
  331. } else {
  332. $result = $object->create($user);
  333. if ($result > 0) {
  334. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  335. exit;
  336. } else {
  337. setEventMessages($object->error, $object->errors, 'errors');
  338. }
  339. $action = 'create';
  340. }
  341. }
  342. } elseif ($action == 'classin' && $user->rights->contrat->creer) {
  343. $object->setProject(GETPOST('projectid'));
  344. } elseif ($action == 'addline' && $user->rights->contrat->creer) {
  345. // Add a new line
  346. // Set if we used free entry or predefined product
  347. $predef = '';
  348. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  349. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  350. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  351. if (GETPOST('prod_entry_mode', 'alpha') == 'free') {
  352. $idprod = 0;
  353. $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0);
  354. } else {
  355. $idprod = GETPOST('idprod', 'int');
  356. $tva_tx = '';
  357. }
  358. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  359. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), 2) : 0);
  360. if ($qty == '') {
  361. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
  362. $error++;
  363. }
  364. if (GETPOST('prod_entry_mode', 'alpha') == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
  365. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
  366. $error++;
  367. }
  368. $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
  369. $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
  370. if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) {
  371. setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
  372. $error++;
  373. }
  374. // Extrafields
  375. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  376. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  377. // Unset extrafield
  378. if (is_array($extralabelsline)) {
  379. // Get extra fields
  380. foreach ($extralabelsline as $key => $value) {
  381. unset($_POST["options_".$key]);
  382. }
  383. }
  384. if (!$error) {
  385. // Clean parameters
  386. $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year'));
  387. $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year'));
  388. $price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT');
  389. // Ecrase $pu par celui du produit
  390. // Ecrase $desc par celui du produit
  391. // Ecrase $tva_tx par celui du produit
  392. // Ecrase $base_price_type par celui du produit
  393. if ($idprod > 0) {
  394. $prod = new Product($db);
  395. $prod->fetch($idprod);
  396. // Update if prices fields are defined
  397. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  398. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  399. if (empty($tva_tx)) {
  400. $tva_npr = 0;
  401. }
  402. $pu_ht = $prod->price;
  403. $pu_ttc = $prod->price_ttc;
  404. $price_min = $prod->price_min;
  405. $price_base_type = $prod->price_base_type;
  406. // On defini prix unitaire
  407. if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) {
  408. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  409. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  410. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  411. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  412. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  413. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  414. $prodcustprice = new Productcustomerprice($db);
  415. $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
  416. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  417. if ($result) {
  418. if (count($prodcustprice->lines) > 0) {
  419. $pu_ht = price($prodcustprice->lines [0]->price);
  420. $pu_ttc = price($prodcustprice->lines [0]->price_ttc);
  421. $price_base_type = $prodcustprice->lines [0]->price_base_type;
  422. $tva_tx = $prodcustprice->lines [0]->tva_tx;
  423. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  424. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  425. }
  426. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  427. if (empty($tva_tx)) {
  428. $tva_npr = 0;
  429. }
  430. }
  431. }
  432. }
  433. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  434. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  435. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  436. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  437. if ($tmpvat != $tmpprodvat) {
  438. if ($price_base_type != 'HT') {
  439. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  440. } else {
  441. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  442. }
  443. }
  444. $desc = $prod->description;
  445. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  446. if ($product_desc == $desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  447. $product_desc = '';
  448. }
  449. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  450. $desc = $product_desc;
  451. } else {
  452. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  453. }
  454. $fk_unit = $prod->fk_unit;
  455. } else {
  456. $pu_ht = GETPOST('price_ht');
  457. $price_base_type = 'HT';
  458. $tva_tx = GETPOST('tva_tx') ?str_replace('*', '', GETPOST('tva_tx')) : 0; // tva_tx field may be disabled, so we use vat rate 0
  459. $tva_npr = preg_match('/\*/', GETPOST('tva_tx')) ? 1 : 0;
  460. $desc = $product_desc;
  461. $fk_unit = GETPOST('units', 'alpha');
  462. }
  463. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  464. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  465. // ajout prix achat
  466. $fk_fournprice = GETPOST('fournprice');
  467. if (GETPOST('buying_price')) {
  468. $pa_ht = GETPOST('buying_price');
  469. } else {
  470. $pa_ht = null;
  471. }
  472. $info_bits = 0;
  473. if ($tva_npr) {
  474. $info_bits |= 0x01;
  475. }
  476. if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance))
  477. || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) {
  478. $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  479. $result = -1;
  480. } else {
  481. // Insert line
  482. $result = $object->addline(
  483. $desc,
  484. $pu_ht,
  485. $qty,
  486. $tva_tx,
  487. $localtax1_tx,
  488. $localtax2_tx,
  489. $idprod,
  490. $remise_percent,
  491. $date_start,
  492. $date_end,
  493. $price_base_type,
  494. $pu_ttc,
  495. $info_bits,
  496. $fk_fournprice,
  497. $pa_ht,
  498. $array_options,
  499. $fk_unit
  500. );
  501. }
  502. if ($result > 0) {
  503. // Define output language
  504. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) { // No generation if default type not defined
  505. $outputlangs = $langs;
  506. $newlang = '';
  507. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  508. $newlang = GETPOST('lang_id', 'aZ09');
  509. }
  510. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  511. $newlang = $object->thirdparty->default_lang;
  512. }
  513. if (!empty($newlang)) {
  514. $outputlangs = new Translate("", $conf);
  515. $outputlangs->setDefaultLang($newlang);
  516. }
  517. $ret = $object->fetch($id); // Reload to get new records
  518. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  519. }
  520. unset($_POST['prod_entry_mode']);
  521. unset($_POST['qty']);
  522. unset($_POST['type']);
  523. unset($_POST['remise_percent']);
  524. unset($_POST['price_ht']);
  525. unset($_POST['multicurrency_price_ht']);
  526. unset($_POST['price_ttc']);
  527. unset($_POST['tva_tx']);
  528. unset($_POST['product_ref']);
  529. unset($_POST['product_label']);
  530. unset($_POST['product_desc']);
  531. unset($_POST['fournprice']);
  532. unset($_POST['buying_price']);
  533. unset($_POST['np_marginRate']);
  534. unset($_POST['np_markRate']);
  535. unset($_POST['dp_desc']);
  536. unset($_POST['idprod']);
  537. unset($_POST['date_starthour']);
  538. unset($_POST['date_startmin']);
  539. unset($_POST['date_startsec']);
  540. unset($_POST['date_startday']);
  541. unset($_POST['date_startmonth']);
  542. unset($_POST['date_startyear']);
  543. unset($_POST['date_endhour']);
  544. unset($_POST['date_endmin']);
  545. unset($_POST['date_endsec']);
  546. unset($_POST['date_endday']);
  547. unset($_POST['date_endmonth']);
  548. unset($_POST['date_endyear']);
  549. } else {
  550. setEventMessages($object->error, $object->errors, 'errors');
  551. }
  552. }
  553. } elseif ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha')) {
  554. $error = 0;
  555. if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) {
  556. setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
  557. $action = 'editline';
  558. $_GET['rowid'] = GETPOST('elrowid');
  559. $error++;
  560. }
  561. if (!$error) {
  562. $objectline = new ContratLigne($db);
  563. if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) {
  564. setEventMessages($objectline->error, $objectline->errors, 'errors');
  565. $error++;
  566. }
  567. $objectline->fetch_optionals();
  568. }
  569. $db->begin();
  570. if (!$error) {
  571. if ($date_start_real_update == '') {
  572. $date_start_real_update = $objectline->date_ouverture;
  573. }
  574. if ($date_end_real_update == '') {
  575. $date_end_real_update = $objectline->date_cloture;
  576. }
  577. $vat_rate = GETPOST('eltva_tx');
  578. // Define info_bits
  579. $info_bits = 0;
  580. if (preg_match('/\*/', $vat_rate)) {
  581. $info_bits |= 0x01;
  582. }
  583. // Define vat_rate
  584. $vat_rate = str_replace('*', '', $vat_rate);
  585. $localtax1_tx = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  586. $localtax2_tx = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  587. $txtva = $vat_rate;
  588. // Clean vat code
  589. $reg = array();
  590. $vat_src_code = '';
  591. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  592. $vat_src_code = $reg[1];
  593. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  594. }
  595. // ajout prix d'achat
  596. if (GETPOST('buying_price')) {
  597. $pa_ht = price2num(GETPOST('buying_price'), '', 2);
  598. } else {
  599. $pa_ht = null;
  600. }
  601. $fk_unit = GETPOST('unit', 'alpha');
  602. $objectline->fk_product = GETPOST('idprod', 'int');
  603. $objectline->description = GETPOST('product_desc', 'restricthtml');
  604. $objectline->price_ht = price2num(GETPOST('elprice'), 'MU');
  605. $objectline->subprice = price2num(GETPOST('elprice'), 'MU');
  606. $objectline->qty = price2num(GETPOST('elqty'), 'MS');
  607. $objectline->remise_percent = price2num(GETPOST('elremise_percent'), 2);
  608. $objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0
  609. $objectline->vat_src_code = $vat_src_code;
  610. $objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0;
  611. $objectline->localtax2_tx = is_numeric($localtax2_tx) ? $localtax2_tx : 0;
  612. $objectline->date_ouverture_prevue = $date_start_update;
  613. $objectline->date_ouverture = $date_start_real_update;
  614. $objectline->date_fin_validite = $date_end_update;
  615. $objectline->date_cloture = $date_end_real_update;
  616. $objectline->fk_user_cloture = $user->id;
  617. $objectline->fk_fournprice = $fk_fournprice;
  618. $objectline->pa_ht = $pa_ht;
  619. if ($fk_unit > 0) {
  620. $objectline->fk_unit = GETPOST('unit');
  621. } else {
  622. $objectline->fk_unit = null;
  623. }
  624. // Extrafields
  625. $extralabelsline = $extrafields->fetch_name_optionals_label($objectline->table_element);
  626. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  627. if (is_array($array_options) && count($array_options) > 0) {
  628. // We replace values in this->line->array_options only for entries defined into $array_options
  629. foreach ($array_options as $key => $value) {
  630. $objectline->array_options[$key] = $array_options[$key];
  631. }
  632. }
  633. // TODO verifier price_min si fk_product et multiprix
  634. $result = $objectline->update($user);
  635. if ($result < 0) {
  636. $error++;
  637. setEventMessages($objectline->error, $objectline->errors, 'errors');
  638. }
  639. }
  640. if (!$error) {
  641. $db->commit();
  642. } else {
  643. $db->rollback();
  644. }
  645. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) {
  646. $result = $object->deleteline(GETPOST('lineid', 'int'), $user);
  647. if ($result >= 0) {
  648. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  649. exit;
  650. } else {
  651. setEventMessages($object->error, $object->errors, 'errors');
  652. }
  653. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) {
  654. $result = $object->validate($user);
  655. if ($result > 0) {
  656. // Define output language
  657. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  658. $outputlangs = $langs;
  659. $newlang = '';
  660. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  661. $newlang = GETPOST('lang_id', 'aZ09');
  662. }
  663. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  664. $newlang = $object->thirdparty->default_lang;
  665. }
  666. if (!empty($newlang)) {
  667. $outputlangs = new Translate("", $conf);
  668. $outputlangs->setDefaultLang($newlang);
  669. }
  670. $model = $object->model_pdf;
  671. $ret = $object->fetch($id); // Reload to get new records
  672. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  673. }
  674. } else {
  675. setEventMessages($object->error, $object->errors, 'errors');
  676. }
  677. } elseif ($action == 'reopen' && $user->rights->contrat->creer) {
  678. $result = $object->reopen($user);
  679. if ($result < 0) {
  680. setEventMessages($object->error, $object->errors, 'errors');
  681. }
  682. } elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) {
  683. // Close all lines
  684. $result = $object->closeAll($user);
  685. if ($result < 0) {
  686. setEventMessages($object->error, $object->errors, 'errors');
  687. }
  688. } elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) {
  689. // Close all lines
  690. $result = $object->activateAll($user);
  691. if ($result < 0) {
  692. setEventMessages($object->error, $object->errors, 'errors');
  693. }
  694. } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) {
  695. $result = $object->delete($user);
  696. if ($result >= 0) {
  697. header("Location: list.php?restore_lastsearch_values=1");
  698. return;
  699. } else {
  700. setEventMessages($object->error, $object->errors, 'errors');
  701. }
  702. } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer) {
  703. if (GETPOST('newcid') > 0) {
  704. $contractline = new ContratLigne($db);
  705. $result = $contractline->fetch(GETPOSTINT('lineid'));
  706. $contractline->fk_contrat = GETPOSTINT('newcid');
  707. $result = $contractline->update($user, 1);
  708. if ($result >= 0) {
  709. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  710. return;
  711. } else {
  712. setEventMessages($object->error, $object->errors, 'errors');
  713. }
  714. } else {
  715. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
  716. }
  717. } elseif ($action == 'update_extras') {
  718. $object->oldcopy = dol_clone($object);
  719. // Fill array 'array_options' with data from update form
  720. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  721. if ($ret < 0) {
  722. $error++;
  723. }
  724. if (!$error) {
  725. $result = $object->insertExtraFields('CONTRACT_MODIFY');
  726. if ($result < 0) {
  727. setEventMessages($object->error, $object->errors, 'errors');
  728. $error++;
  729. }
  730. }
  731. if ($error) {
  732. $action = 'edit_extras';
  733. }
  734. } elseif ($action == 'setref_supplier') {
  735. if (!$cancel) {
  736. $object->oldcopy = dol_clone($object);
  737. $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  738. if ($result < 0) {
  739. setEventMessages($object->error, $object->errors, 'errors');
  740. $action = 'editref_supplier';
  741. } else {
  742. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  743. exit;
  744. }
  745. } else {
  746. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  747. exit;
  748. }
  749. } elseif ($action == 'setref_customer') {
  750. if (!$cancel) {
  751. $object->oldcopy = dol_clone($object);
  752. $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  753. if ($result < 0) {
  754. setEventMessages($object->error, $object->errors, 'errors');
  755. $action = 'editref_customer';
  756. } else {
  757. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  758. exit;
  759. }
  760. } else {
  761. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  762. exit;
  763. }
  764. } elseif ($action == 'setref') {
  765. if (!$cancel) {
  766. $result = $object->fetch($id);
  767. if ($result < 0) {
  768. setEventMessages($object->error, $object->errors, 'errors');
  769. }
  770. $old_ref = $object->ref;
  771. $result = $object->setValueFrom('ref', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  772. if ($result < 0) {
  773. setEventMessages($object->error, $object->errors, 'errors');
  774. $action = 'editref';
  775. } else {
  776. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  777. $old_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($old_ref);
  778. $new_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
  779. $files = dol_dir_list($old_filedir);
  780. if (!empty($files)) {
  781. if (!is_dir($new_filedir)) {
  782. dol_mkdir($new_filedir);
  783. }
  784. foreach ($files as $file) {
  785. dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
  786. }
  787. }
  788. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  789. exit;
  790. }
  791. } else {
  792. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  793. exit;
  794. }
  795. } elseif ($action == 'setdate_contrat') {
  796. if (!$cancel) {
  797. $result = $object->fetch($id);
  798. if ($result < 0) {
  799. setEventMessages($object->error, $object->errors, 'errors');
  800. }
  801. $datacontrat = dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
  802. $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
  803. if ($result < 0) {
  804. setEventMessages($object->error, $object->errors, 'errors');
  805. $action = 'editdate_contrat';
  806. } else {
  807. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  808. exit;
  809. }
  810. } else {
  811. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  812. exit;
  813. }
  814. }
  815. // Actions when printing a doc from card
  816. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  817. // Actions to build doc
  818. $upload_dir = $conf->contrat->multidir_output[$object->entity];
  819. $permissiontoadd = $user->rights->contrat->creer;
  820. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  821. // Actions to send emails
  822. $triggersendname = 'CONTRACT_SENTBYMAIL';
  823. $paramname = 'id';
  824. $mode = 'emailfromcontract';
  825. $trackid = 'con'.$object->id;
  826. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  827. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) {
  828. if ($action == 'addcontact') {
  829. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  830. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  831. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  832. if ($result >= 0) {
  833. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  834. exit;
  835. } else {
  836. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  837. $langs->load("errors");
  838. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  839. } else {
  840. setEventMessages($object->error, $object->errors, 'errors');
  841. }
  842. }
  843. } elseif ($action == 'swapstatut') {
  844. // bascule du statut d'un contact
  845. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  846. } elseif ($action == 'deletecontact') {
  847. // Efface un contact
  848. $result = $object->delete_contact(GETPOST('lineid', 'int'));
  849. if ($result >= 0) {
  850. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  851. exit;
  852. } else {
  853. setEventMessages($object->error, $object->errors, 'errors');
  854. }
  855. }
  856. }
  857. // Action clone object
  858. if ($action == 'confirm_clone' && $confirm == 'yes') {
  859. if (!GETPOST('socid', 3)) {
  860. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  861. } else {
  862. if ($object->id > 0) {
  863. $result = $object->createFromClone($user, $socid);
  864. if ($result > 0) {
  865. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  866. exit();
  867. } else {
  868. if (count($object->errors) > 0) {
  869. setEventMessages($object->error, $object->errors, 'errors');
  870. }
  871. $action = '';
  872. }
  873. }
  874. }
  875. }
  876. }
  877. /*
  878. * View
  879. */
  880. $help_url = 'EN:Module_Contracts|FR:Module_Contrat';
  881. llxHeader('', $langs->trans("Contract"), $help_url);
  882. $form = new Form($db);
  883. $formfile = new FormFile($db);
  884. if (!empty($conf->projet->enabled)) {
  885. $formproject = new FormProjets($db);
  886. }
  887. // Load object modContract
  888. $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
  889. if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
  890. $module = substr($module, 0, dol_strlen($module) - 4);
  891. }
  892. $result = dol_include_once('/core/modules/contract/'.$module.'.php');
  893. if ($result > 0) {
  894. $modCodeContract = new $module();
  895. }
  896. // Create
  897. if ($action == 'create') {
  898. print load_fiche_titre($langs->trans('AddContract'), '', 'contract');
  899. $soc = new Societe($db);
  900. if ($socid > 0) {
  901. $soc->fetch($socid);
  902. }
  903. if (GETPOST('origin') && GETPOST('originid', 'int')) {
  904. // Parse element/subelement (ex: project_task)
  905. $regs = array();
  906. $element = $subelement = GETPOST('origin');
  907. if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) {
  908. $element = $regs[1];
  909. $subelement = $regs[2];
  910. }
  911. if ($element == 'project') {
  912. $projectid = GETPOST('originid', 'int');
  913. } else {
  914. // For compatibility
  915. if ($element == 'order' || $element == 'commande') {
  916. $element = $subelement = 'commande';
  917. }
  918. if ($element == 'propal') {
  919. $element = 'comm/propal'; $subelement = 'propal';
  920. }
  921. if ($element == 'invoice' || $element == 'facture') {
  922. $element = 'compta/facture';
  923. $subelement = 'facture';
  924. }
  925. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  926. $classname = ucfirst($subelement);
  927. $objectsrc = new $classname($db);
  928. $objectsrc->fetch($originid);
  929. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  930. $objectsrc->fetch_lines();
  931. }
  932. $objectsrc->fetch_thirdparty();
  933. // Replicate extrafields
  934. $objectsrc->fetch_optionals();
  935. $object->array_options = $objectsrc->array_options;
  936. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  937. $soc = $objectsrc->thirdparty;
  938. $note_private = (!empty($objectsrc->note_private) ? $objectsrc->note_private : '');
  939. $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : '');
  940. // Object source contacts list
  941. $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
  942. }
  943. } else {
  944. $projectid = GETPOST('projectid', 'int');
  945. $note_private = GETPOST("note_private");
  946. $note_public = GETPOST("note_public");
  947. }
  948. $object->date_contrat = dol_now();
  949. print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  950. print '<input type="hidden" name="token" value="'.newToken().'">';
  951. print '<input type="hidden" name="action" value="add">';
  952. print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
  953. print '<input type="hidden" name="remise_percent" value="0">';
  954. print dol_get_fiche_head();
  955. print '<table class="border centpercent">';
  956. // Ref
  957. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
  958. if (!empty($modCodeContract->code_auto)) {
  959. $tmpcode = $langs->trans("Draft");
  960. } else {
  961. $tmpcode = '<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref') ?GETPOST('ref') : $tmpcode).'">';
  962. }
  963. print $tmpcode;
  964. print '</td></tr>';
  965. // Ref customer
  966. print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
  967. print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer', 'alpha')).'"></td></tr>';
  968. // Ref supplier
  969. print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
  970. print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier', 'alpha')).'"></td></tr>';
  971. // Thirdparty
  972. print '<tr>';
  973. print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
  974. if ($socid > 0) {
  975. print '<td>';
  976. print $soc->getNomUrl(1);
  977. print '<input type="hidden" name="socid" value="'.$soc->id.'">';
  978. print '</td>';
  979. } else {
  980. print '<td>';
  981. print img_picto('', 'company', 'class="pictofixedwidth"');
  982. print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  983. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  984. print '</td>';
  985. }
  986. print '</tr>'."\n";
  987. if ($socid > 0) {
  988. // Ligne info remises tiers
  989. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  990. if ($soc->remise_percent) {
  991. print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent).' ';
  992. } else {
  993. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoRelativeDiscount").'. </span>';
  994. }
  995. $absolute_discount = $soc->getAvailableDiscounts();
  996. if ($absolute_discount) {
  997. print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)).'.';
  998. } else {
  999. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoAbsoluteDiscount").'.</span>';
  1000. }
  1001. print '</td></tr>';
  1002. }
  1003. // Commercial suivi
  1004. print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
  1005. print img_picto('', 'user', 'class="pictofixedwidth"');
  1006. print $form->select_dolusers(GETPOST("commercial_suivi_id") ?GETPOST("commercial_suivi_id") : $user->id, 'commercial_suivi_id', 1, '');
  1007. print '</td></tr>';
  1008. // Commercial signature
  1009. print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
  1010. print img_picto('', 'user', 'class="pictofixedwidth"');
  1011. print $form->select_dolusers(GETPOST("commercial_signature_id") ?GETPOST("commercial_signature_id") : $user->id, 'commercial_signature_id', 1, '');
  1012. print '</td></tr>';
  1013. print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
  1014. print $form->selectDate($datecontrat, '', 0, 0, '', "contrat");
  1015. print "</td></tr>";
  1016. // Project
  1017. if (!empty($conf->projet->enabled)) {
  1018. $langs->load('projects');
  1019. $formproject = new FormProjets($db);
  1020. print '<tr><td>'.$langs->trans("Project").'</td><td>';
  1021. $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, "projectid", 0, 0, 1, 1);
  1022. print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
  1023. print "</td></tr>";
  1024. }
  1025. print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
  1026. $doleditor = new DolEditor('note_public', $note_public, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  1027. print $doleditor->Create(1);
  1028. print '</td></tr>';
  1029. if (empty($user->socid)) {
  1030. print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
  1031. $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  1032. print $doleditor->Create(1);
  1033. print '</td></tr>';
  1034. }
  1035. // Other attributes
  1036. $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3');
  1037. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1038. print $hookmanager->resPrint;
  1039. // Other attributes
  1040. if (empty($reshook)) {
  1041. print $object->showOptionals($extrafields, 'create', $parameters);
  1042. }
  1043. print "</table>\n";
  1044. print dol_get_fiche_end();
  1045. print $form->buttonsSaveCancel("Create");
  1046. if (is_object($objectsrc)) {
  1047. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  1048. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  1049. if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) {
  1050. print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
  1051. }
  1052. }
  1053. print "</form>\n";
  1054. } else {
  1055. // View and edit mode
  1056. $now = dol_now();
  1057. if ($object->id > 0) {
  1058. $object->fetch_thirdparty();
  1059. $soc = $object->thirdparty; // $soc is used later
  1060. $result = $object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
  1061. if ($result < 0) {
  1062. dol_print_error($db, $object->error);
  1063. }
  1064. $nbofservices = count($object->lines);
  1065. $author = new User($db);
  1066. $author->fetch($object->user_author_id);
  1067. $commercial_signature = new User($db);
  1068. $commercial_signature->fetch($object->commercial_signature_id);
  1069. $commercial_suivi = new User($db);
  1070. $commercial_suivi->fetch($object->commercial_suivi_id);
  1071. $head = contract_prepare_head($object);
  1072. $hselected = 0;
  1073. $formconfirm = '';
  1074. print dol_get_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract');
  1075. if ($action == 'delete') {
  1076. //Confirmation de la suppression du contrat
  1077. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAContract"), $langs->trans("ConfirmDeleteAContract"), "confirm_delete", '', 0, 1);
  1078. } elseif ($action == 'valid') {
  1079. //Confirmation de la validation
  1080. $ref = substr($object->ref, 1, 4);
  1081. if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) {
  1082. $numref = $object->getNextNumRef($object->thirdparty);
  1083. } else {
  1084. $numref = $object->ref;
  1085. }
  1086. $text = $langs->trans('ConfirmValidateContract', $numref);
  1087. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ValidateAContract"), $text, "confirm_valid", '', 0, 1);
  1088. } elseif ($action == 'close') {
  1089. // Confirmation de la fermeture
  1090. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CloseAContract"), $langs->trans("ConfirmCloseContract"), "confirm_close", '', 0, 1);
  1091. } elseif ($action == 'activate') {
  1092. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ActivateAllOnContract"), $langs->trans("ConfirmActivateAllOnContract"), "confirm_activate", '', 0, 1);
  1093. } elseif ($action == 'clone') {
  1094. // Clone confirmation
  1095. $formquestion = array(array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)')));
  1096. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  1097. }
  1098. // Call Hook formConfirm
  1099. $parameters = array(
  1100. 'formConfirm' => $formconfirm,
  1101. 'id' => $id,
  1102. //'lineid' => $lineid,
  1103. );
  1104. // Note that $action and $object may have been modified by hook
  1105. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
  1106. if (empty($reshook)) {
  1107. $formconfirm .= $hookmanager->resPrint;
  1108. } elseif ($reshook > 0) {
  1109. $formconfirm = $hookmanager->resPrint;
  1110. }
  1111. // Print form confirm
  1112. print $formconfirm;
  1113. /*
  1114. * Contrat
  1115. */
  1116. if (!empty($object->brouillon) && $user->rights->contrat->creer) {
  1117. print '<form action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="POST">';
  1118. print '<input type="hidden" name="token" value="'.newToken().'">';
  1119. print '<input type="hidden" name="action" value="setremise">';
  1120. }
  1121. // Contract card
  1122. $linkback = '<a href="'.DOL_URL_ROOT.'/contrat/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  1123. $morehtmlref = '';
  1124. if (!empty($modCodeContract->code_auto)) {
  1125. $morehtmlref .= $object->ref;
  1126. } else {
  1127. $morehtmlref .= $form->editfieldkey("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 3);
  1128. $morehtmlref .= $form->editfieldval("", 'ref', $object->ref, $object, $user->rights->contrat->creer, 'string', '', 0, 2);
  1129. }
  1130. $morehtmlref .= '<div class="refidno">';
  1131. // Ref customer
  1132. $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
  1133. $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_customer', $object->ref_customer, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedCustomerRef');
  1134. // Ref supplier
  1135. $morehtmlref .= '<br>';
  1136. $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', 0, 1);
  1137. $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedSupplierRef');
  1138. // Thirdparty
  1139. $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
  1140. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  1141. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/contrat/list.php?socid='.$object->thirdparty->id.'&search_name='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherContracts").'</a>)';
  1142. }
  1143. // Project
  1144. if (!empty($conf->projet->enabled)) {
  1145. $langs->load("projects");
  1146. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  1147. if ($user->rights->contrat->creer) {
  1148. if ($action != 'classify') {
  1149. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  1150. }
  1151. if ($action == 'classify') {
  1152. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  1153. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  1154. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  1155. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  1156. $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  1157. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  1158. $morehtmlref .= '</form>';
  1159. } else {
  1160. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1);
  1161. }
  1162. } else {
  1163. if (!empty($object->fk_project)) {
  1164. $proj = new Project($db);
  1165. $proj->fetch($object->fk_project);
  1166. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  1167. if ($proj->title) {
  1168. $morehtmlref .= ' - '.$proj->title;
  1169. }
  1170. } else {
  1171. $morehtmlref .= '';
  1172. }
  1173. }
  1174. }
  1175. $morehtmlref .= '</div>';
  1176. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'none', $morehtmlref);
  1177. print '<div class="fichecenter">';
  1178. print '<div class="underbanner clearboth"></div>';
  1179. print '<table class="border tableforfield" width="100%">';
  1180. // Line info of thirdparty discounts
  1181. print '<tr><td class="titlefield">'.$langs->trans('Discount').'</td><td colspan="3">';
  1182. if ($object->thirdparty->remise_percent) {
  1183. print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent).'. ';
  1184. } else {
  1185. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoRelativeDiscount").'. </span>';
  1186. }
  1187. $absolute_discount = $object->thirdparty->getAvailableDiscounts();
  1188. if ($absolute_discount) {
  1189. print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)).'.';
  1190. } else {
  1191. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoAbsoluteDiscount").'.</span>';
  1192. }
  1193. print '</td></tr>';
  1194. // Date
  1195. print '<tr>';
  1196. print '<td class="titlefield">';
  1197. print $form->editfieldkey("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer);
  1198. print '</td><td>';
  1199. print $form->editfieldval("Date", 'date_contrat', $object->date_contrat, $object, $user->rights->contrat->creer, 'datehourpicker');
  1200. print '</td>';
  1201. print '</tr>';
  1202. // Other attributes
  1203. $cols = 3;
  1204. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  1205. print "</table>";
  1206. print '</div>';
  1207. if (!empty($object->brouillon) && $user->rights->contrat->creer) {
  1208. print '</form>';
  1209. }
  1210. echo '<br>';
  1211. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  1212. $blocname = 'contacts';
  1213. $title = $langs->trans('ContactsAddresses');
  1214. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  1215. }
  1216. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  1217. $blocname = 'notes';
  1218. $title = $langs->trans('Notes');
  1219. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  1220. }
  1221. $arrayothercontracts = $object->getListOfContracts('others');
  1222. /*
  1223. * Lines of contracts
  1224. */
  1225. $productstatic = new Product($db);
  1226. $usemargins = 0;
  1227. if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) {
  1228. $usemargins = 1;
  1229. }
  1230. // Title line for service
  1231. $cursorline = 1;
  1232. print '<div id="contrat-lines-container" data-contractid="'.$object->id.'" data-element="'.$object->element.'" >';
  1233. while ($cursorline <= $nbofservices) {
  1234. print '<div id="contrat-line-container'.$object->lines[$cursorline - 1]->id.'" data-contratlineid = "'.$object->lines[$cursorline - 1]->id.'" data-element="'.$object->lines[$cursorline - 1]->element.'" >';
  1235. print '<form name="update" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'" method="post">';
  1236. print '<input type="hidden" name="token" value="'.newToken().'">';
  1237. print '<input type="hidden" name="action" value="updateline">';
  1238. print '<input type="hidden" name="elrowid" value="'.$object->lines[$cursorline - 1]->id.'">';
  1239. print '<input type="hidden" name="fournprice" value="'.(!empty($object->lines[$cursorline - 1]->fk_fournprice) ? $object->lines[$cursorline - 1]->fk_fournprice : 0).'">';
  1240. // Area with common detail of line
  1241. print '<div class="div-table-responsive-no-min">';
  1242. print '<table class="notopnoleftnoright allwidth tableforservicepart1" width="100%">';
  1243. $sql = "SELECT cd.rowid, cd.statut, cd.label as label_det, cd.fk_product, cd.product_type, cd.description, cd.price_ht, cd.qty,";
  1244. $sql .= " cd.tva_tx, cd.vat_src_code, cd.remise_percent, cd.info_bits, cd.subprice, cd.multicurrency_subprice,";
  1245. $sql .= " cd.date_ouverture_prevue as date_debut, cd.date_ouverture as date_debut_reelle,";
  1246. $sql .= " cd.date_fin_validite as date_fin, cd.date_cloture as date_fin_reelle,";
  1247. $sql .= " cd.commentaire as comment, cd.fk_product_fournisseur_price as fk_fournprice, cd.buy_price_ht as pa_ht,";
  1248. $sql .= " cd.fk_unit,";
  1249. $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity, p.tosell, p.tobuy, p.tobatch";
  1250. $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd";
  1251. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid";
  1252. $sql .= " WHERE cd.rowid = ".((int) $object->lines[$cursorline - 1]->id);
  1253. $result = $db->query($sql);
  1254. if ($result) {
  1255. $total = 0;
  1256. print '<tr class="liste_titre'.($cursorline ? ' liste_titre_add' : '').'">';
  1257. print '<td>'.$langs->trans("ServiceNb", $cursorline).'</td>';
  1258. print '<td width="80" class="center">'.$langs->trans("VAT").'</td>';
  1259. print '<td width="80" class="right">'.$langs->trans("PriceUHT").'</td>';
  1260. //if (!empty($conf->multicurrency->enabled)) {
  1261. // print '<td width="80" class="right">'.$langs->trans("PriceUHTCurrency").'</td>';
  1262. //}
  1263. print '<td width="30" class="center">'.$langs->trans("Qty").'</td>';
  1264. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1265. print '<td width="30" class="left">'.$langs->trans("Unit").'</td>';
  1266. }
  1267. print '<td width="50" class="right">'.$langs->trans("ReductionShort").'</td>';
  1268. if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
  1269. print '<td width="50" class="right">'.$langs->trans("BuyingPrice").'</td>';
  1270. }
  1271. print '<td width="30">&nbsp;</td>';
  1272. print "</tr>\n";
  1273. $objp = $db->fetch_object($result);
  1274. // Line in view mode
  1275. if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) {
  1276. $moreparam = '';
  1277. if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') {
  1278. $moreparam = 'style="display: none;"';
  1279. }
  1280. print '<tr class="tdtop oddeven" '.$moreparam.'>';
  1281. // Label
  1282. if ($objp->fk_product > 0) {
  1283. $productstatic->id = $objp->fk_product;
  1284. $productstatic->type = $objp->ptype;
  1285. $productstatic->ref = $objp->pref;
  1286. $productstatic->entity = $objp->pentity;
  1287. $productstatic->label = $objp->plabel;
  1288. $productstatic->status = $objp->tosell;
  1289. $productstatic->status_buy = $objp->tobuy;
  1290. $productstatic->status_batch = $objp->tobatch;
  1291. print '<td>';
  1292. $text = $productstatic->getNomUrl(1, '', 32);
  1293. if ($objp->plabel) {
  1294. $text .= ' - ';
  1295. $text .= $objp->plabel;
  1296. }
  1297. $description = $objp->description;
  1298. // Add description in form
  1299. if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) {
  1300. $text .= (!empty($objp->description) && $objp->description != $objp->plabel) ? '<br>'.dol_htmlentitiesbr($objp->description) : '';
  1301. $description = ''; // Already added into main visible desc
  1302. }
  1303. echo $form->textwithtooltip($text, $description, 3, '', '', $cursorline, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : ''));
  1304. print '</td>';
  1305. } else {
  1306. print '<td>'.img_object($langs->trans("ShowProductOrService"), ($objp->product_type ? 'service' : 'product')).' '.dol_htmlentitiesbr($objp->description)."</td>\n";
  1307. }
  1308. // VAT
  1309. print '<td class="center">';
  1310. print vatrate($objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), '%', $objp->info_bits);
  1311. print '</td>';
  1312. // Price
  1313. print '<td class="right">'.($objp->subprice != '' ? price($objp->subprice) : '')."</td>\n";
  1314. // Price multicurrency
  1315. /*if (!empty($conf->multicurrency->enabled)) {
  1316. print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
  1317. }*/
  1318. // Quantity
  1319. print '<td class="center">'.$objp->qty.'</td>';
  1320. // Unit
  1321. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1322. print '<td class="left">'.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).'</td>';
  1323. }
  1324. // Discount
  1325. if ($objp->remise_percent > 0) {
  1326. print '<td class="right">'.$objp->remise_percent."%</td>\n";
  1327. } else {
  1328. print '<td>&nbsp;</td>';
  1329. }
  1330. // Margin
  1331. if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
  1332. print '<td class="right nowraponall">'.price($objp->pa_ht).'</td>';
  1333. }
  1334. // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme)
  1335. print '<td class="nowraponall right">';
  1336. if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) {
  1337. print '<!-- link to move service line into another contract -->';
  1338. print '<a class="reposition marginrightonly" style="padding-left: 5px;" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=move&token='.newToken().'&rowid='.$objp->rowid.'">';
  1339. print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow');
  1340. print '</a>';
  1341. }
  1342. if ($user->rights->contrat->creer && ($object->statut >= 0)) {
  1343. print '<a class="reposition marginrightonly editfielda" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=editline&token='.newToken().'&rowid='.$objp->rowid.'">';
  1344. print img_edit();
  1345. print '</a>';
  1346. }
  1347. if ($user->rights->contrat->creer && ($object->statut >= 0)) {
  1348. print '<a class="reposition marginrightonly" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=deleteline&token='.newToken().'&rowid='.$objp->rowid.'">';
  1349. print img_delete();
  1350. print '</a>';
  1351. }
  1352. print '</td>';
  1353. print "</tr>\n";
  1354. // Dates of service planed and real
  1355. if ($objp->subprice >= 0) {
  1356. $colspan = 6;
  1357. if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) {
  1358. $colspan = 8;
  1359. } elseif ($conf->margin->enabled || $conf->global->PRODUCT_USE_UNITS) {
  1360. $colspan = 7;
  1361. }
  1362. print '<tr class="oddeven" '.$moreparam.'>';
  1363. print '<td colspan="'.$colspan.'">';
  1364. // Date planned
  1365. print $langs->trans("DateStartPlanned").': ';
  1366. if ($objp->date_debut) {
  1367. print dol_print_date($db->jdate($objp->date_debut), 'day');
  1368. // Warning si date prevu passee et pas en service
  1369. if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) {
  1370. $warning_delay = $conf->contrat->services->inactifs->warning_delay / 3600 / 24;
  1371. $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
  1372. print " ".img_warning($textlate);
  1373. }
  1374. } else {
  1375. print $langs->trans("Unknown");
  1376. }
  1377. print ' &nbsp;-&nbsp; ';
  1378. print $langs->trans("DateEndPlanned").': ';
  1379. if ($objp->date_fin) {
  1380. print dol_print_date($db->jdate($objp->date_fin), 'day');
  1381. if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) {
  1382. $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24;
  1383. $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days");
  1384. print " ".img_warning($textlate);
  1385. }
  1386. } else {
  1387. print $langs->trans("Unknown");
  1388. }
  1389. print '</td>';
  1390. print '</tr>';
  1391. }
  1392. // Display lines extrafields
  1393. if (is_array($extralabelslines) && count($extralabelslines) > 0) {
  1394. $line = new ContratLigne($db);
  1395. $line->id = $objp->rowid;
  1396. $line->fetch_optionals();
  1397. print $line->showOptionals($extrafields, 'view', array('class'=>'oddeven', 'style'=>$moreparam, 'colspan'=>$colspan), '', '', 1);
  1398. }
  1399. } else {
  1400. // Line in mode update
  1401. // Ligne carac
  1402. print '<tr class="oddeven">';
  1403. print '<td>';
  1404. if ($objp->fk_product > 0) {
  1405. $canchangeproduct = 1;
  1406. if (empty($canchangeproduct)) {
  1407. $productstatic->id = $objp->fk_product;
  1408. $productstatic->type = $objp->ptype;
  1409. $productstatic->ref = $objp->pref;
  1410. $productstatic->entity = $objp->pentity;
  1411. print $productstatic->getNomUrl(1, '', 32);
  1412. print $objp->label ? ' - '.dol_trunc($objp->label, 32) : '';
  1413. print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0).'">';
  1414. } else {
  1415. $senderissupplier = 0;
  1416. if (empty($senderissupplier)) {
  1417. print $form->select_produits((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod');
  1418. } else {
  1419. print $form->select_produits_fournisseurs((!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0), 'idprod');
  1420. }
  1421. }
  1422. print '<br>';
  1423. } else {
  1424. print $objp->label ? $objp->label.'<br>' : '';
  1425. print '<input type="hidden" name="idprod" value="'.(!empty($object->lines[$cursorline - 1]->fk_product) ? $object->lines[$cursorline - 1]->fk_product : 0).'">';
  1426. }
  1427. // editeur wysiwyg
  1428. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  1429. $nbrows = ROWS_2;
  1430. if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) {
  1431. $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT;
  1432. }
  1433. $enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0);
  1434. $doleditor = new DolEditor('product_desc', $objp->description, '', 92, 'dolibarr_details', '', false, true, $enable, $nbrows, '90%');
  1435. $doleditor->Create();
  1436. print '</td>';
  1437. // VAT
  1438. print '<td class="right">';
  1439. print $form->load_tva("eltva_tx", $objp->tva_tx.($objp->vat_src_code ? (' ('.$objp->vat_src_code.')') : ''), $mysoc, $object->thirdparty, $objp->fk_product, $objp->info_bits, $objp->product_type, 0, 1);
  1440. print '</td>';
  1441. // Price
  1442. print '<td class="right"><input size="5" type="text" name="elprice" value="'.price($objp->subprice).'"></td>';
  1443. // Price multicurrency
  1444. /*if (!empty($conf->multicurrency->enabled)) {
  1445. print '<td class="linecoluht_currency nowrap right">'.price($objp->multicurrency_subprice).'</td>';
  1446. }*/
  1447. // Quantity
  1448. print '<td class="center"><input size="2" type="text" name="elqty" value="'.$objp->qty.'"></td>';
  1449. // Unit
  1450. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1451. print '<td class="left">';
  1452. print $form->selectUnits($objp->fk_unit, "unit");
  1453. print '</td>';
  1454. }
  1455. // Discount
  1456. print '<td class="nowrap right"><input size="1" type="text" name="elremise_percent" value="'.$objp->remise_percent.'">%</td>';
  1457. if (!empty($usemargins)) {
  1458. print '<td class="right">';
  1459. if ($objp->fk_product) {
  1460. print '<select id="fournprice" name="fournprice"></select>';
  1461. }
  1462. print '<input id="buying_price" type="text" size="5" name="buying_price" value="'.price($objp->pa_ht, 0, '', 0).'"></td>';
  1463. }
  1464. print '<td class="center">';
  1465. print '<input type="submit" class="button margintoponly marginbottomonly" name="save" value="'.$langs->trans("Modify").'">';
  1466. print '<br><input type="submit" class="button margintoponly marginbottomonly button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  1467. print '</td>';
  1468. print '</tr>';
  1469. $colspan = 6;
  1470. if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) {
  1471. $colspan++;
  1472. }
  1473. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1474. $colspan++;
  1475. }
  1476. // Line dates planed
  1477. print '<tr class="oddeven">';
  1478. print '<td colspan="'.$colspan.'">';
  1479. print $langs->trans("DateStartPlanned").' ';
  1480. print $form->selectDate($db->jdate($objp->date_debut), "date_start_update", $usehm, $usehm, ($db->jdate($objp->date_debut) > 0 ? 0 : 1), "update");
  1481. print ' &nbsp;&nbsp;'.$langs->trans("DateEndPlanned").' ';
  1482. print $form->selectDate($db->jdate($objp->date_fin), "date_end_update", $usehm, $usehm, ($db->jdate($objp->date_fin) > 0 ? 0 : 1), "update");
  1483. print '</td>';
  1484. print '</tr>';
  1485. if (is_array($extralabelslines) && count($extralabelslines) > 0) {
  1486. $line = new ContratLigne($db);
  1487. $line->id = $objp->rowid;
  1488. $line->fetch_optionals();
  1489. print $line->showOptionals($extrafields, 'edit', array('style'=>'class="oddeven"', 'colspan'=>$colspan), '', '', 1);
  1490. }
  1491. }
  1492. $db->free($result);
  1493. } else {
  1494. dol_print_error($db);
  1495. }
  1496. if ($object->statut > 0) {
  1497. $moreparam = '';
  1498. if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') {
  1499. $moreparam = 'style="display: none;"';
  1500. }
  1501. print '<tr class="oddeven" '.$moreparam.'>';
  1502. print '<td class="tdhrthin" colspan="'.($conf->margin->enabled ? 7 : 6).'"><hr class="opacitymedium tdhrthin"></td>';
  1503. print "</tr>\n";
  1504. }
  1505. print "</table>";
  1506. print '</div>';
  1507. print "</form>\n";
  1508. /*
  1509. * Confirmation to delete service line of contract
  1510. */
  1511. if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) {
  1512. print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1);
  1513. if ($ret == 'html') {
  1514. print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
  1515. }
  1516. }
  1517. /*
  1518. * Confirmation to move service toward another contract
  1519. */
  1520. if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) {
  1521. $arraycontractid = array();
  1522. foreach ($arrayothercontracts as $contractcursor) {
  1523. $arraycontractid[$contractcursor->id] = $contractcursor->ref;
  1524. }
  1525. //var_dump($arraycontractid);
  1526. // Cree un tableau formulaire
  1527. $formquestion = array(
  1528. 'text' => $langs->trans("ConfirmMoveToAnotherContractQuestion"),
  1529. array('type' => 'select', 'name' => 'newcid', 'values' => $arraycontractid));
  1530. print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid', 'int'), $langs->trans("MoveToAnotherContract"), $langs->trans("ConfirmMoveToAnotherContract"), "confirm_move", $formquestion);
  1531. print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
  1532. }
  1533. /*
  1534. * Confirmation de la validation activation
  1535. */
  1536. if ($action == 'active' && !$cancel && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne', 'int')) {
  1537. $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  1538. $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
  1539. $comment = GETPOST('comment', 'alpha');
  1540. print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("ActivateService"), $langs->trans("ConfirmActivateService", dol_print_date($dateactstart, "%A %d %B %Y")), "confirm_active", '', 0, 1);
  1541. print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
  1542. }
  1543. /*
  1544. * Confirmation de la validation fermeture
  1545. */
  1546. if ($action == 'closeline' && !$cancel && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne', 'int')) {
  1547. $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  1548. $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
  1549. $comment = GETPOST('comment', 'alpha');
  1550. if (empty($dateactend)) {
  1551. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors');
  1552. } else {
  1553. print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService", dol_print_date($dateactend, "%A %d %B %Y")), "confirm_closeline", '', 0, 1);
  1554. }
  1555. print '<table class="notopnoleftnoright" width="100%"><tr class="oddeven" height="6"><td></td></tr></table>';
  1556. }
  1557. // Area with status and activation info of line
  1558. if ($object->statut > 0) {
  1559. print '<table class="notopnoleftnoright tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
  1560. print '<tr class="oddeven" '.$moreparam.'>';
  1561. print '<td><span class="valignmiddle hideonsmartphone">'.$langs->trans("ServiceStatus").':</span> '.$object->lines[$cursorline - 1]->getLibStatut(4).'</td>';
  1562. print '<td width="30" class="right">';
  1563. if ($user->socid == 0) {
  1564. if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') {
  1565. $tmpaction = 'activateline';
  1566. $tmpactionpicto = 'play';
  1567. $tmpactiontext = $langs->trans("Activate");
  1568. if ($objp->statut == 4) {
  1569. $tmpaction = 'unactivateline';
  1570. $tmpactionpicto = 'playstop';
  1571. $tmpactiontext = $langs->trans("Disable");
  1572. }
  1573. if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver)) {
  1574. print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'&amp;action='.$tmpaction.'">';
  1575. print img_picto($tmpactiontext, $tmpactionpicto);
  1576. print '</a>';
  1577. }
  1578. }
  1579. }
  1580. print '</td>';
  1581. print "</tr>\n";
  1582. print '<tr class="oddeven" '.$moreparam.'>';
  1583. print '<td>';
  1584. // Si pas encore active
  1585. if (!$objp->date_debut_reelle) {
  1586. print $langs->trans("DateStartReal").': ';
  1587. if ($objp->date_debut_reelle) {
  1588. print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
  1589. } else {
  1590. print $langs->trans("ContractStatusNotRunning");
  1591. }
  1592. }
  1593. // Si active et en cours
  1594. if ($objp->date_debut_reelle && !$objp->date_fin_reelle) {
  1595. print $langs->trans("DateStartReal").': ';
  1596. print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
  1597. }
  1598. // Si desactive
  1599. if ($objp->date_debut_reelle && $objp->date_fin_reelle) {
  1600. print $langs->trans("DateStartReal").': ';
  1601. print dol_print_date($db->jdate($objp->date_debut_reelle), 'day');
  1602. print ' &nbsp;-&nbsp; ';
  1603. print $langs->trans("DateEndReal").': ';
  1604. print dol_print_date($db->jdate($objp->date_fin_reelle), 'day');
  1605. }
  1606. if (!empty($objp->comment)) {
  1607. print " &nbsp;-&nbsp; ".$objp->comment;
  1608. }
  1609. print '</td>';
  1610. print '<td class="center">&nbsp;</td>';
  1611. print '</tr>';
  1612. print '</table>';
  1613. }
  1614. // Form to activate line
  1615. if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne', 'int')) {
  1616. print '<form name="active" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.GETPOST('ligne', 'int').'&amp;action=active" method="post">';
  1617. print '<input type="hidden" name="token" value="'.newToken().'">';
  1618. print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
  1619. // Definie date debut et fin par defaut
  1620. $dateactstart = $objp->date_debut;
  1621. if (GETPOST('remonth')) {
  1622. $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  1623. } elseif (!$dateactstart) {
  1624. $dateactstart = time();
  1625. }
  1626. $dateactend = $objp->date_fin;
  1627. if (GETPOST('endmonth')) {
  1628. $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
  1629. } elseif (!$dateactend) {
  1630. if ($objp->fk_product > 0) {
  1631. $product = new Product($db);
  1632. $product->fetch($objp->fk_product);
  1633. $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
  1634. }
  1635. }
  1636. print '<tr class="oddeven">';
  1637. print '<td class="nohover">'.$langs->trans("DateServiceActivate").'</td><td class="nohover">';
  1638. print $form->selectDate($dateactstart, '', $usehm, $usehm, '', "active", 1, 0);
  1639. print '</td>';
  1640. print '<td class="nohover">'.$langs->trans("DateEndPlanned").'</td><td class="nohover">';
  1641. print $form->selectDate($dateactend, "end", $usehm, $usehm, '', "active", 1, 0);
  1642. print '</td>';
  1643. print '<td class="center nohover">';
  1644. print '</td>';
  1645. print '</tr>';
  1646. print '<tr class="oddeven">';
  1647. print '<td class="nohover">'.$langs->trans("Comment").'</td><td colspan="3" class="nohover" colspan="'.($conf->margin->enabled ? 4 : 3).'"><input type="text" class="minwidth300" name="comment" value="'.dol_escape_htmltag(GETPOST("comment", 'alphanohtml')).'"></td>';
  1648. print '<td class="nohover right">';
  1649. print '<input type="submit" class="button" name="activate" value="'.$langs->trans("Activate").'"> &nbsp; ';
  1650. print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  1651. print '</td>';
  1652. print '</tr>';
  1653. print '</table>';
  1654. print '</form>';
  1655. }
  1656. if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne', 'int')) {
  1657. /**
  1658. * Disable a contract line
  1659. */
  1660. print '<!-- Form to disabled a line -->'."\n";
  1661. print '<form name="closeline" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;ligne='.$object->lines[$cursorline - 1]->id.'" method="post">';
  1662. print '<input type="hidden" name="token" value="'.newToken().'">';
  1663. print '<input type="hidden" name="action" value="closeline">';
  1664. print '<table class="noborder tableforservicepart2'.($cursorline < $nbofservices ? ' boxtablenobottom' : '').'" width="100%">';
  1665. // Definie date debut et fin par defaut
  1666. $dateactstart = $objp->date_debut_reelle;
  1667. if (GETPOST('remonth')) {
  1668. $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  1669. } elseif (!$dateactstart) {
  1670. $dateactstart = time();
  1671. }
  1672. $dateactend = $objp->date_fin_reelle;
  1673. if (GETPOST('endmonth')) {
  1674. $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear'));
  1675. } elseif (!$dateactend) {
  1676. if ($objp->fk_product > 0) {
  1677. $product = new Product($db);
  1678. $product->fetch($objp->fk_product);
  1679. $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit);
  1680. }
  1681. }
  1682. $now = dol_now();
  1683. if ($dateactend > $now) {
  1684. $dateactend = $now;
  1685. }
  1686. print '<tr class="oddeven"><td colspan="2" class="nohover">';
  1687. if ($objp->statut >= 4) {
  1688. if ($objp->statut == 4) {
  1689. print $langs->trans("DateEndReal").' ';
  1690. print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle > 0 ? 0 : 1), "closeline", 1, 1);
  1691. }
  1692. }
  1693. print '</td>';
  1694. print '<td class="center nohover">';
  1695. print '</td></tr>';
  1696. print '<tr class="oddeven">';
  1697. print '<td class="nohover">'.$langs->trans("Comment").'</td><td class="nohover"><input size="70" type="text" class="flat" name="comment" value="'.dol_escape_htmltag(GETPOST('comment', 'alpha')).'"></td>';
  1698. print '<td class="nohover right">';
  1699. print '<input type="submit" class="button" name="close" value="'.$langs->trans("Disable").'"> &nbsp; ';
  1700. print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  1701. print '</td>';
  1702. print '</tr>';
  1703. print '</table>';
  1704. print '</form>';
  1705. }
  1706. print '</div>';
  1707. $cursorline++;
  1708. }
  1709. print '</div>';
  1710. // Form to add new line
  1711. if ($user->rights->contrat->creer && ($object->statut == 0)) {
  1712. $dateSelector = 1;
  1713. print "\n";
  1714. print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#add' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
  1715. <input type="hidden" name="token" value="'.newToken().'">
  1716. <input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">
  1717. <input type="hidden" name="mode" value="">
  1718. <input type="hidden" name="id" value="'.$object->id.'">
  1719. ';
  1720. print '<div class="div-table-responsive-no-min">';
  1721. print '<table id="tablelines" class="noborder noshadow" width="100%">'; // Array with (n*2)+1 lines
  1722. // Form to add new line
  1723. if ($action != 'editline') {
  1724. $forcetoshowtitlelines = 1;
  1725. if (empty($object->multicurrency_code)) {
  1726. $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts
  1727. }
  1728. // Add free products/services
  1729. $parameters = array();
  1730. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1731. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1732. if (empty($reshook))
  1733. $object->formAddObjectLine(1, $mysoc, $soc);
  1734. }
  1735. print '</table>';
  1736. print '</div>';
  1737. print '</form>';
  1738. }
  1739. print dol_get_fiche_end();
  1740. /*
  1741. * Buttons
  1742. */
  1743. if ($user->socid == 0) {
  1744. print '<div class="tabsAction">';
  1745. $parameters = array();
  1746. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1747. if (empty($reshook)) {
  1748. $params = array(
  1749. 'attr' => array(
  1750. 'title' => '',
  1751. 'class' => 'classfortooltip'
  1752. )
  1753. );
  1754. // Send
  1755. if (empty($user->socid)) {
  1756. if ($object->statut == 1) {
  1757. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->contrat->creer)) {
  1758. print dolGetButtonAction($langs->trans('SendMail'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&token='.newToken().'&mode=init#formmailbeforetitle', '', true, $params);
  1759. } else {
  1760. print dolGetButtonAction($langs->trans('SendMail'), '', 'default', '#', '', false, $params);
  1761. }
  1762. }
  1763. }
  1764. if ($object->statut == 0 && $nbofservices) {
  1765. if ($user->rights->contrat->creer) {
  1766. print dolGetButtonAction($langs->trans('Validate'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid&amp;token='.newToken(), '', true, $params);
  1767. } else {
  1768. $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
  1769. print dolGetButtonAction($langs->trans('Validate'), '', 'default', '#', '', false, $params);
  1770. }
  1771. }
  1772. if ($object->statut == 1) {
  1773. if ($user->rights->contrat->creer) {
  1774. print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken(), '', true, $params);
  1775. } else {
  1776. $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
  1777. print dolGetButtonAction($langs->trans('Modify'), '', 'default', '#', '', false, $params);
  1778. }
  1779. }
  1780. if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) {
  1781. $langs->load("orders");
  1782. if ($user->rights->commande->creer) {
  1783. print dolGetButtonAction($langs->trans('CreateOrder'), '', 'default', DOL_URL_ROOT.'/commande/card.php?action=create&token='.newToken().'&origin='.$object->element.'&originid='.$object->id.'&socid='.$object->thirdparty->id, '', true, $params);
  1784. } else {
  1785. $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
  1786. print dolGetButtonAction($langs->trans('CreateOrder'), '', 'default', '#', '', false, $params);
  1787. }
  1788. }
  1789. if (!empty($conf->facture->enabled) && $object->statut > 0) {
  1790. $langs->load("bills");
  1791. if ($user->rights->facture->creer) {
  1792. print dolGetButtonAction($langs->trans('CreateBill'), '', 'default', DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->thirdparty->id, '', true, $params);
  1793. } else {
  1794. $params['attr']['title'] = $langs->trans("NotEnoughPermissions");
  1795. print dolGetButtonAction($langs->trans('CreateBill'), '', 'default', '#', '', false, $params);
  1796. }
  1797. }
  1798. if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) {
  1799. if ($user->rights->contrat->activer) {
  1800. print dolGetButtonAction($langs->trans('ActivateAllContracts'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=activate&amp;token='.newToken(), '', true, $params);
  1801. } else {
  1802. print dolGetButtonAction($langs->trans('ActivateAllContracts'), '', 'default', '#', '', false, $params);
  1803. }
  1804. }
  1805. if ($object->nbofservicesclosed < $nbofservices) {
  1806. if ($user->rights->contrat->desactiver) {
  1807. print dolGetButtonAction($langs->trans('CloseAllContracts'), '', 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=close&amp;token='.newToken(), '', true, $params);
  1808. } else {
  1809. print dolGetButtonAction($langs->trans('CloseAllContracts'), '', 'default', '#', '', false, $params);
  1810. }
  1811. //if (! $numactive)
  1812. //{
  1813. //}
  1814. //else
  1815. //{
  1816. // print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("CloseRefusedBecauseOneServiceActive").'">'.$langs->trans("Close").'</a></div>';
  1817. //}
  1818. }
  1819. if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0) {
  1820. if ($action == 'showclosedlines') {
  1821. print '<div class="inline-block divButAction"><a class="butAction" id="btnhideclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=hideclosedlines">'.$langs->trans("HideClosedServices").'</a></div>';
  1822. } else {
  1823. print '<div class="inline-block divButAction"><a class="butAction" id="btnshowclosedlines" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=showclosedlines">'.$langs->trans("ShowClosedServices").'</a></div>';
  1824. }
  1825. }
  1826. // Clone
  1827. if ($user->rights->contrat->creer) {
  1828. print dolGetButtonAction($langs->trans('ToClone'), '', 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;token='.newToken(), '', true, $params);
  1829. }
  1830. // On peut supprimer entite si
  1831. // - Droit de creer + mode brouillon (erreur creation)
  1832. // - Droit de supprimer
  1833. if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) {
  1834. print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), '', true, $params);
  1835. } else {
  1836. $params['attr']['title'] = $langs->trans("NotAllowed");
  1837. print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), '', false, $params);
  1838. }
  1839. }
  1840. print "</div>";
  1841. }
  1842. // Select mail models is same action as presend
  1843. if (GETPOST('modelselected')) {
  1844. $action = 'presend';
  1845. }
  1846. if ($action != 'presend') {
  1847. print '<div class="fichecenter"><div class="fichehalfleft">';
  1848. /*
  1849. * Generated documents
  1850. */
  1851. $filename = dol_sanitizeFileName($object->ref);
  1852. $filedir = $conf->contrat->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref);
  1853. $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
  1854. $genallowed = $user->rights->contrat->lire;
  1855. $delallowed = $user->rights->contrat->creer;
  1856. print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, ($object->model_pdf ? $object->model_pdf : $conf->global->CONTRACT_ADDON_PDF), 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang, '', $object);
  1857. // Show links to link elements
  1858. $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat'));
  1859. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  1860. print '</div><div class="fichehalfright">';
  1861. $MAXEVENT = 10;
  1862. $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/contrat/agenda.php?id='.$object->id);
  1863. // List of actions on element
  1864. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  1865. $formactions = new FormActions($db);
  1866. $somethingshown = $formactions->showactions($object, 'contract', $socid, 1, 'listactions', $MAXEVENT, '', $morehtmlcenter);
  1867. print '</div></div>';
  1868. }
  1869. // Presend form
  1870. $modelmail = 'contract';
  1871. $defaulttopic = 'SendContractRef';
  1872. $diroutput = $conf->contrat->multidir_output[$object->entity];
  1873. $trackid = 'con'.$object->id;
  1874. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  1875. }
  1876. }
  1877. llxFooter();
  1878. $db->close();
  1879. ?>
  1880. <?php
  1881. if (!empty($conf->margin->enabled) && $action == 'editline') {
  1882. // TODO Why this ? To manage margin on contracts ?
  1883. ?>
  1884. <script type="text/javascript">
  1885. $(document).ready(function() {
  1886. var idprod = $("input[name='idprod']").val();
  1887. var fournprice = $("input[name='fournprice']").val();
  1888. var token = '<?php echo currentToken(); ?>'; // For AJAX Call we use old 'token' and not 'newtoken'
  1889. if (idprod > 0) {
  1890. $.post('<?php echo DOL_URL_ROOT; ?>/fourn/ajax/getSupplierPrices.php', {
  1891. 'idprod': idprod,
  1892. 'token': token
  1893. }, function(data) {
  1894. if (data.length > 0) {
  1895. var options = '';
  1896. var trouve=false;
  1897. $(data).each(function() {
  1898. options += '<option value="'+this.id+'" price="'+this.price+'"';
  1899. if (fournprice > 0) {
  1900. if (this.id == fournprice) {
  1901. options += ' selected';
  1902. $("#buying_price").val(this.price);
  1903. trouve = true;
  1904. }
  1905. }
  1906. options += '>'+this.label+'</option>';
  1907. });
  1908. options += '<option value=null'+(trouve?'':' selected')+'><?php echo $langs->trans("InputPrice"); ?></option>';
  1909. $("#fournprice").html(options);
  1910. if (trouve) {
  1911. $("#buying_price").hide();
  1912. $("#fournprice").show();
  1913. }
  1914. else {
  1915. $("#buying_price").show();
  1916. }
  1917. $("#fournprice").change(function() {
  1918. var selval = $(this).find('option:selected').attr("price");
  1919. if (selval)
  1920. $("#buying_price").val(selval).hide();
  1921. else
  1922. $('#buying_price').show();
  1923. });
  1924. }
  1925. else {
  1926. $("#fournprice").hide();
  1927. $('#buying_price').show();
  1928. }
  1929. },
  1930. 'json');
  1931. }
  1932. else {
  1933. $("#fournprice").hide();
  1934. $('#buying_price').show();
  1935. }
  1936. });
  1937. </script>
  1938. <?php
  1939. }