card.php 91 KB

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