card.php 90 KB

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