card.php 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250
  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->project->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. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  233. $classname = ucfirst($subelement);
  234. $srcobject = new $classname($db);
  235. dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
  236. $result = $srcobject->fetch($object->origin_id);
  237. if ($result > 0) {
  238. $srcobject->fetch_thirdparty();
  239. $lines = $srcobject->lines;
  240. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  241. $srcobject->fetch_lines();
  242. $lines = $srcobject->lines;
  243. }
  244. $fk_parent_line = 0;
  245. $num = count($lines);
  246. for ($i = 0; $i < $num; $i++) {
  247. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  248. if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee
  249. // service prédéfini
  250. if ($lines[$i]->fk_product > 0) {
  251. $product_static = new Product($db);
  252. // Define output language
  253. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  254. $prod = new Product($db);
  255. $prod->id = $lines[$i]->fk_product;
  256. $prod->getMultiLangs();
  257. $outputlangs = $langs;
  258. $newlang = '';
  259. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  260. $newlang = GETPOST('lang_id', 'aZ09');
  261. }
  262. if (empty($newlang)) {
  263. $newlang = $srcobject->thirdparty->default_lang;
  264. }
  265. if (!empty($newlang)) {
  266. $outputlangs = new Translate("", $conf);
  267. $outputlangs->setDefaultLang($newlang);
  268. }
  269. $label = (!empty($prod->multilangs[$outputlangs->defaultlang]["libelle"])) ? $prod->multilangs[$outputlangs->defaultlang]["libelle"] : $lines[$i]->product_label;
  270. } else {
  271. $label = $lines[$i]->product_label;
  272. }
  273. $desc = ($lines[$i]->desc && $lines[$i]->desc != $lines[$i]->libelle) ?dol_htmlentitiesbr($lines[$i]->desc) : '';
  274. } else {
  275. $desc = dol_htmlentitiesbr($lines[$i]->desc);
  276. }
  277. // Extrafields
  278. $array_options = array();
  279. // For avoid conflicts if trigger used
  280. if (method_exists($lines[$i], 'fetch_optionals')) {
  281. $lines[$i]->fetch_optionals();
  282. $array_options = $lines[$i]->array_options;
  283. }
  284. $txtva = $lines[$i]->vat_src_code ? $lines[$i]->tva_tx.' ('.$lines[$i]->vat_src_code.')' : $lines[$i]->tva_tx;
  285. // View third's localtaxes for now
  286. $localtax1_tx = get_localtax($txtva, 1, $object->thirdparty);
  287. $localtax2_tx = get_localtax($txtva, 2, $object->thirdparty);
  288. $result = $object->addline(
  289. $desc,
  290. $lines[$i]->subprice,
  291. $lines[$i]->qty,
  292. $txtva,
  293. $localtax1_tx,
  294. $localtax2_tx,
  295. $lines[$i]->fk_product,
  296. $lines[$i]->remise_percent,
  297. $lines[$i]->date_start,
  298. $lines[$i]->date_end,
  299. 'HT',
  300. 0,
  301. $lines[$i]->info_bits,
  302. $lines[$i]->fk_fournprice,
  303. $lines[$i]->pa_ht,
  304. $array_options,
  305. $lines[$i]->fk_unit
  306. );
  307. if ($result < 0) {
  308. $error++;
  309. break;
  310. }
  311. }
  312. }
  313. } else {
  314. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  315. $error++;
  316. }
  317. // Hooks
  318. $parameters = array('objFrom' => $srcobject);
  319. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  320. // modified by hook
  321. if ($reshook < 0) {
  322. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  323. $error++;
  324. }
  325. } else {
  326. setEventMessages($object->error, $object->errors, 'errors');
  327. $error++;
  328. }
  329. if ($error) {
  330. $action = 'create';
  331. }
  332. } else {
  333. $result = $object->create($user);
  334. if ($result > 0) {
  335. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  336. exit;
  337. } else {
  338. setEventMessages($object->error, $object->errors, 'errors');
  339. }
  340. $action = 'create';
  341. }
  342. }
  343. } elseif ($action == 'classin' && $user->rights->contrat->creer) {
  344. $object->setProject(GETPOST('projectid'));
  345. } elseif ($action == 'addline' && $user->rights->contrat->creer) {
  346. // Add a new line
  347. // Set if we used free entry or predefined product
  348. $predef = '';
  349. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  350. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  351. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  352. if (GETPOST('prod_entry_mode', 'alpha') == 'free') {
  353. $idprod = 0;
  354. $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0);
  355. } else {
  356. $idprod = GETPOST('idprod', 'int');
  357. $tva_tx = '';
  358. }
  359. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  360. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), 2) : 0);
  361. if ($qty == '') {
  362. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors');
  363. $error++;
  364. }
  365. if (GETPOST('prod_entry_mode', 'alpha') == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
  366. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors');
  367. $error++;
  368. }
  369. $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'));
  370. $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'));
  371. if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) {
  372. setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
  373. $error++;
  374. }
  375. // Extrafields
  376. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  377. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  378. // Unset extrafield
  379. if (is_array($extralabelsline)) {
  380. // Get extra fields
  381. foreach ($extralabelsline as $key => $value) {
  382. unset($_POST["options_".$key]);
  383. }
  384. }
  385. if (!$error) {
  386. // Clean parameters
  387. $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'));
  388. $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'));
  389. $price_base_type = (GETPOST('price_base_type', 'alpha') ?GETPOST('price_base_type', 'alpha') : 'HT');
  390. // Ecrase $pu par celui du produit
  391. // Ecrase $desc par celui du produit
  392. // Ecrase $tva_tx par celui du produit
  393. // Ecrase $base_price_type par celui du produit
  394. if ($idprod > 0) {
  395. $prod = new Product($db);
  396. $prod->fetch($idprod);
  397. // Update if prices fields are defined
  398. $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  399. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  400. if (empty($tva_tx)) {
  401. $tva_npr = 0;
  402. }
  403. $pu_ht = $prod->price;
  404. $pu_ttc = $prod->price_ttc;
  405. $price_min = $prod->price_min;
  406. $price_base_type = $prod->price_base_type;
  407. // On defini prix unitaire
  408. if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) {
  409. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  410. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  411. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  412. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  413. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  414. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  415. $prodcustprice = new Productcustomerprice($db);
  416. $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
  417. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  418. if ($result) {
  419. if (count($prodcustprice->lines) > 0) {
  420. $pu_ht = price($prodcustprice->lines [0]->price);
  421. $pu_ttc = price($prodcustprice->lines [0]->price_ttc);
  422. $price_base_type = $prodcustprice->lines [0]->price_base_type;
  423. $tva_tx = $prodcustprice->lines [0]->tva_tx;
  424. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  425. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  426. }
  427. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  428. if (empty($tva_tx)) {
  429. $tva_npr = 0;
  430. }
  431. }
  432. }
  433. }
  434. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  435. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  436. $pu_ht = price2num($price_ht, 'MU');
  437. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  438. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  439. if ($tmpvat != $tmpprodvat) {
  440. if ($price_base_type != 'HT') {
  441. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  442. } else {
  443. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  444. }
  445. }
  446. $desc = $prod->description;
  447. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  448. if ($product_desc == $desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  449. $product_desc = '';
  450. }
  451. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  452. $desc = $product_desc;
  453. } else {
  454. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  455. }
  456. $fk_unit = $prod->fk_unit;
  457. } else {
  458. $pu_ht = price2num($price_ht, 'MU');
  459. $price_base_type = 'HT';
  460. $tva_tx = GETPOST('tva_tx') ?str_replace('*', '', GETPOST('tva_tx')) : 0; // tva_tx field may be disabled, so we use vat rate 0
  461. $tva_npr = preg_match('/\*/', GETPOST('tva_tx')) ? 1 : 0;
  462. $desc = $product_desc;
  463. $fk_unit = GETPOST('units', 'alpha');
  464. }
  465. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  466. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  467. // ajout prix achat
  468. $fk_fournprice = GETPOST('fournprice');
  469. if (GETPOST('buying_price')) {
  470. $pa_ht = GETPOST('buying_price');
  471. } else {
  472. $pa_ht = null;
  473. }
  474. $info_bits = 0;
  475. if ($tva_npr) {
  476. $info_bits |= 0x01;
  477. }
  478. if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance))
  479. || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) {
  480. $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  481. $result = -1;
  482. } else {
  483. // Insert line
  484. $result = $object->addline(
  485. $desc,
  486. $pu_ht,
  487. $qty,
  488. $tva_tx,
  489. $localtax1_tx,
  490. $localtax2_tx,
  491. $idprod,
  492. $remise_percent,
  493. $date_start,
  494. $date_end,
  495. $price_base_type,
  496. $pu_ttc,
  497. $info_bits,
  498. $fk_fournprice,
  499. $pa_ht,
  500. $array_options,
  501. $fk_unit
  502. );
  503. }
  504. if ($result > 0) {
  505. // Define output language
  506. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) { // No generation if default type not defined
  507. $outputlangs = $langs;
  508. $newlang = '';
  509. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  510. $newlang = GETPOST('lang_id', 'aZ09');
  511. }
  512. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  513. $newlang = $object->thirdparty->default_lang;
  514. }
  515. if (!empty($newlang)) {
  516. $outputlangs = new Translate("", $conf);
  517. $outputlangs->setDefaultLang($newlang);
  518. }
  519. $ret = $object->fetch($id); // Reload to get new records
  520. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  521. }
  522. unset($_POST['prod_entry_mode']);
  523. unset($_POST['qty']);
  524. unset($_POST['type']);
  525. unset($_POST['remise_percent']);
  526. unset($_POST['price_ht']);
  527. unset($_POST['multicurrency_price_ht']);
  528. unset($_POST['price_ttc']);
  529. unset($_POST['tva_tx']);
  530. unset($_POST['product_ref']);
  531. unset($_POST['product_label']);
  532. unset($_POST['product_desc']);
  533. unset($_POST['fournprice']);
  534. unset($_POST['buying_price']);
  535. unset($_POST['np_marginRate']);
  536. unset($_POST['np_markRate']);
  537. unset($_POST['dp_desc']);
  538. unset($_POST['idprod']);
  539. unset($_POST['date_starthour']);
  540. unset($_POST['date_startmin']);
  541. unset($_POST['date_startsec']);
  542. unset($_POST['date_startday']);
  543. unset($_POST['date_startmonth']);
  544. unset($_POST['date_startyear']);
  545. unset($_POST['date_endhour']);
  546. unset($_POST['date_endmin']);
  547. unset($_POST['date_endsec']);
  548. unset($_POST['date_endday']);
  549. unset($_POST['date_endmonth']);
  550. unset($_POST['date_endyear']);
  551. } else {
  552. setEventMessages($object->error, $object->errors, 'errors');
  553. }
  554. }
  555. } elseif ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha')) {
  556. $error = 0;
  557. if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) {
  558. setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors');
  559. $action = 'editline';
  560. $_GET['rowid'] = GETPOST('elrowid');
  561. $error++;
  562. }
  563. if (!$error) {
  564. $objectline = new ContratLigne($db);
  565. if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) {
  566. setEventMessages($objectline->error, $objectline->errors, 'errors');
  567. $error++;
  568. }
  569. $objectline->fetch_optionals();
  570. }
  571. $db->begin();
  572. if (!$error) {
  573. if ($date_start_real_update == '') {
  574. $date_start_real_update = $objectline->date_ouverture;
  575. }
  576. if ($date_end_real_update == '') {
  577. $date_end_real_update = $objectline->date_cloture;
  578. }
  579. $vat_rate = GETPOST('eltva_tx');
  580. // Define info_bits
  581. $info_bits = 0;
  582. if (preg_match('/\*/', $vat_rate)) {
  583. $info_bits |= 0x01;
  584. }
  585. // Define vat_rate
  586. $vat_rate = str_replace('*', '', $vat_rate);
  587. $localtax1_tx = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  588. $localtax2_tx = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  589. $txtva = $vat_rate;
  590. // Clean vat code
  591. $reg = array();
  592. $vat_src_code = '';
  593. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  594. $vat_src_code = $reg[1];
  595. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  596. }
  597. // ajout prix d'achat
  598. if (GETPOST('buying_price')) {
  599. $pa_ht = price2num(GETPOST('buying_price'), '', 2);
  600. } else {
  601. $pa_ht = null;
  602. }
  603. $fk_unit = GETPOST('unit', 'alpha');
  604. $objectline->fk_product = GETPOST('idprod', 'int');
  605. $objectline->description = GETPOST('product_desc', 'restricthtml');
  606. $objectline->price_ht = price2num(GETPOST('elprice'), 'MU');
  607. $objectline->subprice = price2num(GETPOST('elprice'), 'MU');
  608. $objectline->qty = price2num(GETPOST('elqty'), 'MS');
  609. $objectline->remise_percent = price2num(GETPOST('elremise_percent'), 2);
  610. $objectline->tva_tx = ($txtva ? $txtva : 0); // Field may be disabled, so we use vat rate 0
  611. $objectline->vat_src_code = $vat_src_code;
  612. $objectline->localtax1_tx = is_numeric($localtax1_tx) ? $localtax1_tx : 0;
  613. $objectline->localtax2_tx = is_numeric($localtax2_tx) ? $localtax2_tx : 0;
  614. $objectline->date_ouverture_prevue = $date_start_update;
  615. $objectline->date_ouverture = $date_start_real_update;
  616. $objectline->date_fin_validite = $date_end_update;
  617. $objectline->date_cloture = $date_end_real_update;
  618. $objectline->fk_user_cloture = $user->id;
  619. $objectline->fk_fournprice = $fk_fournprice;
  620. $objectline->pa_ht = $pa_ht;
  621. if ($fk_unit > 0) {
  622. $objectline->fk_unit = GETPOST('unit');
  623. } else {
  624. $objectline->fk_unit = null;
  625. }
  626. // Extrafields
  627. $extralabelsline = $extrafields->fetch_name_optionals_label($objectline->table_element);
  628. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  629. if (is_array($array_options) && count($array_options) > 0) {
  630. // We replace values in this->line->array_options only for entries defined into $array_options
  631. foreach ($array_options as $key => $value) {
  632. $objectline->array_options[$key] = $array_options[$key];
  633. }
  634. }
  635. // TODO verifier price_min si fk_product et multiprix
  636. $result = $objectline->update($user);
  637. if ($result < 0) {
  638. $error++;
  639. setEventMessages($objectline->error, $objectline->errors, 'errors');
  640. }
  641. }
  642. if (!$error) {
  643. $db->commit();
  644. } else {
  645. $db->rollback();
  646. }
  647. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) {
  648. $result = $object->deleteline(GETPOST('lineid', 'int'), $user);
  649. if ($result >= 0) {
  650. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  651. exit;
  652. } else {
  653. setEventMessages($object->error, $object->errors, 'errors');
  654. }
  655. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) {
  656. $result = $object->validate($user);
  657. if ($result > 0) {
  658. // Define output language
  659. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  660. $outputlangs = $langs;
  661. $newlang = '';
  662. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  663. $newlang = GETPOST('lang_id', 'aZ09');
  664. }
  665. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  666. $newlang = $object->thirdparty->default_lang;
  667. }
  668. if (!empty($newlang)) {
  669. $outputlangs = new Translate("", $conf);
  670. $outputlangs->setDefaultLang($newlang);
  671. }
  672. $model = $object->model_pdf;
  673. $ret = $object->fetch($id); // Reload to get new records
  674. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  675. }
  676. } else {
  677. setEventMessages($object->error, $object->errors, 'errors');
  678. }
  679. } elseif ($action == 'reopen' && $user->rights->contrat->creer) {
  680. $result = $object->reopen($user);
  681. if ($result < 0) {
  682. setEventMessages($object->error, $object->errors, 'errors');
  683. }
  684. } elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) {
  685. // Close all lines
  686. $result = $object->closeAll($user);
  687. if ($result < 0) {
  688. setEventMessages($object->error, $object->errors, 'errors');
  689. }
  690. } elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) {
  691. // Close all lines
  692. $result = $object->activateAll($user);
  693. if ($result < 0) {
  694. setEventMessages($object->error, $object->errors, 'errors');
  695. }
  696. } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) {
  697. $result = $object->delete($user);
  698. if ($result >= 0) {
  699. header("Location: list.php?restore_lastsearch_values=1");
  700. return;
  701. } else {
  702. setEventMessages($object->error, $object->errors, 'errors');
  703. }
  704. } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer) {
  705. if (GETPOST('newcid') > 0) {
  706. $contractline = new ContratLigne($db);
  707. $result = $contractline->fetch(GETPOSTINT('lineid'));
  708. $contractline->fk_contrat = GETPOSTINT('newcid');
  709. $result = $contractline->update($user, 1);
  710. if ($result >= 0) {
  711. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  712. return;
  713. } else {
  714. setEventMessages($object->error, $object->errors, 'errors');
  715. }
  716. } else {
  717. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors');
  718. }
  719. } elseif ($action == 'update_extras') {
  720. $object->oldcopy = dol_clone($object);
  721. // Fill array 'array_options' with data from update form
  722. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  723. if ($ret < 0) {
  724. $error++;
  725. }
  726. if (!$error) {
  727. $result = $object->insertExtraFields('CONTRACT_MODIFY');
  728. if ($result < 0) {
  729. setEventMessages($object->error, $object->errors, 'errors');
  730. $error++;
  731. }
  732. }
  733. if ($error) {
  734. $action = 'edit_extras';
  735. }
  736. } elseif ($action == 'setref_supplier') {
  737. if (!$cancel) {
  738. $object->oldcopy = dol_clone($object);
  739. $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  740. if ($result < 0) {
  741. setEventMessages($object->error, $object->errors, 'errors');
  742. $action = 'editref_supplier';
  743. } else {
  744. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  745. exit;
  746. }
  747. } else {
  748. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  749. exit;
  750. }
  751. } elseif ($action == 'setref_customer') {
  752. if (!$cancel) {
  753. $object->oldcopy = dol_clone($object);
  754. $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  755. if ($result < 0) {
  756. setEventMessages($object->error, $object->errors, 'errors');
  757. $action = 'editref_customer';
  758. } else {
  759. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  760. exit;
  761. }
  762. } else {
  763. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  764. exit;
  765. }
  766. } elseif ($action == 'setref') {
  767. if (!$cancel) {
  768. $result = $object->fetch($id);
  769. if ($result < 0) {
  770. setEventMessages($object->error, $object->errors, 'errors');
  771. }
  772. $old_ref = $object->ref;
  773. $result = $object->setValueFrom('ref', GETPOST('ref', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY');
  774. if ($result < 0) {
  775. setEventMessages($object->error, $object->errors, 'errors');
  776. $action = 'editref';
  777. } else {
  778. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  779. $old_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($old_ref);
  780. $new_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
  781. $files = dol_dir_list($old_filedir);
  782. if (!empty($files)) {
  783. if (!is_dir($new_filedir)) {
  784. dol_mkdir($new_filedir);
  785. }
  786. foreach ($files as $file) {
  787. dol_move($file['fullname'], $new_filedir.'/'.$file['name']);
  788. }
  789. }
  790. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  791. exit;
  792. }
  793. } else {
  794. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  795. exit;
  796. }
  797. } elseif ($action == 'setdate_contrat') {
  798. if (!$cancel) {
  799. $result = $object->fetch($id);
  800. if ($result < 0) {
  801. setEventMessages($object->error, $object->errors, 'errors');
  802. }
  803. $datacontrat = dol_mktime(GETPOST('date_contrathour'), GETPOST('date_contratmin'), 0, GETPOST('date_contratmonth'), GETPOST('date_contratday'), GETPOST('date_contratyear'));
  804. $result = $object->setValueFrom('date_contrat', $datacontrat, '', null, 'date', '', $user, 'CONTRACT_MODIFY');
  805. if ($result < 0) {
  806. setEventMessages($object->error, $object->errors, 'errors');
  807. $action = 'editdate_contrat';
  808. } else {
  809. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  810. exit;
  811. }
  812. } else {
  813. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  814. exit;
  815. }
  816. }
  817. // Actions when printing a doc from card
  818. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  819. // Actions to build doc
  820. $upload_dir = $conf->contrat->multidir_output[$object->entity];
  821. $permissiontoadd = $user->rights->contrat->creer;
  822. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  823. // Actions to send emails
  824. $triggersendname = 'CONTRACT_SENTBYMAIL';
  825. $paramname = 'id';
  826. $mode = 'emailfromcontract';
  827. $trackid = 'con'.$object->id;
  828. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  829. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) {
  830. if ($action == 'addcontact') {
  831. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  832. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  833. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  834. if ($result >= 0) {
  835. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  836. exit;
  837. } else {
  838. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  839. $langs->load("errors");
  840. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  841. } else {
  842. setEventMessages($object->error, $object->errors, 'errors');
  843. }
  844. }
  845. } elseif ($action == 'swapstatut') {
  846. // bascule du statut d'un contact
  847. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  848. } elseif ($action == 'deletecontact') {
  849. // Efface un contact
  850. $result = $object->delete_contact(GETPOST('lineid', 'int'));
  851. if ($result >= 0) {
  852. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  853. exit;
  854. } else {
  855. setEventMessages($object->error, $object->errors, 'errors');
  856. }
  857. }
  858. }
  859. // Action clone object
  860. if ($action == 'confirm_clone' && $confirm == 'yes') {
  861. if (!GETPOST('socid', 3)) {
  862. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  863. } else {
  864. if ($object->id > 0) {
  865. $result = $object->createFromClone($user, $socid);
  866. if ($result > 0) {
  867. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  868. exit();
  869. } else {
  870. if (count($object->errors) > 0) {
  871. setEventMessages($object->error, $object->errors, 'errors');
  872. }
  873. $action = '';
  874. }
  875. }
  876. }
  877. }
  878. }
  879. /*
  880. * View
  881. */
  882. $help_url = 'EN:Module_Contracts|FR:Module_Contrat';
  883. llxHeader('', $langs->trans("Contract"), $help_url);
  884. $form = new Form($db);
  885. $formfile = new FormFile($db);
  886. if (!empty($conf->project->enabled)) {
  887. $formproject = new FormProjets($db);
  888. }
  889. // Load object modContract
  890. $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis');
  891. if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') {
  892. $module = substr($module, 0, dol_strlen($module) - 4);
  893. }
  894. $result = dol_include_once('/core/modules/contract/'.$module.'.php');
  895. if ($result > 0) {
  896. $modCodeContract = new $module();
  897. }
  898. // Create
  899. if ($action == 'create') {
  900. print load_fiche_titre($langs->trans('AddContract'), '', 'contract');
  901. $soc = new Societe($db);
  902. if ($socid > 0) {
  903. $soc->fetch($socid);
  904. }
  905. if (GETPOST('origin') && GETPOST('originid', 'int')) {
  906. // Parse element/subelement (ex: project_task)
  907. $regs = array();
  908. $element = $subelement = GETPOST('origin');
  909. if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) {
  910. $element = $regs[1];
  911. $subelement = $regs[2];
  912. }
  913. if ($element == 'project') {
  914. $projectid = GETPOST('originid', 'int');
  915. } else {
  916. // For compatibility
  917. if ($element == 'order' || $element == 'commande') {
  918. $element = $subelement = 'commande';
  919. }
  920. if ($element == 'propal') {
  921. $element = 'comm/propal'; $subelement = 'propal';
  922. }
  923. if ($element == 'invoice' || $element == 'facture') {
  924. $element = 'compta/facture';
  925. $subelement = 'facture';
  926. }
  927. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  928. $classname = ucfirst($subelement);
  929. $objectsrc = new $classname($db);
  930. $objectsrc->fetch($originid);
  931. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  932. $objectsrc->fetch_lines();
  933. }
  934. $objectsrc->fetch_thirdparty();
  935. // Replicate extrafields
  936. $objectsrc->fetch_optionals();
  937. $object->array_options = $objectsrc->array_options;
  938. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  939. $soc = $objectsrc->thirdparty;
  940. $note_private = (!empty($objectsrc->note_private) ? $objectsrc->note_private : '');
  941. $note_public = (!empty($objectsrc->note_public) ? $objectsrc->note_public : '');
  942. // Object source contacts list
  943. $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
  944. }
  945. } else {
  946. $projectid = GETPOST('projectid', 'int');
  947. $note_private = GETPOST("note_private");
  948. $note_public = GETPOST("note_public");
  949. }
  950. $object->date_contrat = dol_now();
  951. print '<form name="form_contract" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  952. print '<input type="hidden" name="token" value="'.newToken().'">';
  953. print '<input type="hidden" name="action" value="add">';
  954. print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
  955. print '<input type="hidden" name="remise_percent" value="0">';
  956. print dol_get_fiche_head();
  957. print '<table class="border centpercent">';
  958. // Ref
  959. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>';
  960. if (!empty($modCodeContract->code_auto)) {
  961. $tmpcode = $langs->trans("Draft");
  962. } else {
  963. $tmpcode = '<input name="ref" class="maxwidth100" maxlength="128" value="'.dol_escape_htmltag(GETPOST('ref') ?GETPOST('ref') : $tmpcode).'">';
  964. }
  965. print $tmpcode;
  966. print '</td></tr>';
  967. // Ref customer
  968. print '<tr><td>'.$langs->trans('RefCustomer').'</td>';
  969. print '<td><input type="text" class="maxwidth150" name="ref_customer" id="ref_customer" value="'.dol_escape_htmltag(GETPOST('ref_customer', 'alpha')).'"></td></tr>';
  970. // Ref supplier
  971. print '<tr><td>'.$langs->trans('RefSupplier').'</td>';
  972. print '<td><input type="text" class="maxwidth150" name="ref_supplier" id="ref_supplier" value="'.dol_escape_htmltag(GETPOST('ref_supplier', 'alpha')).'"></td></tr>';
  973. // Thirdparty
  974. print '<tr>';
  975. print '<td class="fieldrequired">'.$langs->trans('ThirdParty').'</td>';
  976. if ($socid > 0) {
  977. print '<td>';
  978. print $soc->getNomUrl(1);
  979. print '<input type="hidden" name="socid" value="'.$soc->id.'">';
  980. print '</td>';
  981. } else {
  982. print '<td>';
  983. print img_picto('', 'company', 'class="pictofixedwidth"');
  984. print $form->select_company('', 'socid', '', 'SelectThirdParty', 1, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  985. 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>';
  986. print '</td>';
  987. }
  988. print '</tr>'."\n";
  989. if ($socid > 0) {
  990. // Ligne info remises tiers
  991. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  992. if ($soc->remise_percent) {
  993. print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent).' ';
  994. } else {
  995. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoRelativeDiscount").'. </span>';
  996. }
  997. $absolute_discount = $soc->getAvailableDiscounts();
  998. if ($absolute_discount) {
  999. print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)).'.';
  1000. } else {
  1001. print '<span class="hideonsmartphone">'.$langs->trans("CompanyHasNoAbsoluteDiscount").'.</span>';
  1002. }
  1003. print '</td></tr>';
  1004. }
  1005. // Commercial suivi
  1006. print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPFOLL").'</span></td><td>';
  1007. print img_picto('', 'user', 'class="pictofixedwidth"');
  1008. print $form->select_dolusers(GETPOST("commercial_suivi_id") ?GETPOST("commercial_suivi_id") : $user->id, 'commercial_suivi_id', 1, '');
  1009. print '</td></tr>';
  1010. // Commercial signature
  1011. print '<tr><td class="nowrap"><span class="fieldrequired">'.$langs->trans("TypeContact_contrat_internal_SALESREPSIGN").'</span></td><td>';
  1012. print img_picto('', 'user', 'class="pictofixedwidth"');
  1013. print $form->select_dolusers(GETPOST("commercial_signature_id") ?GETPOST("commercial_signature_id") : $user->id, 'commercial_signature_id', 1, '');
  1014. print '</td></tr>';
  1015. print '<tr><td><span class="fieldrequired">'.$langs->trans("Date").'</span></td><td>';
  1016. print $form->selectDate($datecontrat, '', 0, 0, '', "contrat");
  1017. print "</td></tr>";
  1018. // Project
  1019. if (!empty($conf->project->enabled)) {
  1020. $langs->load('projects');
  1021. $formproject = new FormProjets($db);
  1022. print '<tr><td>'.$langs->trans("Project").'</td><td>';
  1023. $formproject->select_projects(($soc->id > 0 ? $soc->id : -1), $projectid, "projectid", 0, 0, 1, 1);
  1024. 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>';
  1025. print "</td></tr>";
  1026. }
  1027. print '<tr><td>'.$langs->trans("NotePublic").'</td><td class="tdtop">';
  1028. $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%');
  1029. print $doleditor->Create(1);
  1030. print '</td></tr>';
  1031. if (empty($user->socid)) {
  1032. print '<tr><td>'.$langs->trans("NotePrivate").'</td><td class="tdtop">';
  1033. $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%');
  1034. print $doleditor->Create(1);
  1035. print '</td></tr>';
  1036. }
  1037. // Other attributes
  1038. $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="3"', 'cols' => '3');
  1039. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1040. print $hookmanager->resPrint;
  1041. // Other attributes
  1042. if (empty($reshook)) {
  1043. print $object->showOptionals($extrafields, 'create', $parameters);
  1044. }
  1045. print "</table>\n";
  1046. print dol_get_fiche_end();
  1047. print $form->buttonsSaveCancel("Create");
  1048. if (is_object($objectsrc)) {
  1049. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  1050. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  1051. if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) {
  1052. print '<br>'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed");
  1053. }
  1054. }
  1055. print "</form>\n";
  1056. } else {
  1057. // View and edit mode
  1058. $now = dol_now();
  1059. if ($object->id > 0) {
  1060. $object->fetch_thirdparty();
  1061. $soc = $object->thirdparty; // $soc is used later
  1062. $result = $object->fetch_lines(); // This also init $this->nbofserviceswait, $this->nbofservicesopened, $this->nbofservicesexpired=, $this->nbofservicesclosed
  1063. if ($result < 0) {
  1064. dol_print_error($db, $object->error);
  1065. }
  1066. $nbofservices = count($object->lines);
  1067. $author = new User($db);
  1068. $author->fetch($object->user_author_id);
  1069. $commercial_signature = new User($db);
  1070. $commercial_signature->fetch($object->commercial_signature_id);
  1071. $commercial_suivi = new User($db);
  1072. $commercial_suivi->fetch($object->commercial_suivi_id);
  1073. $head = contract_prepare_head($object);
  1074. $hselected = 0;
  1075. $formconfirm = '';
  1076. print dol_get_fiche_head($head, $hselected, $langs->trans("Contract"), -1, 'contract');
  1077. if ($action == 'delete') {
  1078. //Confirmation de la suppression du contrat
  1079. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("DeleteAContract"), $langs->trans("ConfirmDeleteAContract"), "confirm_delete", '', 0, 1);
  1080. } elseif ($action == 'valid') {
  1081. //Confirmation de la validation
  1082. $ref = substr($object->ref, 1, 4);
  1083. if ($ref == 'PROV' && !empty($modCodeContract->code_auto)) {
  1084. $numref = $object->getNextNumRef($object->thirdparty);
  1085. } else {
  1086. $numref = $object->ref;
  1087. }
  1088. $text = $langs->trans('ConfirmValidateContract', $numref);
  1089. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ValidateAContract"), $text, "confirm_valid", '', 0, 1);
  1090. } elseif ($action == 'close') {
  1091. // Confirmation de la fermeture
  1092. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("CloseAContract"), $langs->trans("ConfirmCloseContract"), "confirm_close", '', 0, 1);
  1093. } elseif ($action == 'activate') {
  1094. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ActivateAllOnContract"), $langs->trans("ConfirmActivateAllOnContract"), "confirm_activate", '', 0, 1);
  1095. } elseif ($action == 'clone') {
  1096. // Clone confirmation
  1097. $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)')));
  1098. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneContract', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  1099. }
  1100. // Call Hook formConfirm
  1101. $parameters = array(
  1102. 'formConfirm' => $formconfirm,
  1103. 'id' => $id,
  1104. //'lineid' => $lineid,
  1105. );
  1106. // Note that $action and $object may have been modified by hook
  1107. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
  1108. if (empty($reshook)) {
  1109. $formconfirm .= $hookmanager->resPrint;
  1110. } elseif ($reshook > 0) {
  1111. $formconfirm = $hookmanager->resPrint;
  1112. }
  1113. // Print form confirm
  1114. print $formconfirm;
  1115. // Contract
  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->project->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'); // array or -1 if technical error
  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 (status contract 0=draft,1=validated,2=closed)
  1335. print '<td class="nowraponall right">';
  1336. if ($user->rights->contrat->creer && is_array($arrayothercontracts) && 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 (isModEnabled('facture') && $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. }