card.php 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132
  1. <?php
  2. /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  5. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  7. * Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2011-2023 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2012-2023 Christophe Battarel <christophe.battarel@altairis.fr>
  10. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  13. * Copyright (C) 2014 Ferran Marcet <fmarcet@2byte.es>
  14. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  15. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  16. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  17. * Copyright (C) 2023 Benjamin Falière <benjamin.faliere@altairis.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/commande/card.php
  34. * \ingroup commande
  35. * \brief Page to show sales order
  36. */
  37. // Load Dolibarr environment
  38. require '../main.inc.php';
  39. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
  45. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  46. require_once DOL_DOCUMENT_ROOT.'/core/lib/order.lib.php';
  47. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  48. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  49. if (isModEnabled("propal")) {
  50. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  51. }
  52. if (isModEnabled('project')) {
  53. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  54. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  55. }
  56. if (isModEnabled('variants')) {
  57. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  58. }
  59. // Load translation files required by the page
  60. $langs->loadLangs(array('orders', 'sendings', 'companies', 'bills', 'propal', 'deliveries', 'products', 'other'));
  61. if (isModEnabled('incoterm')) {
  62. $langs->load('incoterm');
  63. }
  64. if (isModEnabled('margin')) {
  65. $langs->load('margins');
  66. }
  67. if (isModEnabled('productbatch')) {
  68. $langs->load('productbatch');
  69. }
  70. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('orderid', 'int'));
  71. $ref = GETPOST('ref', 'alpha');
  72. $socid = GETPOST('socid', 'int');
  73. $action = GETPOST('action', 'aZ09');
  74. $cancel = GETPOST('cancel', 'alpha');
  75. $confirm = GETPOST('confirm', 'alpha');
  76. $backtopage = GETPOST('backtopage', 'alpha');
  77. $lineid = GETPOST('lineid', 'int');
  78. $contactid = GETPOST('contactid', 'int');
  79. $projectid = GETPOST('projectid', 'int');
  80. $origin = GETPOST('origin', 'alpha');
  81. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  82. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  83. // PDF
  84. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0));
  85. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0));
  86. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0));
  87. // Security check
  88. if (!empty($user->socid)) {
  89. $socid = $user->socid;
  90. }
  91. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  92. $hookmanager->initHooks(array('ordercard', 'globalcard'));
  93. $result = restrictedArea($user, 'commande', $id);
  94. $object = new Commande($db);
  95. $extrafields = new ExtraFields($db);
  96. // fetch optionals attributes and labels
  97. $extrafields->fetch_name_optionals_label($object->table_element);
  98. // Load object
  99. include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
  100. // Permissions / Rights
  101. $usercanread = $user->hasRight("commande", "lire");
  102. $usercancreate = $user->hasRight("commande", "creer");
  103. $usercandelete = $user->hasRight("commande", "supprimer");
  104. // Advanced permissions
  105. $usercanclose = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !empty($usercancreate)) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'close')));
  106. $usercanvalidate = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'validate')));
  107. $usercancancel = ((!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $usercancreate) || (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('commande', 'order_advance', 'annuler')));
  108. $usercansend = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight('commande', 'order_advance', 'send'));
  109. $usercangeneretedoc = (!getDolGlobalString('MAIN_USE_ADVANCED_PERMS') || $user->hasRight('commande', 'order_advance', 'generetedoc'));
  110. $usermustrespectpricemin = ((getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && empty($user->rights->produit->ignore_price_min_advance)) || !getDolGlobalString('MAIN_USE_ADVANCED_PERMS'));
  111. $usercancreatepurchaseorder = ($user->hasRight('fournisseur', 'commande', 'creer') || $user->hasRight('supplier_order', 'creer'));
  112. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  113. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  114. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
  115. $error = 0;
  116. $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int'));
  117. /*
  118. * Actions
  119. */
  120. $parameters = array('socid' => $socid);
  121. // Note that $action and $object may be modified by some hooks
  122. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
  123. if ($reshook < 0) {
  124. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  125. }
  126. if (empty($reshook)) {
  127. $backurlforlist = DOL_URL_ROOT.'/commande/list.php';
  128. if (empty($backtopage) || ($cancel && empty($id))) {
  129. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  130. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  131. $backtopage = $backurlforlist;
  132. } else {
  133. $backtopage = DOL_URL_ROOT.'/commande/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  134. }
  135. }
  136. }
  137. $selectedLines = GETPOST('toselect', 'array');
  138. if ($cancel) {
  139. if (!empty($backtopageforcancel)) {
  140. header("Location: ".$backtopageforcancel);
  141. exit;
  142. } elseif (!empty($backtopage)) {
  143. header("Location: ".$backtopage);
  144. exit;
  145. }
  146. $action = '';
  147. }
  148. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  149. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  150. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  151. // Action clone object
  152. if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) {
  153. if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
  154. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  155. } else {
  156. if ($object->id > 0) {
  157. // Because createFromClone modifies the object, we must clone it so that we can restore it later
  158. $orig = clone $object;
  159. $result = $object->createFromClone($user, $socid);
  160. if ($result > 0) {
  161. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  162. exit;
  163. } else {
  164. setEventMessages($object->error, $object->errors, 'errors');
  165. $object = $orig;
  166. $action = '';
  167. }
  168. }
  169. }
  170. } elseif ($action == 'reopen' && $usercancreate) {
  171. // Reopen a closed order
  172. if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) {
  173. if (getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) {
  174. $result = $object->setDraft($user, $idwarehouse);
  175. if ($result < 0) {
  176. setEventMessages($object->error, $object->errors, 'errors');
  177. }
  178. } else {
  179. $result = $object->set_reopen($user);
  180. if ($result > 0) {
  181. setEventMessages($langs->trans('OrderReopened', $object->ref), null);
  182. } else {
  183. setEventMessages($object->error, $object->errors, 'errors');
  184. }
  185. }
  186. }
  187. } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
  188. // Remove order
  189. $result = $object->delete($user);
  190. if ($result > 0) {
  191. header('Location: list.php?restore_lastsearch_values=1');
  192. exit;
  193. } else {
  194. setEventMessages($object->error, $object->errors, 'errors');
  195. }
  196. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  197. // Remove a product line
  198. $result = $object->deleteline($user, $lineid);
  199. if ($result > 0) {
  200. // reorder lines
  201. $object->line_order(true);
  202. // Define output language
  203. $outputlangs = $langs;
  204. $newlang = '';
  205. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  206. $newlang = GETPOST('lang_id', 'aZ09');
  207. }
  208. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  209. $newlang = $object->thirdparty->default_lang;
  210. }
  211. if (!empty($newlang)) {
  212. $outputlangs = new Translate("", $conf);
  213. $outputlangs->setDefaultLang($newlang);
  214. }
  215. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  216. $ret = $object->fetch($object->id); // Reload to get new records
  217. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  218. }
  219. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  220. exit;
  221. } else {
  222. setEventMessages($object->error, $object->errors, 'errors');
  223. }
  224. } elseif ($action == 'classin' && $usercancreate) {
  225. // Link to a project
  226. $object->setProject(GETPOST('projectid', 'int'));
  227. } elseif ($action == 'add' && $usercancreate) {
  228. // Add order
  229. $datecommande = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear'));
  230. $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int'));
  231. if ($datecommande == '') {
  232. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors');
  233. $action = 'create';
  234. $error++;
  235. }
  236. if ($socid < 1) {
  237. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  238. $action = 'create';
  239. $error++;
  240. }
  241. if (!$error) {
  242. $object->socid = $socid;
  243. $object->fetch_thirdparty();
  244. $db->begin();
  245. $object->date_commande = $datecommande;
  246. $object->note_private = GETPOST('note_private', 'restricthtml');
  247. $object->note_public = GETPOST('note_public', 'restricthtml');
  248. $object->source = GETPOST('source_id', 'int');
  249. $object->fk_project = GETPOST('projectid', 'int');
  250. $object->ref_client = GETPOST('ref_client', 'alpha');
  251. $object->model_pdf = GETPOST('model');
  252. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  253. $object->deposit_percent = GETPOST('cond_reglement_id_deposit_percent', 'alpha');
  254. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  255. $object->fk_account = GETPOST('fk_account', 'int');
  256. $object->availability_id = GETPOST('availability_id');
  257. $object->demand_reason_id = GETPOST('demand_reason_id', 'int');
  258. $object->delivery_date = $date_delivery;
  259. $object->shipping_method_id = GETPOST('shipping_method_id', 'int');
  260. $object->warehouse_id = GETPOST('warehouse_id', 'int');
  261. $object->fk_delivery_address = GETPOST('fk_address', 'int');
  262. $object->contact_id = GETPOST('contactid', 'int');
  263. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  264. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  265. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  266. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  267. // Fill array 'array_options' with data from add form
  268. if (!$error) {
  269. $ret = $extrafields->setOptionalsFromPost(null, $object);
  270. if ($ret < 0) {
  271. $error++;
  272. }
  273. }
  274. // If creation from another object of another module (Example: origin=propal, originid=1)
  275. if (!empty($origin) && !empty($originid)) {
  276. // Parse element/subelement (ex: project_task)
  277. $element = $subelement = $origin;
  278. $regs = array();
  279. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  280. $element = $regs [1];
  281. $subelement = $regs [2];
  282. }
  283. // For compatibility
  284. if ($element == 'order') {
  285. $element = $subelement = 'commande';
  286. }
  287. if ($element == 'propal') {
  288. $element = 'comm/propal';
  289. $subelement = 'propal';
  290. }
  291. if ($element == 'contract') {
  292. $element = $subelement = 'contrat';
  293. }
  294. $object->origin = $origin;
  295. $object->origin_id = $originid;
  296. // Possibility to add external linked objects with hooks
  297. $object->linked_objects [$object->origin] = $object->origin_id;
  298. $other_linked_objects = GETPOST('other_linked_objects', 'array');
  299. if (!empty($other_linked_objects)) {
  300. $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects);
  301. }
  302. if (!$error) {
  303. $object_id = $object->create($user);
  304. if ($object_id > 0) {
  305. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  306. $classname = ucfirst($subelement);
  307. $srcobject = new $classname($db);
  308. dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
  309. $result = $srcobject->fetch($object->origin_id);
  310. if ($result > 0) {
  311. $lines = $srcobject->lines;
  312. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  313. $srcobject->fetch_lines();
  314. $lines = $srcobject->lines;
  315. }
  316. $fk_parent_line = 0;
  317. $num = count($lines);
  318. for ($i = 0; $i < $num; $i++) {
  319. if (!in_array($lines[$i]->id, $selectedLines)) {
  320. continue; // Skip unselected lines
  321. }
  322. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  323. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : '');
  324. $product_type = (!empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0);
  325. // Dates
  326. // TODO mutualiser
  327. $date_start = $lines[$i]->date_debut_prevue;
  328. if ($lines[$i]->date_debut_reel) {
  329. $date_start = $lines[$i]->date_debut_reel;
  330. }
  331. if ($lines[$i]->date_start) {
  332. $date_start = $lines[$i]->date_start;
  333. }
  334. $date_end = $lines[$i]->date_fin_prevue;
  335. if ($lines[$i]->date_fin_reel) {
  336. $date_end = $lines[$i]->date_fin_reel;
  337. }
  338. if ($lines[$i]->date_end) {
  339. $date_end = $lines[$i]->date_end;
  340. }
  341. // Reset fk_parent_line for no child products and special product
  342. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  343. $fk_parent_line = 0;
  344. }
  345. // Extrafields
  346. if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if trigger used
  347. $lines[$i]->fetch_optionals();
  348. $array_options = $lines[$i]->array_options;
  349. }
  350. $tva_tx = $lines[$i]->tva_tx;
  351. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  352. $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
  353. }
  354. $result = $object->addline(
  355. $desc,
  356. $lines[$i]->subprice,
  357. $lines[$i]->qty,
  358. $tva_tx,
  359. $lines[$i]->localtax1_tx,
  360. $lines[$i]->localtax2_tx,
  361. $lines[$i]->fk_product,
  362. $lines[$i]->remise_percent,
  363. $lines[$i]->info_bits,
  364. $lines[$i]->fk_remise_except,
  365. 'HT',
  366. 0,
  367. $date_start,
  368. $date_end,
  369. $product_type,
  370. $lines[$i]->rang,
  371. $lines[$i]->special_code,
  372. $fk_parent_line,
  373. $lines[$i]->fk_fournprice,
  374. $lines[$i]->pa_ht,
  375. $label,
  376. $array_options,
  377. $lines[$i]->fk_unit,
  378. $object->origin,
  379. $lines[$i]->rowid
  380. );
  381. if ($result < 0) {
  382. $error++;
  383. break;
  384. }
  385. // Defined the new fk_parent_line
  386. if ($result > 0 && $lines[$i]->product_type == 9) {
  387. $fk_parent_line = $result;
  388. }
  389. }
  390. } else {
  391. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  392. $error++;
  393. }
  394. // Now we create same links to contact than the ones found on origin object
  395. /* Useless, already into the create
  396. if (!empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  397. {
  398. $originforcontact = $object->origin;
  399. $originidforcontact = $object->origin_id;
  400. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  401. {
  402. $originforcontact=$srcobject->origin;
  403. $originidforcontact=$srcobject->origin_id;
  404. }
  405. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  406. $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
  407. $resqlcontact = $db->query($sqlcontact);
  408. if ($resqlcontact)
  409. {
  410. while($objcontact = $db->fetch_object($resqlcontact))
  411. {
  412. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  413. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  414. }
  415. }
  416. else dol_print_error($resqlcontact);
  417. }*/
  418. // Hooks
  419. $parameters = array('objFrom' => $srcobject);
  420. // Note that $action and $object may be modified by hook
  421. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action);
  422. if ($reshook < 0) {
  423. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  424. $error++;
  425. }
  426. } else {
  427. setEventMessages($object->error, $object->errors, 'errors');
  428. $error++;
  429. }
  430. } else {
  431. // Required extrafield left blank, error message already defined by setOptionalsFromPost()
  432. $action = 'create';
  433. }
  434. } else {
  435. if (!$error) {
  436. $object_id = $object->create($user);
  437. }
  438. }
  439. // Insert default contacts if defined
  440. if ($object_id > 0) {
  441. if (GETPOST('contactid', 'int')) {
  442. $result = $object->add_contact(GETPOST('contactid', 'int'), 'CUSTOMER', 'external');
  443. if ($result < 0) {
  444. setEventMessages($langs->trans("ErrorFailedToAddContact"), null, 'errors');
  445. $error++;
  446. }
  447. }
  448. $id = $object_id;
  449. $action = '';
  450. }
  451. // End of object creation, we show it
  452. if ($object_id > 0 && !$error) {
  453. $db->commit();
  454. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object_id);
  455. exit();
  456. } else {
  457. $db->rollback();
  458. $action = 'create';
  459. setEventMessages($object->error, $object->errors, 'errors');
  460. }
  461. }
  462. } elseif ($action == 'classifybilled' && $usercancreate) {
  463. $ret = $object->classifyBilled($user);
  464. if ($ret < 0) {
  465. setEventMessages($object->error, $object->errors, 'errors');
  466. }
  467. } elseif ($action == 'classifyunbilled' && $usercancreate) {
  468. $ret = $object->classifyUnBilled($user);
  469. if ($ret < 0) {
  470. setEventMessages($object->error, $object->errors, 'errors');
  471. }
  472. } elseif ($action == 'setref_client' && $usercancreate) {
  473. // Positionne ref commande client
  474. $result = $object->set_ref_client($user, GETPOST('ref_client'));
  475. if ($result < 0) {
  476. setEventMessages($object->error, $object->errors, 'errors');
  477. }
  478. } elseif ($action == 'setremise' && $usercancreate) {
  479. $result = $object->setDiscount($user, price2num(GETPOST('remise'), 2));
  480. if ($result < 0) {
  481. setEventMessages($object->error, $object->errors, 'errors');
  482. }
  483. } elseif ($action == 'setabsolutediscount' && $usercancreate) {
  484. if (GETPOST('remise_id')) {
  485. if ($object->id > 0) {
  486. $object->insert_discount(GETPOST('remise_id'));
  487. } else {
  488. dol_print_error($db, $object->error);
  489. }
  490. }
  491. } elseif ($action == 'setdate' && $usercancreate) {
  492. $date = dol_mktime(0, 0, 0, GETPOST('order_month', 'int'), GETPOST('order_day', 'int'), GETPOST('order_year', 'int'));
  493. $result = $object->set_date($user, $date);
  494. if ($result < 0) {
  495. setEventMessages($object->error, $object->errors, 'errors');
  496. }
  497. } elseif ($action == 'setdate_livraison' && $usercancreate) {
  498. $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int'));
  499. $object->fetch($id);
  500. $result = $object->setDeliveryDate($user, $date_delivery);
  501. if ($result < 0) {
  502. setEventMessages($object->error, $object->errors, 'errors');
  503. }
  504. } elseif ($action == 'setmode' && $usercancreate) {
  505. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  506. if ($result < 0) {
  507. setEventMessages($object->error, $object->errors, 'errors');
  508. }
  509. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  510. // Multicurrency Code
  511. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  512. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  513. // Multicurrency rate
  514. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  515. } elseif ($action == 'setavailability' && $usercancreate) {
  516. $result = $object->availability(GETPOST('availability_id'));
  517. if ($result < 0) {
  518. setEventMessages($object->error, $object->errors, 'errors');
  519. }
  520. } elseif ($action == 'setdemandreason' && $usercancreate) {
  521. $result = $object->demand_reason(GETPOST('demand_reason_id'));
  522. if ($result < 0) {
  523. setEventMessages($object->error, $object->errors, 'errors');
  524. }
  525. } elseif ($action == 'setconditions' && $usercancreate) {
  526. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'), GETPOST('cond_reglement_id_deposit_percent', 'alpha'));
  527. if ($result < 0) {
  528. dol_print_error($db, $object->error);
  529. } else {
  530. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  531. // Define output language
  532. $outputlangs = $langs;
  533. $newlang = GETPOST('lang_id', 'alpha');
  534. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  535. $newlang = $object->thirdparty->default_lang;
  536. }
  537. if (!empty($newlang)) {
  538. $outputlangs = new Translate("", $conf);
  539. $outputlangs->setDefaultLang($newlang);
  540. }
  541. $ret = $object->fetch($object->id); // Reload to get new records
  542. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  543. }
  544. }
  545. } elseif ($action == 'set_incoterms' && isModEnabled('incoterm')) {
  546. // Set incoterm
  547. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  548. if ($result < 0) {
  549. setEventMessages($object->error, $object->errors, 'errors');
  550. }
  551. } elseif ($action == 'setbankaccount' && $usercancreate) {
  552. // bank account
  553. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  554. if ($result < 0) {
  555. setEventMessages($object->error, $object->errors, 'errors');
  556. }
  557. } elseif ($action == 'setshippingmethod' && $usercancreate) {
  558. // shipping method
  559. $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int'));
  560. if ($result < 0) {
  561. setEventMessages($object->error, $object->errors, 'errors');
  562. }
  563. } elseif ($action == 'setwarehouse' && $usercancreate) {
  564. // warehouse
  565. $result = $object->setWarehouse(GETPOST('warehouse_id', 'int'));
  566. if ($result < 0) {
  567. setEventMessages($object->error, $object->errors, 'errors');
  568. }
  569. //} elseif ($action == 'setremisepercent' && $usercancreate) {
  570. // $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
  571. //} elseif ($action == 'setremiseabsolue' && $usercancreate) {
  572. // $result = $object->set_remise_absolue($user, price2num(GETPOST('remise_absolue'), 'MU', 2));
  573. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') {
  574. // Define vat_rate
  575. $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
  576. $vat_rate = str_replace('*', '', $vat_rate);
  577. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  578. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  579. foreach ($object->lines as $line) {
  580. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
  581. }
  582. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('remiseforalllines', 'alpha') !== '' && $usercancreate) {
  583. // Define remise_percent
  584. $remise_percent = (GETPOST('remiseforalllines') ? GETPOST('remiseforalllines') : 0);
  585. $remise_percent = str_replace('*', '', $remise_percent);
  586. foreach ($object->lines as $line) {
  587. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice);
  588. }
  589. } elseif ($action == 'addline' && $usercancreate) { // Add a new line
  590. $langs->load('errors');
  591. $error = 0;
  592. // Set if we used free entry or predefined product
  593. $predef = '';
  594. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  595. $price_ht = '';
  596. $price_ht_devise = '';
  597. $price_ttc = '';
  598. $price_ttc_devise = '';
  599. $pu_ht = '';
  600. $pu_ttc = '';
  601. $pu_ht_devise = '';
  602. $pu_ttc_devise = '';
  603. if (GETPOST('price_ht') !== '') {
  604. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  605. }
  606. if (GETPOST('multicurrency_price_ht') !== '') {
  607. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  608. }
  609. if (GETPOST('price_ttc') !== '') {
  610. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  611. }
  612. if (GETPOST('multicurrency_price_ttc') !== '') {
  613. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  614. }
  615. $prod_entry_mode = GETPOST('prod_entry_mode', 'aZ09');
  616. if ($prod_entry_mode == 'free') {
  617. $idprod = 0;
  618. } else {
  619. $idprod = GETPOST('idprod', 'int');
  620. if (getDolGlobalString('MAIN_DISABLE_FREE_LINES') && $idprod <= 0) {
  621. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  622. $error++;
  623. }
  624. }
  625. $tva_tx = GETPOST('tva_tx', 'alpha');
  626. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS', 2);
  627. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
  628. if (empty($remise_percent)) {
  629. $remise_percent = 0;
  630. }
  631. // Extrafields
  632. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  633. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  634. // Unset extrafield
  635. if (is_array($extralabelsline)) {
  636. // Get extra fields
  637. foreach ($extralabelsline as $key => $value) {
  638. unset($_POST["options_".$key]);
  639. }
  640. }
  641. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  642. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  643. $error++;
  644. }
  645. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  646. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  647. $error++;
  648. }
  649. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && $price_ht === '' && $price_ht_devise === '' && $price_ttc === '' && $price_ttc_devise === '') { // Unit price can be 0 but not ''. Also price can be negative for order.
  650. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  651. $error++;
  652. }
  653. if ($qty == '') {
  654. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  655. $error++;
  656. }
  657. if ($qty < 0) {
  658. setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  659. $error++;
  660. }
  661. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && empty($product_desc)) {
  662. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  663. $error++;
  664. }
  665. if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
  666. if ($combinations = GETPOST('combinations', 'array')) {
  667. //Check if there is a product with the given combination
  668. $prodcomb = new ProductCombination($db);
  669. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  670. $idprod = $res->fk_product_child;
  671. } else {
  672. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  673. $error++;
  674. }
  675. }
  676. }
  677. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  678. // Clean parameters
  679. $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'));
  680. $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'));
  681. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  682. $price_min = $price_min_ttc = 0;
  683. // Ecrase $pu par celui du produit
  684. // Ecrase $desc par celui du produit
  685. // Ecrase $base_price_type par celui du produit
  686. if (!empty($idprod) && $idprod > 0) {
  687. $prod = new Product($db);
  688. $prod->fetch($idprod);
  689. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  690. // Update if prices fields are defined
  691. /*$tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id);
  692. $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id);
  693. if (empty($tva_tx)) {
  694. $tva_npr = 0;
  695. }*/
  696. $pu_ht = $prod->price;
  697. $pu_ttc = $prod->price_ttc;
  698. $price_min = $prod->price_min;
  699. $price_min_ttc = $prod->price_min_ttc;
  700. $price_base_type = $prod->price_base_type;
  701. // If price per segment
  702. if (getDolGlobalString('PRODUIT_MULTIPRICES') && !empty($object->thirdparty->price_level)) {
  703. $pu_ht = $prod->multiprices[$object->thirdparty->price_level];
  704. $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level];
  705. $price_min = $prod->multiprices_min[$object->thirdparty->price_level];
  706. $price_min_ttc = $prod->multiprices_min_ttc[$object->thirdparty->price_level];
  707. $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level];
  708. if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
  709. if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) {
  710. $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level];
  711. }
  712. if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) {
  713. $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level];
  714. }
  715. }
  716. } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
  717. // If price per customer
  718. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  719. $prodcustprice = new ProductCustomerPrice($db);
  720. $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id);
  721. $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
  722. if ($result >= 0) {
  723. if (count($prodcustprice->lines) > 0) {
  724. $pu_ht = price($prodcustprice->lines[0]->price);
  725. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  726. $price_min = price($prodcustprice->lines[0]->price_min);
  727. $price_min_ttc = price($prodcustprice->lines[0]->price_min_ttc);
  728. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  729. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  730. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  731. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  732. }
  733. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  734. if (empty($tva_tx)) {
  735. $tva_npr = 0;
  736. }
  737. }
  738. } else {
  739. setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors');
  740. }
  741. } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY')) {
  742. // If price per quantity
  743. if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity
  744. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  745. $pqp = GETPOST('pbq', 'int');
  746. // Search price into product_price_by_qty from $prod->id
  747. foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) {
  748. if ($priceforthequantityarray['rowid'] != $pqp) {
  749. continue;
  750. }
  751. // We found the price
  752. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  753. $pu_ht = $priceforthequantityarray['unitprice'];
  754. } else {
  755. $pu_ttc = $priceforthequantityarray['unitprice'];
  756. }
  757. // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
  758. break;
  759. }
  760. }
  761. } elseif (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  762. // If price per quantity and customer
  763. if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity
  764. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  765. $pqp = GETPOST('pbq', 'int');
  766. // Search price into product_price_by_qty from $prod->id
  767. foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) {
  768. if ($priceforthequantityarray['rowid'] != $pqp) {
  769. continue;
  770. }
  771. // We found the price
  772. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  773. $pu_ht = $priceforthequantityarray['unitprice'];
  774. } else {
  775. $pu_ttc = $priceforthequantityarray['unitprice'];
  776. }
  777. // Note: the remise_percent or price by qty is used to set data on form, so we will use value from POST.
  778. break;
  779. }
  780. }
  781. }
  782. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  783. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  784. // Set unit price to use
  785. if (!empty($price_ht) || $price_ht === '0') {
  786. $pu_ht = price2num($price_ht, 'MU');
  787. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  788. } elseif (!empty($price_ttc) || $price_ttc === '0') {
  789. $pu_ttc = price2num($price_ttc, 'MU');
  790. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  791. } elseif ($tmpvat != $tmpprodvat) {
  792. // Is this still used ?
  793. if ($price_base_type != 'HT') {
  794. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  795. } else {
  796. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  797. }
  798. }
  799. $desc = '';
  800. // Define output language
  801. if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
  802. $outputlangs = $langs;
  803. $newlang = '';
  804. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  805. $newlang = GETPOST('lang_id', 'aZ09');
  806. }
  807. if (empty($newlang)) {
  808. $newlang = $object->thirdparty->default_lang;
  809. }
  810. if (!empty($newlang)) {
  811. $outputlangs = new Translate("", $conf);
  812. $outputlangs->setDefaultLang($newlang);
  813. }
  814. $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description;
  815. } else {
  816. $desc = $prod->description;
  817. }
  818. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  819. if ($product_desc==$desc && getDolGlobalString('PRODUIT_AUTOFILL_DESC')) {
  820. $product_desc='';
  821. }
  822. if (!empty($product_desc) && getDolGlobalString('MAIN_NO_CONCAT_DESCRIPTION')) {
  823. $desc = $product_desc;
  824. } else {
  825. $desc = dol_concatdesc($desc, $product_desc, '', getDolGlobalString('MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION'));
  826. }
  827. // Add custom code and origin country into description
  828. if (!getDolGlobalString('MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE') && (!empty($prod->customcode) || !empty($prod->country_code))) {
  829. $tmptxt = '(';
  830. // Define output language
  831. if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
  832. $outputlangs = $langs;
  833. $newlang = '';
  834. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  835. $newlang = GETPOST('lang_id', 'alpha');
  836. }
  837. if (empty($newlang)) {
  838. $newlang = $object->thirdparty->default_lang;
  839. }
  840. if (!empty($newlang)) {
  841. $outputlangs = new Translate("", $conf);
  842. $outputlangs->setDefaultLang($newlang);
  843. $outputlangs->load('products');
  844. }
  845. if (!empty($prod->customcode)) {
  846. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  847. }
  848. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  849. $tmptxt .= ' - ';
  850. }
  851. if (!empty($prod->country_code)) {
  852. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  853. }
  854. } else {
  855. if (!empty($prod->customcode)) {
  856. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  857. }
  858. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  859. $tmptxt .= ' - ';
  860. }
  861. if (!empty($prod->country_code)) {
  862. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
  863. }
  864. }
  865. $tmptxt .= ')';
  866. $desc = dol_concatdesc($desc, $tmptxt);
  867. }
  868. $type = $prod->type;
  869. $fk_unit = $prod->fk_unit;
  870. } else {
  871. $pu_ht = price2num($price_ht, 'MU');
  872. $pu_ttc = price2num($price_ttc, 'MU');
  873. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  874. $tva_tx = str_replace('*', '', $tva_tx);
  875. if (empty($tva_tx)) {
  876. $tva_npr = 0;
  877. }
  878. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  879. $desc = $product_desc;
  880. $type = GETPOST('type');
  881. $fk_unit = GETPOST('units', 'alpha');
  882. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  883. $pu_ttc_devise = price2num($price_ttc_devise, 'MU');
  884. if ($pu_ttc && !$pu_ht) {
  885. $price_base_type = 'TTC';
  886. }
  887. }
  888. $info_bits = 0;
  889. if ($tva_npr) {
  890. $info_bits |= 0x01;
  891. }
  892. // Local Taxes
  893. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
  894. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
  895. // Margin
  896. $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
  897. $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we muste keep this value
  898. // Prepare a price equivalent for minimum price check
  899. $pu_equivalent = $pu_ht;
  900. $pu_equivalent_ttc = $pu_ttc;
  901. $currency_tx = $object->multicurrency_tx;
  902. // Check if we have a foreign currency
  903. // If so, we update the pu_equiv as the equivalent price in base currency
  904. if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '') {
  905. $pu_equivalent = $pu_ht_devise * $currency_tx;
  906. }
  907. if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '') {
  908. $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
  909. }
  910. // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one defined
  911. /*
  912. if ($pu_equivalent) {
  913. $tmp = calcul_price_total(1, $pu_equivalent, 0, $tva_tx, -1, -1, 0, 'HT', $info_bits, $type);
  914. $pu_equivalent_ttc = ...
  915. } else {
  916. $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $tva_tx, -1, -1, 0, 'TTC', $info_bits, $type);
  917. $pu_equivalent_ht = ...
  918. }
  919. */
  920. $desc = dol_htmlcleanlastbr($desc);
  921. // Check price is not lower than minimum
  922. if ($usermustrespectpricemin) {
  923. if ($pu_equivalent && $price_min && ((price2num($pu_equivalent) * (1 - $remise_percent / 100)) < price2num($price_min)) && $price_base_type == 'HT') {
  924. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  925. setEventMessages($mesg, null, 'errors');
  926. $error++;
  927. } elseif ($pu_equivalent_ttc && $price_min_ttc && ((price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc)) && $price_base_type == 'TTC') {
  928. $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  929. setEventMessages($mesg, null, 'errors');
  930. $error++;
  931. }
  932. }
  933. if (!$error) {
  934. // Insert line
  935. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $info_bits, 0, $price_base_type, $pu_ttc, $date_start, $date_end, $type, min($rank, count($object->lines) + 1), 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $fk_unit, '', 0, $pu_ht_devise);
  936. if ($result > 0) {
  937. $ret = $object->fetch($object->id); // Reload to get new records
  938. $object->fetch_thirdparty();
  939. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  940. // Define output language
  941. $outputlangs = $langs;
  942. $newlang = GETPOST('lang_id', 'alpha');
  943. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  944. $newlang = $object->thirdparty->default_lang;
  945. }
  946. if (!empty($newlang)) {
  947. $outputlangs = new Translate("", $conf);
  948. $outputlangs->setDefaultLang($newlang);
  949. }
  950. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  951. }
  952. unset($_POST['prod_entry_mode']);
  953. unset($_POST['qty']);
  954. unset($_POST['type']);
  955. unset($_POST['remise_percent']);
  956. unset($_POST['price_ht']);
  957. unset($_POST['multicurrency_price_ht']);
  958. unset($_POST['price_ttc']);
  959. unset($_POST['tva_tx']);
  960. unset($_POST['product_ref']);
  961. unset($_POST['product_label']);
  962. unset($_POST['product_desc']);
  963. unset($_POST['fournprice']);
  964. unset($_POST['buying_price']);
  965. unset($_POST['np_marginRate']);
  966. unset($_POST['np_markRate']);
  967. unset($_POST['dp_desc']);
  968. unset($_POST['idprod']);
  969. unset($_POST['units']);
  970. unset($_POST['date_starthour']);
  971. unset($_POST['date_startmin']);
  972. unset($_POST['date_startsec']);
  973. unset($_POST['date_startday']);
  974. unset($_POST['date_startmonth']);
  975. unset($_POST['date_startyear']);
  976. unset($_POST['date_endhour']);
  977. unset($_POST['date_endmin']);
  978. unset($_POST['date_endsec']);
  979. unset($_POST['date_endday']);
  980. unset($_POST['date_endmonth']);
  981. unset($_POST['date_endyear']);
  982. } else {
  983. setEventMessages($object->error, $object->errors, 'errors');
  984. }
  985. }
  986. }
  987. } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) {
  988. // Update a line
  989. // Clean parameters
  990. $date_start = '';
  991. $date_end = '';
  992. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  993. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  994. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml'));
  995. // Define info_bits
  996. $info_bits = 0;
  997. if (preg_match('/\*/', GETPOST('tva_tx'))) {
  998. $info_bits |= 0x01;
  999. }
  1000. // Define vat_rate
  1001. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx', 'alpha') : 0);
  1002. $vat_rate = str_replace('*', '', $vat_rate);
  1003. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  1004. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  1005. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  1006. $pu_ttc = price2num(GETPOST('price_ttc'), '', 2);
  1007. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  1008. $pu_ttc_devise = price2num(GETPOST('multicurrency_subprice_ttc'), '', 2);
  1009. $qty = price2num(GETPOST('qty', 'alpha'), 'MS');
  1010. // Prepare a price equivalent for minimum price check
  1011. $pu_equivalent = $pu_ht;
  1012. $pu_equivalent_ttc = $pu_ttc;
  1013. $currency_tx = $object->multicurrency_tx;
  1014. // Check if we have a foreign currency
  1015. // If so, we update the pu_equiv as the equivalent price in base currency
  1016. if ($pu_ht == '' && $pu_ht_devise != '' && $currency_tx != '') {
  1017. $pu_equivalent = $pu_ht_devise * $currency_tx;
  1018. }
  1019. if ($pu_ttc == '' && $pu_ttc_devise != '' && $currency_tx != '') {
  1020. $pu_equivalent_ttc = $pu_ttc_devise * $currency_tx;
  1021. }
  1022. // TODO $pu_equivalent or $pu_equivalent_ttc must be calculated from the one not null taking into account all taxes
  1023. /*
  1024. if ($pu_equivalent) {
  1025. $tmp = calcul_price_total(1, $pu_equivalent, 0, $vat_rate, -1, -1, 0, 'HT', $info_bits, $type);
  1026. $pu_equivalent_ttc = ...
  1027. } else {
  1028. $tmp = calcul_price_total(1, $pu_equivalent_ttc, 0, $vat_rate, -1, -1, 0, 'TTC', $info_bits, $type);
  1029. $pu_equivalent_ht = ...
  1030. }
  1031. */
  1032. // Add buying price
  1033. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  1034. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  1035. // Extrafields Lines
  1036. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1037. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  1038. // Unset extrafield POST Data
  1039. if (is_array($extralabelsline)) {
  1040. foreach ($extralabelsline as $key => $value) {
  1041. unset($_POST["options_".$key]);
  1042. }
  1043. }
  1044. // Define special_code for special lines
  1045. $special_code = GETPOST('special_code');
  1046. if (!GETPOST('qty')) {
  1047. $special_code = 3;
  1048. }
  1049. $remise_percent = GETPOST('remise_percent') != '' ? price2num(GETPOST('remise_percent'), '', 2) : 0;
  1050. // Check minimum price
  1051. $productid = GETPOST('productid', 'int');
  1052. if (!empty($productid)) {
  1053. $product = new Product($db);
  1054. $product->fetch($productid);
  1055. $type = $product->type;
  1056. $price_min = $product->price_min;
  1057. if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
  1058. $price_min = $product->multiprices_min[$object->thirdparty->price_level];
  1059. }
  1060. $price_min_ttc = $product->price_min_ttc;
  1061. if ((getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) && !empty($object->thirdparty->price_level)) {
  1062. $price_min_ttc = $product->multiprices_min_ttc[$object->thirdparty->price_level];
  1063. }
  1064. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  1065. // Check price is not lower than minimum
  1066. if ($usermustrespectpricemin) {
  1067. if ($pu_equivalent && $price_min && ((price2num($pu_equivalent) * (1 - $remise_percent / 100)) < price2num($price_min)) && $price_base_type == 'HT') {
  1068. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  1069. setEventMessages($mesg, null, 'errors');
  1070. $error++;
  1071. $action = 'editline';
  1072. } elseif ($pu_equivalent_ttc && $price_min_ttc && ((price2num($pu_equivalent_ttc) * (1 - $remise_percent / 100)) < price2num($price_min_ttc)) && $price_base_type == 'TTC') {
  1073. $mesg = $langs->trans("CantBeLessThanMinPriceInclTax", price(price2num($price_min_ttc, 'MU'), 0, $langs, 0, 0, -1, $conf->currency));
  1074. setEventMessages($mesg, null, 'errors');
  1075. $error++;
  1076. $action = 'editline';
  1077. }
  1078. }
  1079. } else {
  1080. $type = GETPOST('type');
  1081. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1082. // Check parameters
  1083. if (GETPOST('type') < 0) {
  1084. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  1085. $error++;
  1086. $action = 'editline';
  1087. }
  1088. }
  1089. if ($qty < 0) {
  1090. setEventMessages($langs->trans('FieldCannotBeNegative', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1091. $error++;
  1092. $action = 'editline';
  1093. }
  1094. if (!$error) {
  1095. if (!$user->hasRight('margins', 'creer')) {
  1096. foreach ($object->lines as &$line) {
  1097. if ($line->id == GETPOST('lineid', 'int')) {
  1098. $fournprice = $line->fk_fournprice;
  1099. $buyingprice = $line->pa_ht;
  1100. break;
  1101. }
  1102. }
  1103. }
  1104. $price_base_type = 'HT';
  1105. $pu = $pu_ht;
  1106. if (empty($pu) && !empty($pu_ttc)) {
  1107. $pu = $pu_ttc;
  1108. $price_base_type = 'TTC';
  1109. }
  1110. $result = $object->updateline(GETPOST('lineid', 'int'), $description, $pu, $qty, $remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, $price_base_type, $info_bits, $date_start, $date_end, $type, GETPOST('fk_parent_line'), 0, $fournprice, $buyingprice, $label, $special_code, $array_options, GETPOST('units'), $pu_ht_devise);
  1111. if ($result >= 0) {
  1112. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  1113. // Define output language
  1114. $outputlangs = $langs;
  1115. $newlang = '';
  1116. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1117. $newlang = GETPOST('lang_id', 'aZ09');
  1118. }
  1119. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  1120. $newlang = $object->thirdparty->default_lang;
  1121. }
  1122. if (!empty($newlang)) {
  1123. $outputlangs = new Translate("", $conf);
  1124. $outputlangs->setDefaultLang($newlang);
  1125. }
  1126. $ret = $object->fetch($object->id); // Reload to get new records
  1127. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1128. }
  1129. unset($_POST['qty']);
  1130. unset($_POST['type']);
  1131. unset($_POST['productid']);
  1132. unset($_POST['remise_percent']);
  1133. unset($_POST['price_ht']);
  1134. unset($_POST['multicurrency_price_ht']);
  1135. unset($_POST['price_ttc']);
  1136. unset($_POST['tva_tx']);
  1137. unset($_POST['product_ref']);
  1138. unset($_POST['product_label']);
  1139. unset($_POST['product_desc']);
  1140. unset($_POST['fournprice']);
  1141. unset($_POST['buying_price']);
  1142. unset($_POST['date_starthour']);
  1143. unset($_POST['date_startmin']);
  1144. unset($_POST['date_startsec']);
  1145. unset($_POST['date_startday']);
  1146. unset($_POST['date_startmonth']);
  1147. unset($_POST['date_startyear']);
  1148. unset($_POST['date_endhour']);
  1149. unset($_POST['date_endmin']);
  1150. unset($_POST['date_endsec']);
  1151. unset($_POST['date_endday']);
  1152. unset($_POST['date_endmonth']);
  1153. unset($_POST['date_endyear']);
  1154. } else {
  1155. setEventMessages($object->error, $object->errors, 'errors');
  1156. }
  1157. }
  1158. } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha')) {
  1159. header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition
  1160. exit();
  1161. } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) {
  1162. $idwarehouse = GETPOST('idwarehouse', 'int');
  1163. $qualified_for_stock_change = 0;
  1164. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1165. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1166. } else {
  1167. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1168. }
  1169. // Check parameters
  1170. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  1171. if (!$idwarehouse || $idwarehouse == -1) {
  1172. $error++;
  1173. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1174. $action = '';
  1175. }
  1176. }
  1177. if (!$error) {
  1178. $locationTarget = '';
  1179. $db->begin();
  1180. $result = $object->valid($user, $idwarehouse);
  1181. if ($result >= 0) {
  1182. $error = 0;
  1183. $deposit = null;
  1184. $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
  1185. if (
  1186. GETPOST('generate_deposit', 'alpha') == 'on' && !empty($deposit_percent_from_payment_terms)
  1187. && isModEnabled('facture') && $user->hasRight('facture', 'creer')
  1188. ) {
  1189. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  1190. $date = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'));
  1191. $forceFields = array();
  1192. if (GETPOSTISSET('date_pointoftax')) {
  1193. $forceFields['date_pointoftax'] = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'));
  1194. }
  1195. $deposit = Facture::createDepositFromOrigin($object, $date, GETPOST('cond_reglement_id', 'int'), $user, 0, GETPOST('validate_generated_deposit', 'alpha') == 'on', $forceFields);
  1196. if ($deposit) {
  1197. setEventMessage('DepositGenerated');
  1198. $locationTarget = DOL_URL_ROOT . '/compta/facture/card.php?id=' . $deposit->id;
  1199. } else {
  1200. $error++;
  1201. setEventMessages($object->error, $object->errors, 'errors');
  1202. }
  1203. }
  1204. // Define output language
  1205. if (! $error) {
  1206. $db->commit();
  1207. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  1208. $outputlangs = $langs;
  1209. $newlang = '';
  1210. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1211. $newlang = GETPOST('lang_id', 'aZ09');
  1212. }
  1213. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  1214. $newlang = $object->thirdparty->default_lang;
  1215. }
  1216. if (!empty($newlang)) {
  1217. $outputlangs = new Translate("", $conf);
  1218. $outputlangs->setDefaultLang($newlang);
  1219. }
  1220. $model = $object->model_pdf;
  1221. $ret = $object->fetch($id); // Reload to get new records
  1222. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1223. if ($deposit) {
  1224. $deposit->fetch($deposit->id); // Reload to get new records
  1225. $deposit->generateDocument($deposit->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1226. }
  1227. }
  1228. if ($locationTarget) {
  1229. header('Location: ' . $locationTarget);
  1230. exit;
  1231. }
  1232. } else {
  1233. $db->rollback();
  1234. }
  1235. } else {
  1236. $db->rollback();
  1237. setEventMessages($object->error, $object->errors, 'errors');
  1238. }
  1239. }
  1240. } elseif ($action == 'confirm_modif' && $usercancreate) {
  1241. // Go back to draft status
  1242. $idwarehouse = GETPOST('idwarehouse');
  1243. $qualified_for_stock_change = 0;
  1244. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1245. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1246. } else {
  1247. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1248. }
  1249. // Check parameters
  1250. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  1251. if (!$idwarehouse || $idwarehouse == -1) {
  1252. $error++;
  1253. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1254. $action = '';
  1255. }
  1256. }
  1257. if (!$error) {
  1258. $result = $object->setDraft($user, $idwarehouse);
  1259. if ($result >= 0) {
  1260. // Define output language
  1261. if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
  1262. $outputlangs = $langs;
  1263. $newlang = '';
  1264. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1265. $newlang = GETPOST('lang_id', 'aZ09');
  1266. }
  1267. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  1268. $newlang = $object->thirdparty->default_lang;
  1269. }
  1270. if (!empty($newlang)) {
  1271. $outputlangs = new Translate("", $conf);
  1272. $outputlangs->setDefaultLang($newlang);
  1273. }
  1274. $model = $object->model_pdf;
  1275. $ret = $object->fetch($id); // Reload to get new records
  1276. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1277. }
  1278. } else {
  1279. setEventMessages($object->error, $object->errors, 'errors');
  1280. }
  1281. }
  1282. } elseif ($action == 'confirm_shipped' && $confirm == 'yes' && $usercanclose) {
  1283. $result = $object->cloture($user);
  1284. if ($result < 0) {
  1285. setEventMessages($object->error, $object->errors, 'errors');
  1286. }
  1287. } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) {
  1288. $idwarehouse = GETPOST('idwarehouse', 'int');
  1289. $qualified_for_stock_change = 0;
  1290. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1291. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1292. } else {
  1293. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1294. }
  1295. // Check parameters
  1296. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  1297. if (!$idwarehouse || $idwarehouse == -1) {
  1298. $error++;
  1299. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1300. $action = '';
  1301. }
  1302. }
  1303. if (!$error) {
  1304. $result = $object->cancel($idwarehouse);
  1305. if ($result < 0) {
  1306. setEventMessages($object->error, $object->errors, 'errors');
  1307. }
  1308. }
  1309. }
  1310. if ($action == 'update_extras') {
  1311. $object->oldcopy = dol_clone($object, 2);
  1312. // Fill array 'array_options' with data from update form
  1313. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  1314. if ($ret < 0) {
  1315. $error++;
  1316. }
  1317. if (!$error) {
  1318. // Actions on extra fields
  1319. $result = $object->insertExtraFields('ORDER_MODIFY');
  1320. if ($result < 0) {
  1321. setEventMessages($object->error, $object->errors, 'errors');
  1322. $error++;
  1323. }
  1324. }
  1325. if ($error) {
  1326. $action = 'edit_extras';
  1327. }
  1328. }
  1329. // add lines from objectlinked
  1330. if ($action == 'import_lines_from_object'
  1331. && $usercancreate
  1332. && $object->statut == Commande::STATUS_DRAFT
  1333. ) {
  1334. $fromElement = GETPOST('fromelement');
  1335. $fromElementid = GETPOST('fromelementid');
  1336. $importLines = GETPOST('line_checkbox');
  1337. if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
  1338. if ($fromElement == 'commande') {
  1339. dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
  1340. $lineClassName = 'OrderLine';
  1341. } elseif ($fromElement == 'propal') {
  1342. dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
  1343. $lineClassName = 'PropaleLigne';
  1344. } elseif ($fromElement == 'facture') {
  1345. dol_include_once('/compta/'.$fromElement.'/class/'.$fromElement.'.class.php');
  1346. $lineClassName = 'FactureLigne';
  1347. }
  1348. $nextRang = count($object->lines) + 1;
  1349. $importCount = 0;
  1350. $error = 0;
  1351. foreach ($importLines as $lineId) {
  1352. $lineId = intval($lineId);
  1353. $originLine = new $lineClassName($db);
  1354. if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
  1355. $originLine->fetch_optionals();
  1356. $desc = $originLine->desc;
  1357. $pu_ht = $originLine->subprice;
  1358. $qty = $originLine->qty;
  1359. $txtva = $originLine->tva_tx;
  1360. $txlocaltax1 = $originLine->localtax1_tx;
  1361. $txlocaltax2 = $originLine->localtax2_tx;
  1362. $fk_product = $originLine->fk_product;
  1363. $remise_percent = $originLine->remise_percent;
  1364. $date_start = $originLine->date_start;
  1365. $date_end = $originLine->date_end;
  1366. $ventil = 0;
  1367. $info_bits = $originLine->info_bits;
  1368. $fk_remise_except = $originLine->fk_remise_except;
  1369. $price_base_type = 'HT';
  1370. $pu_ttc = 0;
  1371. $type = $originLine->product_type;
  1372. $rang = $nextRang++;
  1373. $special_code = $originLine->special_code;
  1374. $origin = $originLine->element;
  1375. $origin_id = $originLine->id;
  1376. $fk_parent_line = 0;
  1377. $fk_fournprice = $originLine->fk_fournprice;
  1378. $pa_ht = $originLine->pa_ht;
  1379. $label = $originLine->label;
  1380. $array_options = $originLine->array_options;
  1381. $situation_percent = 100;
  1382. $fk_prev_id = '';
  1383. $fk_unit = $originLine->fk_unit;
  1384. $pu_ht_devise = $originLine->multicurrency_subprice;
  1385. $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $date_start, $date_end, $type, $rang, $special_code, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $fk_unit, $origin, $origin_id, $pu_ht_devise);
  1386. if ($res > 0) {
  1387. $importCount++;
  1388. } else {
  1389. $error++;
  1390. }
  1391. } else {
  1392. $error++;
  1393. }
  1394. }
  1395. if ($error) {
  1396. setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
  1397. }
  1398. }
  1399. }
  1400. // Actions when printing a doc from card
  1401. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1402. // Actions to build doc
  1403. $upload_dir = !empty($conf->commande->multidir_output[$object->entity]) ? $conf->commande->multidir_output[$object->entity] : $conf->commande->dir_output;
  1404. $permissiontoadd = $usercancreate;
  1405. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1406. // Actions to send emails
  1407. $triggersendname = 'ORDER_SENTBYMAIL';
  1408. $paramname = 'id';
  1409. $autocopy = 'MAIN_MAIL_AUTOCOPY_ORDER_TO'; // used to know the automatic BCC to add
  1410. $trackid = 'ord'.$object->id;
  1411. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1412. if (!$error && getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB') && $usercancreate) {
  1413. if ($action == 'addcontact') {
  1414. if ($object->id > 0) {
  1415. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1416. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  1417. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  1418. }
  1419. if ($result >= 0) {
  1420. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1421. exit();
  1422. } else {
  1423. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1424. $langs->load("errors");
  1425. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1426. } else {
  1427. setEventMessages($object->error, $object->errors, 'errors');
  1428. }
  1429. }
  1430. } elseif ($action == 'swapstatut') {
  1431. // bascule du statut d'un contact
  1432. if ($object->id > 0) {
  1433. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  1434. } else {
  1435. dol_print_error($db);
  1436. }
  1437. } elseif ($action == 'deletecontact') {
  1438. // Efface un contact
  1439. $result = $object->delete_contact($lineid);
  1440. if ($result >= 0) {
  1441. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1442. exit();
  1443. } else {
  1444. dol_print_error($db);
  1445. }
  1446. }
  1447. }
  1448. }
  1449. /*
  1450. * View
  1451. */
  1452. $title = $object->ref." - ".$langs->trans('Card');
  1453. if ($action == 'create') {
  1454. $title = $langs->trans("NewOrder");
  1455. }
  1456. $help_url = 'EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes|DE:Modul_Kundenaufträge';
  1457. llxHeader('', $title, $help_url);
  1458. $form = new Form($db);
  1459. $formfile = new FormFile($db);
  1460. $formorder = new FormOrder($db);
  1461. $formmargin = new FormMargin($db);
  1462. if (isModEnabled('project')) {
  1463. $formproject = new FormProjets($db);
  1464. }
  1465. // Mode creation
  1466. if ($action == 'create' && $usercancreate) {
  1467. print load_fiche_titre($langs->trans('CreateOrder'), '', 'order');
  1468. $soc = new Societe($db);
  1469. if ($socid > 0) {
  1470. $res = $soc->fetch($socid);
  1471. }
  1472. //$remise_absolue = 0;
  1473. $currency_code = $conf->currency;
  1474. $cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  1475. $deposit_percent = GETPOST('cond_reglement_id_deposit_percent', 'alpha');
  1476. $mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1477. $fk_account = GETPOST('fk_account', 'int');
  1478. if (!empty($origin) && !empty($originid)) {
  1479. // Parse element/subelement (ex: project_task)
  1480. $element = $subelement = $origin;
  1481. $regs = array();
  1482. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1483. $element = $regs[1];
  1484. $subelement = $regs[2];
  1485. }
  1486. if ($element == 'project') {
  1487. $projectid = $originid;
  1488. if (!$cond_reglement_id) {
  1489. $cond_reglement_id = $soc->cond_reglement_id;
  1490. }
  1491. if (!$deposit_percent) {
  1492. $deposit_percent = $soc->deposit_percent;
  1493. }
  1494. if (!$mode_reglement_id) {
  1495. $mode_reglement_id = $soc->mode_reglement_id;
  1496. }
  1497. if (!$remise_percent) {
  1498. $remise_percent = $soc->remise_percent;
  1499. }
  1500. /*if (!$dateorder) {
  1501. // Do not set 0 here (0 for a date is 1970)
  1502. $dateorder = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : '') : $dateorder);
  1503. }*/
  1504. } else {
  1505. // For compatibility
  1506. if ($element == 'order' || $element == 'commande') {
  1507. $element = $subelement = 'commande';
  1508. } elseif ($element == 'propal') {
  1509. $element = 'comm/propal';
  1510. $subelement = 'propal';
  1511. } elseif ($element == 'contract') {
  1512. $element = $subelement = 'contrat';
  1513. }
  1514. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  1515. $classname = ucfirst($subelement);
  1516. $objectsrc = new $classname($db);
  1517. $objectsrc->fetch($originid);
  1518. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  1519. $objectsrc->fetch_lines();
  1520. }
  1521. $objectsrc->fetch_thirdparty();
  1522. // Replicate extrafields
  1523. $objectsrc->fetch_optionals();
  1524. $object->array_options = $objectsrc->array_options;
  1525. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  1526. $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
  1527. $soc = $objectsrc->thirdparty;
  1528. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
  1529. $deposit_percent = (!empty($objectsrc->deposit_percent) ? $objectsrc->deposit_percent : (!empty($soc->deposit_percent) ? $soc->deposit_percent : null));
  1530. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  1531. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  1532. $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : 0);
  1533. $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0));
  1534. $warehouse_id = (!empty($objectsrc->warehouse_id) ? $objectsrc->warehouse_id : (!empty($soc->warehouse_id) ? $soc->warehouse_id : 0));
  1535. $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
  1536. //$remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  1537. //$remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  1538. $dateorder = !getDolGlobalString('MAIN_AUTOFILL_DATE_ORDER') ? -1 : '';
  1539. $date_delivery = (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : '');
  1540. if (isModEnabled("multicurrency")) {
  1541. if (!empty($objectsrc->multicurrency_code)) {
  1542. $currency_code = $objectsrc->multicurrency_code;
  1543. }
  1544. if (getDolGlobalString('MULTICURRENCY_USE_ORIGIN_TX') && !empty($objectsrc->multicurrency_tx)) {
  1545. $currency_tx = $objectsrc->multicurrency_tx;
  1546. }
  1547. }
  1548. $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null));
  1549. $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null));
  1550. // Object source contacts list
  1551. $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
  1552. }
  1553. } else {
  1554. $cond_reglement_id = empty($soc->cond_reglement_id) ? $cond_reglement_id : $soc->cond_reglement_id;
  1555. $deposit_percent = empty($soc->deposit_percent) ? $deposit_percent : $soc->deposit_percent;
  1556. $mode_reglement_id = empty($soc->mode_reglement_id) ? $mode_reglement_id : $soc->mode_reglement_id;
  1557. $fk_account = empty($soc->mode_reglement_id) ? $fk_account : $soc->fk_account;
  1558. $availability_id = 0;
  1559. $shipping_method_id = $soc->shipping_method_id;
  1560. $warehouse_id = $soc->fk_warehouse;
  1561. $demand_reason_id = $soc->demand_reason_id;
  1562. //$remise_percent = $soc->remise_percent;
  1563. //$remise_absolue = 0;
  1564. $dateorder = !getDolGlobalString('MAIN_AUTOFILL_DATE_ORDER') ? -1 : '';
  1565. if (isModEnabled("multicurrency") && !empty($soc->multicurrency_code)) {
  1566. $currency_code = $soc->multicurrency_code;
  1567. }
  1568. $note_private = $object->getDefaultCreateValueFor('note_private');
  1569. $note_public = $object->getDefaultCreateValueFor('note_public');
  1570. }
  1571. // If form was posted (but error returned), we must reuse the value posted in priority (standard Dolibarr behaviour)
  1572. if (!GETPOST('changecompany')) {
  1573. if (GETPOSTISSET('cond_reglement_id')) {
  1574. $cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  1575. }
  1576. if (GETPOSTISSET('deposit_percent')) {
  1577. $deposit_percent = price2num(GETPOST('deposit_percent', 'alpha'));
  1578. }
  1579. if (GETPOSTISSET('mode_reglement_id')) {
  1580. $mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1581. }
  1582. if (GETPOSTISSET('cond_reglement_id')) {
  1583. $fk_account = GETPOST('fk_account', 'int');
  1584. }
  1585. }
  1586. // Warehouse default if null
  1587. if ($soc->fk_warehouse > 0) {
  1588. $warehouse_id = $soc->fk_warehouse;
  1589. }
  1590. if (isModEnabled('stock') && empty($warehouse_id) && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
  1591. if (empty($object->warehouse_id) && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE')) {
  1592. $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE;
  1593. }
  1594. if (empty($object->warehouse_id) && getDolGlobalString('MAIN_DEFAULT_WAREHOUSE_USER')) {
  1595. $warehouse_id = $user->fk_warehouse;
  1596. }
  1597. }
  1598. print '<form name="crea_commande" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  1599. print '<input type="hidden" name="token" value="'.newToken().'">';
  1600. print '<input type="hidden" name="action" value="add">';
  1601. print '<input type="hidden" name="changecompany" value="0">'; // will be set to 1 by javascript so we know post is done after a company change
  1602. print '<input type="hidden" name="remise_percent" value="'.$soc->remise_percent.'">';
  1603. print '<input type="hidden" name="origin" value="'.$origin.'">';
  1604. print '<input type="hidden" name="originid" value="'.$originid.'">';
  1605. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  1606. if (!empty($currency_tx)) {
  1607. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  1608. }
  1609. print dol_get_fiche_head('');
  1610. // Call Hook tabContentCreateOrder
  1611. $parameters = array();
  1612. // Note that $action and $object may be modified by hook
  1613. $reshook = $hookmanager->executeHooks('tabContentCreateOrder', $parameters, $object, $action);
  1614. if (empty($reshook)) {
  1615. print '<table class="border centpercent">';
  1616. // Reference
  1617. print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td>'.$langs->trans("Draft").'</td></tr>';
  1618. // Reference client
  1619. print '<tr><td>'.$langs->trans('RefCustomer').'</td><td>';
  1620. if (getDolGlobalString('MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER') && !empty($origin) && !empty($originid)) {
  1621. print '<input type="text" name="ref_client" value="'.$ref_client.'"></td>';
  1622. } else {
  1623. print '<input type="text" name="ref_client" value="'.GETPOST('ref_client').'"></td>';
  1624. }
  1625. print '</tr>';
  1626. // Thirdparty
  1627. print '<tr>';
  1628. print '<td class="fieldrequired">'.$langs->trans('Customer').'</td>';
  1629. if ($socid > 0) {
  1630. print '<td>';
  1631. print $soc->getNomUrl(1, 'customer');
  1632. print '<input type="hidden" name="socid" value="'.$soc->id.'">';
  1633. print '</td>';
  1634. } else {
  1635. print '<td class="valuefieldcreate">';
  1636. $filter = '((s.client:IN:1,2,3) AND (s.status:=:1))';
  1637. print img_picto('', 'company', 'class="pictofixedwidth"').$form->select_company('', 'socid', $filter, 'SelectThirdParty', 1, 0, null, 0, 'minwidth175 maxwidth500 widthcentpercentminusxx');
  1638. // reload page to retrieve customer informations
  1639. if (!getDolGlobalString('RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED')) {
  1640. print '<script>
  1641. $(document).ready(function() {
  1642. $("#socid").change(function() {
  1643. console.log("We have changed the company - Reload page");
  1644. var socid = $(this).val();
  1645. // reload page
  1646. $("input[name=action]").val("create");
  1647. $("input[name=changecompany]").val("1");
  1648. $("form[name=crea_commande]").submit();
  1649. });
  1650. });
  1651. </script>';
  1652. }
  1653. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  1654. print '</td>';
  1655. }
  1656. print '</tr>'."\n";
  1657. // Contact of order
  1658. if ($socid > 0) {
  1659. // Contacts (ask contact only if thirdparty already defined).
  1660. print "<tr><td>".$langs->trans("DefaultContact").'</td><td>';
  1661. print img_picto('', 'contact', 'class="pictofixedwidth"');
  1662. print $form->selectcontacts($soc->id, $contactid, 'contactid', 1, !empty($srccontactslist) ? $srccontactslist : "", '', 1, 'maxwidth200 widthcentpercentminusx');
  1663. print '</td></tr>';
  1664. // Ligne info remises tiers
  1665. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  1666. $absolute_discount = $soc->getAvailableDiscounts();
  1667. $thirdparty = $soc;
  1668. $discount_type = 0;
  1669. $backtopage = $_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.urlencode(GETPOST('origin')).'&originid='.urlencode(GETPOSTINT('originid'));
  1670. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  1671. print '</td></tr>';
  1672. }
  1673. // Date
  1674. print '<tr><td class="fieldrequired">'.$langs->trans('Date').'</td><td>';
  1675. print img_picto('', 'action', 'class="pictofixedwidth"');
  1676. print $form->selectDate('', 're', '', '', '', "crea_commande", 1, 1); // Always autofill date with current date
  1677. print '</td></tr>';
  1678. // Date delivery planned
  1679. print '<tr><td>'.$langs->trans("DateDeliveryPlanned").'</td>';
  1680. print '<td colspan="3">';
  1681. $date_delivery = ($date_delivery ? $date_delivery : $object->delivery_date);
  1682. print img_picto('', 'action', 'class="pictofixedwidth"');
  1683. print $form->selectDate($date_delivery ? $date_delivery : -1, 'liv_', 1, 1, 1);
  1684. print "</td>\n";
  1685. print '</tr>';
  1686. // Delivery delay
  1687. print '<tr class="fielddeliverydelay"><td>'.$langs->trans('AvailabilityPeriod').'</td><td>';
  1688. print img_picto('', 'clock', 'class="pictofixedwidth"');
  1689. $form->selectAvailabilityDelay((GETPOSTISSET('availability_id') ? GETPOST('availability_id') : $availability_id), 'availability_id', '', 1, 'maxwidth200 widthcentpercentminusx');
  1690. print '</td></tr>';
  1691. // Terms of payment
  1692. print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
  1693. print img_picto('', 'payment', 'class="pictofixedwidth"');
  1694. print $form->getSelectConditionsPaiements($cond_reglement_id, 'cond_reglement_id', 1, 1, 0, 'maxwidth200 widthcentpercentminusx', $deposit_percent);
  1695. print '</td></tr>';
  1696. // Payment mode
  1697. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
  1698. print img_picto('', 'bank', 'class="pictofixedwidth"');
  1699. print $form->select_types_paiements($mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx', 1);
  1700. print '</td></tr>';
  1701. // Bank Account
  1702. if (getDolGlobalString('BANK_ASK_PAYMENT_BANK_DURING_ORDER') && isModEnabled("banque")) {
  1703. print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
  1704. print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes($fk_account, 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  1705. print '</td></tr>';
  1706. }
  1707. // Shipping Method
  1708. if (isModEnabled('expedition')) {
  1709. print '<tr><td>'.$langs->trans('SendingMethod').'</td><td>';
  1710. print img_picto('', 'object_dolly', 'class="pictofixedwidth"');
  1711. $form->selectShippingMethod(((GETPOSTISSET('shipping_method_id') && GETPOST('shipping_method_id', 'int') != 0) ? GETPOST('shipping_method_id') : $shipping_method_id), 'shipping_method_id', '', 1, '', 0, 'maxwidth200 widthcentpercentminusx');
  1712. print '</td></tr>';
  1713. }
  1714. // Warehouse
  1715. if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
  1716. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  1717. $formproduct = new FormProduct($db);
  1718. print '<tr><td>'.$langs->trans('Warehouse').'</td><td>';
  1719. print img_picto('', 'stock', 'class="pictofixedwidth"').$formproduct->selectWarehouses((GETPOSTISSET('warehouse_id') ? GETPOST('warehouse_id') : $warehouse_id), 'warehouse_id', '', 1, 0, 0, '', 0, 0, array(), 'maxwidth500 widthcentpercentminusxx');
  1720. print '</td></tr>';
  1721. }
  1722. // Source / Channel - What trigger creation
  1723. print '<tr><td>'.$langs->trans('Channel').'</td><td>';
  1724. print img_picto('', 'question', 'class="pictofixedwidth"');
  1725. $form->selectInputReason((GETPOSTISSET('demand_reason_id') ? GETPOST('demand_reason_id') : $demand_reason_id), 'demand_reason_id', '', 1, 'maxwidth200 widthcentpercentminusx');
  1726. print '</td></tr>';
  1727. // TODO How record was recorded OrderMode (llx_c_input_method)
  1728. // Project
  1729. if (isModEnabled('project')) {
  1730. $langs->load("projects");
  1731. print '<tr>';
  1732. print '<td>'.$langs->trans("Project").'</td><td>';
  1733. print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects(($soc->id > 0 ? $soc->id : -1), (GETPOSTISSET('projectid') ? GETPOST('projectid') : $projectid), 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  1734. print ' <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>';
  1735. print '</td>';
  1736. print '</tr>';
  1737. }
  1738. // Incoterms
  1739. if (isModEnabled('incoterm')) {
  1740. print '<tr>';
  1741. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), !empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms, 1).'</label></td>';
  1742. print '<td class="maxwidthonsmartphone">';
  1743. $incoterm_id = GETPOST('incoterm_id');
  1744. $location_incoterms = GETPOST('location_incoterms');
  1745. if (empty($incoterm_id)) {
  1746. $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
  1747. $location_incoterms = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
  1748. }
  1749. print img_picto('', 'incoterm', 'class="pictofixedwidth"');
  1750. print $form->select_incoterms($incoterm_id, $location_incoterms);
  1751. print '</td></tr>';
  1752. }
  1753. // Other attributes
  1754. $parameters = array();
  1755. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  1756. $parameters['objectsrc'] = $objectsrc;
  1757. }
  1758. $parameters['socid'] = $socid;
  1759. // Note that $action and $object may be modified by hook
  1760. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action);
  1761. print $hookmanager->resPrint;
  1762. if (empty($reshook)) {
  1763. if (getDolGlobalString('THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_ORDER') && !empty($soc->id)) {
  1764. // copy from thirdparty
  1765. $tpExtrafields = new ExtraFields($db);
  1766. $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
  1767. if ($soc->fetch_optionals() > 0) {
  1768. $object->array_options = array_merge($object->array_options, $soc->array_options);
  1769. }
  1770. }
  1771. print $object->showOptionals($extrafields, 'create', $parameters);
  1772. }
  1773. // Template to use by default
  1774. print '<tr><td>'.$langs->trans('DefaultModel').'</td>';
  1775. print '<td>';
  1776. include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
  1777. $liste = ModelePDFCommandes::liste_modeles($db);
  1778. $preselected = $conf->global->COMMANDE_ADDON_PDF;
  1779. print img_picto('', 'pdf', 'class="pictofixedwidth"');
  1780. print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
  1781. print "</td></tr>";
  1782. // Multicurrency
  1783. if (isModEnabled("multicurrency")) {
  1784. print '<tr>';
  1785. print '<td>'.$form->editfieldkey("Currency", 'multicurrency_code', '', $object, 0).'</td>';
  1786. print '<td class="maxwidthonsmartphone">';
  1787. print img_picto('', 'currency', 'class="pictofixedwidth"').$form->selectMultiCurrency(((GETPOSTISSET('multicurrency_code') && !GETPOST('changecompany')) ? GETPOST('multicurrency_code') : $currency_code), 'multicurrency_code', 0, '', false, 'maxwidth200 widthcentpercentminusx');
  1788. print '</td></tr>';
  1789. }
  1790. // Note public
  1791. print '<tr>';
  1792. print '<td class="tdtop">'.$langs->trans('NotePublic').'</td>';
  1793. print '<td>';
  1794. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PUBLIC') ? 0 : 1, ROWS_3, '90%');
  1795. print $doleditor->Create(1);
  1796. // print '<textarea name="note_public" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_public.'</textarea>';
  1797. print '</td></tr>';
  1798. // Note private
  1799. if (empty($user->socid)) {
  1800. print '<tr>';
  1801. print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>';
  1802. print '<td>';
  1803. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, !getDolGlobalString('FCKEDITOR_ENABLE_NOTE_PRIVATE') ? 0 : 1, ROWS_3, '90%');
  1804. print $doleditor->Create(1);
  1805. // print '<textarea name="note" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'</textarea>';
  1806. print '</td></tr>';
  1807. }
  1808. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  1809. // TODO for compatibility
  1810. if ($origin == 'contrat') {
  1811. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  1812. //$objectsrc->remise_absolue = $remise_absolue;
  1813. //$objectsrc->remise_percent = $remise_percent;
  1814. $objectsrc->update_price(1);
  1815. }
  1816. print "\n<!-- ".$classname." info -->";
  1817. print "\n";
  1818. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  1819. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  1820. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  1821. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  1822. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  1823. switch ($classname) {
  1824. case 'Propal':
  1825. $newclassname = 'CommercialProposal';
  1826. break;
  1827. case 'Commande':
  1828. $newclassname = 'Order';
  1829. break;
  1830. case 'Expedition':
  1831. $newclassname = 'Sending';
  1832. break;
  1833. case 'Contrat':
  1834. $newclassname = 'Contract';
  1835. break;
  1836. default:
  1837. $newclassname = $classname;
  1838. }
  1839. print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1).'</td></tr>';
  1840. // Amount
  1841. print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
  1842. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
  1843. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE
  1844. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
  1845. }
  1846. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF
  1847. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
  1848. }
  1849. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
  1850. if (isModEnabled("multicurrency")) {
  1851. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  1852. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
  1853. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
  1854. }
  1855. }
  1856. print "\n";
  1857. print '</table>';
  1858. }
  1859. print dol_get_fiche_end();
  1860. print $form->buttonsSaveCancel("CreateDraft");
  1861. // Show origin lines
  1862. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  1863. $title = $langs->trans('ProductsAndServices');
  1864. print load_fiche_titre($title);
  1865. print '<div class="div-table-responsive-no-min">';
  1866. print '<table class="noborder centpercent">';
  1867. $objectsrc->printOriginLinesList('', $selectedLines);
  1868. print '</table>';
  1869. print '</div>';
  1870. }
  1871. print '</form>';
  1872. } else {
  1873. // Mode view
  1874. $now = dol_now();
  1875. if ($object->id > 0) {
  1876. $product_static = new Product($db);
  1877. $soc = new Societe($db);
  1878. $soc->fetch($object->socid);
  1879. $author = new User($db);
  1880. $author->fetch($object->user_author_id);
  1881. $object->fetch_thirdparty();
  1882. $res = $object->fetch_optionals();
  1883. $head = commande_prepare_head($object);
  1884. print dol_get_fiche_head($head, 'order', $langs->trans("CustomerOrder"), -1, 'order');
  1885. $formconfirm = '';
  1886. // Confirmation to delete
  1887. if ($action == 'delete') {
  1888. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 1);
  1889. }
  1890. // Confirmation of validation
  1891. if ($action == 'validate') {
  1892. // We check that object has a temporary ref
  1893. $ref = substr($object->ref, 1, 4);
  1894. if ($ref == 'PROV' || $ref == '') {
  1895. $numref = $object->getNextNumRef($soc);
  1896. if (empty($numref)) {
  1897. $error++;
  1898. setEventMessages($object->error, $object->errors, 'errors');
  1899. }
  1900. } else {
  1901. $numref = $object->ref;
  1902. }
  1903. $text = $langs->trans('ConfirmValidateOrder', $numref);
  1904. if (isModEnabled('notification')) {
  1905. require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
  1906. $notify = new Notify($db);
  1907. $text .= '<br>';
  1908. $text .= $notify->confirmMessage('ORDER_VALIDATE', $object->socid, $object);
  1909. }
  1910. $qualified_for_stock_change = 0;
  1911. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  1912. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1913. } else {
  1914. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1915. }
  1916. $formquestion = array();
  1917. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  1918. $langs->load("stocks");
  1919. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  1920. $formproduct = new FormProduct($db);
  1921. $forcecombo = 0;
  1922. if ($conf->browser->name == 'ie') {
  1923. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  1924. }
  1925. $formquestion = array(
  1926. // 'text' => $langs->trans("ConfirmClone"),
  1927. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  1928. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  1929. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int') ? GETPOST('idwarehouse', 'int') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
  1930. );
  1931. }
  1932. // mandatoryPeriod
  1933. $nbMandated = 0;
  1934. foreach ($object->lines as $line) {
  1935. $res = $line->fetch_product();
  1936. if ($res > 0) {
  1937. if ($line->product->isService() && $line->product->isMandatoryPeriod() && (empty($line->date_start) || empty($line->date_end))) {
  1938. $nbMandated++;
  1939. break;
  1940. }
  1941. }
  1942. }
  1943. if ($nbMandated > 0) {
  1944. $text .= '<div><span class="clearboth nowraponall warning">'.$langs->trans("mandatoryPeriodNeedTobeSetMsgValidate").'</span></div>';
  1945. }
  1946. if (getDolGlobalInt('SALE_ORDER_SUGGEST_DOWN_PAYMENT_INVOICE_CREATION')) {
  1947. // This is a hidden option:
  1948. // Suggestion to create invoice during order validation is not enabled by default.
  1949. // Such choice should be managed by the workflow module and trigger. This option generates conflicts with some setup.
  1950. // It may also break step of creating an order when invoicing must be done from proposals and not from orders
  1951. $deposit_percent_from_payment_terms = getDictionaryValue('c_payment_term', 'deposit_percent', $object->cond_reglement_id);
  1952. if (!empty($deposit_percent_from_payment_terms) && isModEnabled('facture') && $user->hasRight('facture', 'creer')) {
  1953. require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
  1954. $object->fetchObjectLinked();
  1955. $eligibleForDepositGeneration = true;
  1956. if (array_key_exists('facture', $object->linkedObjects)) {
  1957. foreach ($object->linkedObjects['facture'] as $invoice) {
  1958. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  1959. $eligibleForDepositGeneration = false;
  1960. break;
  1961. }
  1962. }
  1963. }
  1964. if ($eligibleForDepositGeneration && array_key_exists('propal', $object->linkedObjects)) {
  1965. foreach ($object->linkedObjects['propal'] as $proposal) {
  1966. $proposal->fetchObjectLinked();
  1967. if (array_key_exists('facture', $proposal->linkedObjects)) {
  1968. foreach ($proposal->linkedObjects['facture'] as $invoice) {
  1969. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  1970. $eligibleForDepositGeneration = false;
  1971. break 2;
  1972. }
  1973. }
  1974. }
  1975. }
  1976. }
  1977. if ($eligibleForDepositGeneration) {
  1978. $formquestion[] = array(
  1979. 'type' => 'checkbox',
  1980. 'tdclass' => '',
  1981. 'name' => 'generate_deposit',
  1982. 'label' => $form->textwithpicto($langs->trans('GenerateDeposit', $object->deposit_percent), $langs->trans('DepositGenerationPermittedByThePaymentTermsSelected'))
  1983. );
  1984. $formquestion[] = array(
  1985. 'type' => 'date',
  1986. 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
  1987. 'name' => 'datef',
  1988. 'label' => $langs->trans('DateInvoice'),
  1989. 'value' => dol_now(),
  1990. 'datenow' => true
  1991. );
  1992. if (getDolGlobalString('INVOICE_POINTOFTAX_DATE')) {
  1993. $formquestion[] = array(
  1994. 'type' => 'date',
  1995. 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
  1996. 'name' => 'date_pointoftax',
  1997. 'label' => $langs->trans('DatePointOfTax'),
  1998. 'value' => dol_now(),
  1999. 'datenow' => true
  2000. );
  2001. }
  2002. $paymentTermsSelect = $form->getSelectConditionsPaiements(0, 'cond_reglement_id', -1, 0, 0, 'minwidth200');
  2003. $formquestion[] = array(
  2004. 'type' => 'other',
  2005. 'tdclass' => 'fieldrequired showonlyifgeneratedeposit',
  2006. 'name' => 'cond_reglement_id',
  2007. 'label' => $langs->trans('PaymentTerm'),
  2008. 'value' => $paymentTermsSelect
  2009. );
  2010. $formquestion[] = array(
  2011. 'type' => 'checkbox',
  2012. 'tdclass' => 'showonlyifgeneratedeposit',
  2013. 'name' => 'validate_generated_deposit',
  2014. 'label' => $langs->trans('ValidateGeneratedDeposit')
  2015. );
  2016. $formquestion[] = array(
  2017. 'type' => 'onecolumn',
  2018. 'value' => '
  2019. <script>
  2020. $(document).ready(function() {
  2021. $("[name=generate_deposit]").change(function () {
  2022. let $self = $(this);
  2023. let $target = $(".showonlyifgeneratedeposit").parent(".tagtr");
  2024. if (! $self.parents(".tagtr").is(":hidden") && $self.is(":checked")) {
  2025. $target.show();
  2026. } else {
  2027. $target.hide();
  2028. }
  2029. return true;
  2030. });
  2031. });
  2032. </script>
  2033. '
  2034. );
  2035. }
  2036. }
  2037. }
  2038. if (!$error) {
  2039. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_validate', $formquestion, 0, 1, 220);
  2040. }
  2041. }
  2042. // Confirm back to draft status
  2043. if ($action == 'modif') {
  2044. $qualified_for_stock_change = 0;
  2045. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  2046. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2047. } else {
  2048. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2049. }
  2050. $text = $langs->trans('ConfirmUnvalidateOrder', $object->ref);
  2051. $formquestion = array();
  2052. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  2053. $langs->load("stocks");
  2054. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2055. $formproduct = new FormProduct($db);
  2056. $forcecombo = 0;
  2057. if ($conf->browser->name == 'ie') {
  2058. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  2059. }
  2060. $formquestion = array(
  2061. // 'text' => $langs->trans("ConfirmClone"),
  2062. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  2063. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  2064. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
  2065. );
  2066. }
  2067. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateOrder'), $text, 'confirm_modif', $formquestion, "yes", 1, 220);
  2068. }
  2069. /*
  2070. * Confirmation de la cloture
  2071. */
  2072. if ($action == 'shipped') {
  2073. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('CloseOrder'), $langs->trans('ConfirmCloseOrder'), 'confirm_shipped', '', 0, 1);
  2074. }
  2075. /*
  2076. * Confirmation de l'annulation
  2077. */
  2078. if ($action == 'cancel') {
  2079. $qualified_for_stock_change = 0;
  2080. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  2081. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2082. } else {
  2083. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2084. }
  2085. $text = $langs->trans('ConfirmCancelOrder', $object->ref);
  2086. $formquestion = array();
  2087. if (isModEnabled('stock') && getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') && $qualified_for_stock_change) {
  2088. $langs->load("stocks");
  2089. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2090. $formproduct = new FormProduct($db);
  2091. $forcecombo = 0;
  2092. if ($conf->browser->name == 'ie') {
  2093. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  2094. }
  2095. $formquestion = array(
  2096. // 'text' => $langs->trans("ConfirmClone"),
  2097. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  2098. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  2099. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ? GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
  2100. );
  2101. }
  2102. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans("Cancel"), $text, 'confirm_cancel', $formquestion, 0, 1);
  2103. }
  2104. // Confirmation to delete line
  2105. if ($action == 'ask_deleteline') {
  2106. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
  2107. }
  2108. // Clone confirmation
  2109. if ($action == 'clone') {
  2110. $filter = '(s.client:IN:1,2,3)';
  2111. // Create an array for form
  2112. $formquestion = array(
  2113. array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', $filter, '', 0, 0, null, 0, 'maxwidth300'))
  2114. );
  2115. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  2116. }
  2117. // Call Hook formConfirm
  2118. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
  2119. // Note that $action and $object may be modified by hook
  2120. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action);
  2121. if (empty($reshook)) {
  2122. $formconfirm .= $hookmanager->resPrint;
  2123. } elseif ($reshook > 0) {
  2124. $formconfirm = $hookmanager->resPrint;
  2125. }
  2126. // Print form confirm
  2127. print $formconfirm;
  2128. // Order card
  2129. $linkback = '<a href="'.DOL_URL_ROOT.'/commande/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  2130. $morehtmlref = '<div class="refidno">';
  2131. // Ref customer
  2132. $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
  2133. $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':' . getDolGlobalString('THIRDPARTY_REF_INPUT_SIZE') : ''), '', null, null, '', 1);
  2134. // Thirdparty
  2135. $morehtmlref .= '<br>'.$soc->getNomUrl(1, 'customer');
  2136. if (!getDolGlobalString('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) {
  2137. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/commande/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
  2138. }
  2139. // Project
  2140. if (isModEnabled('project')) {
  2141. $langs->load("projects");
  2142. $morehtmlref .= '<br>';
  2143. if ($usercancreate) {
  2144. $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
  2145. if ($action != 'classify') {
  2146. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
  2147. }
  2148. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
  2149. } else {
  2150. if (!empty($object->fk_project)) {
  2151. $proj = new Project($db);
  2152. $proj->fetch($object->fk_project);
  2153. $morehtmlref .= $proj->getNomUrl(1);
  2154. if ($proj->title) {
  2155. $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
  2156. }
  2157. }
  2158. }
  2159. }
  2160. $morehtmlref .= '</div>';
  2161. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  2162. // Call Hook tabContentViewOrder
  2163. $parameters = array();
  2164. // Note that $action and $object may be modified by hook
  2165. $reshook = $hookmanager->executeHooks('tabContentViewOrder', $parameters, $object, $action);
  2166. if (empty($reshook)) {
  2167. print '<div class="fichecenter">';
  2168. print '<div class="fichehalfleft">';
  2169. print '<div class="underbanner clearboth"></div>';
  2170. print '<table class="border tableforfield centpercent">';
  2171. if ($soc->outstanding_limit) {
  2172. // Outstanding Bill
  2173. print '<tr><td class="titlefield">';
  2174. print $langs->trans('OutstandingBill');
  2175. print '</td><td class="valuefield">';
  2176. $arrayoutstandingbills = $soc->getOutstandingBills();
  2177. print price($arrayoutstandingbills['opened']).' / ';
  2178. print price($soc->outstanding_limit, 0, '', 1, - 1, - 1, $conf->currency);
  2179. print '</td>';
  2180. print '</tr>';
  2181. }
  2182. // Relative and absolute discounts
  2183. if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
  2184. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2185. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2186. } else {
  2187. $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
  2188. $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
  2189. }
  2190. $addrelativediscount = '<a href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditRelativeDiscounts").'</a>';
  2191. $addabsolutediscount = '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$soc->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("EditGlobalDiscounts").'</a>';
  2192. $addcreditnote = '<a href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&socid='.$soc->id.'&type=2&backtopage='.urlencode($_SERVER["PHP_SELF"]).'?facid='.$object->id.'">'.$langs->trans("AddCreditNote").'</a>';
  2193. print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td class="valuefield">';
  2194. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  2195. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  2196. $absolute_discount = price2num($absolute_discount, 'MT');
  2197. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2198. $thirdparty = $soc;
  2199. $discount_type = 0;
  2200. $backtopage = $_SERVER["PHP_SELF"].'?id='.$object->id;
  2201. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2202. print '</td></tr>';
  2203. // Date
  2204. print '<tr><td>';
  2205. $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT;
  2206. print $form->editfieldkey("Date", 'date', '', $object, $editenable);
  2207. print '</td><td class="valuefield">';
  2208. if ($action == 'editdate') {
  2209. print '<form name="setdate" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  2210. print '<input type="hidden" name="token" value="'.newToken().'">';
  2211. print '<input type="hidden" name="action" value="setdate">';
  2212. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  2213. print $form->selectDate($object->date, 'order_', '', '', '', "setdate");
  2214. print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
  2215. print '</form>';
  2216. } else {
  2217. print $object->date ? dol_print_date($object->date, 'day') : '&nbsp;';
  2218. if ($object->hasDelay() && empty($object->delivery_date)) { // If there is a delivery date planned, warning should be on this date
  2219. print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
  2220. }
  2221. }
  2222. print '</td>';
  2223. print '</tr>';
  2224. // Delivery date planed
  2225. print '<tr><td>';
  2226. $editenable = $usercancreate;
  2227. print $form->editfieldkey("DateDeliveryPlanned", 'date_livraison', '', $object, $editenable);
  2228. print '</td><td class="valuefield">';
  2229. if ($action == 'editdate_livraison') {
  2230. print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  2231. print '<input type="hidden" name="token" value="'.newToken().'">';
  2232. print '<input type="hidden" name="action" value="setdate_livraison">';
  2233. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  2234. print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', 1, 1, '', "setdate_livraison", 1, 0);
  2235. print '<input type="submit" class="button button-edit" value="'.$langs->trans('Modify').'">';
  2236. print '</form>';
  2237. } else {
  2238. print $object->delivery_date ? dol_print_date($object->delivery_date, 'dayhour') : '&nbsp;';
  2239. if ($object->hasDelay() && !empty($object->delivery_date)) {
  2240. print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
  2241. }
  2242. }
  2243. print '</td>';
  2244. print '</tr>';
  2245. // Delivery delay
  2246. print '<tr class="fielddeliverydelay"><td>';
  2247. $editenable = $usercancreate;
  2248. print $form->editfieldkey("AvailabilityPeriod", 'availability', '', $object, $editenable);
  2249. print '</td><td class="valuefield">';
  2250. if ($action == 'editavailability') {
  2251. $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'availability_id', 1);
  2252. } else {
  2253. $form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id, $object->availability_id, 'none', 1);
  2254. }
  2255. print '</td></tr>';
  2256. // Shipping Method
  2257. if (isModEnabled('expedition')) {
  2258. print '<tr><td>';
  2259. $editenable = $usercancreate;
  2260. print $form->editfieldkey("SendingMethod", 'shippingmethod', '', $object, $editenable);
  2261. print '</td><td class="valuefield">';
  2262. if ($action == 'editshippingmethod') {
  2263. $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1);
  2264. } else {
  2265. $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?id='.$object->id, $object->shipping_method_id, 'none');
  2266. }
  2267. print '</td>';
  2268. print '</tr>';
  2269. }
  2270. // Warehouse
  2271. if (isModEnabled('stock') && getDolGlobalString('WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER')) {
  2272. $langs->load('stocks');
  2273. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2274. $formproduct = new FormProduct($db);
  2275. print '<tr><td>';
  2276. $editenable = $usercancreate;
  2277. print $form->editfieldkey("Warehouse", 'warehouse', '', $object, $editenable);
  2278. print '</td><td class="valuefield">';
  2279. if ($action == 'editwarehouse') {
  2280. $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'warehouse_id', 1);
  2281. } else {
  2282. $formproduct->formSelectWarehouses($_SERVER['PHP_SELF'].'?id='.$object->id, $object->warehouse_id, 'none');
  2283. }
  2284. print '</td>';
  2285. print '</tr>';
  2286. }
  2287. // Source reason (why we have an order)
  2288. print '<tr><td>';
  2289. $editenable = $usercancreate;
  2290. print $form->editfieldkey("Source", 'demandreason', '', $object, $editenable);
  2291. print '</td><td class="valuefield">';
  2292. if ($action == 'editdemandreason') {
  2293. $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'demand_reason_id', 1);
  2294. } else {
  2295. $form->formInputReason($_SERVER['PHP_SELF'].'?id='.$object->id, $object->demand_reason_id, 'none');
  2296. }
  2297. print '</td></tr>';
  2298. // Terms of payment
  2299. print '<tr><td>';
  2300. $editenable = $usercancreate;
  2301. print $form->editfieldkey("PaymentConditionsShort", 'conditions', '', $object, $editenable);
  2302. print '</td><td class="valuefield">';
  2303. if ($action == 'editconditions') {
  2304. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id', 1, '', 1, $object->deposit_percent);
  2305. } else {
  2306. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none', 1, '', 1, $object->deposit_percent);
  2307. }
  2308. print '</td>';
  2309. print '</tr>';
  2310. // Mode of payment
  2311. print '<tr><td>';
  2312. $editenable = $usercancreate;
  2313. print $form->editfieldkey("PaymentMode", 'mode', '', $object, $editenable);
  2314. print '</td><td class="valuefield">';
  2315. if ($action == 'editmode') {
  2316. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  2317. } else {
  2318. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  2319. }
  2320. print '</td></tr>';
  2321. // Multicurrency
  2322. if (isModEnabled("multicurrency")) {
  2323. // Multicurrency code
  2324. print '<tr>';
  2325. print '<td>';
  2326. $editenable = $usercancreate && $object->statut == Commande::STATUS_DRAFT;
  2327. print $form->editfieldkey("Currency", 'multicurrencycode', '', $object, $editenable);
  2328. print '</td><td class="valuefield">';
  2329. if ($action == 'editmulticurrencycode') {
  2330. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
  2331. } else {
  2332. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
  2333. }
  2334. print '</td></tr>';
  2335. // Multicurrency rate
  2336. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2337. print '<tr>';
  2338. print '<td>';
  2339. $editenable = $usercancreate && $object->multicurrency_code && $object->multicurrency_code != $conf->currency && $object->statut == $object::STATUS_DRAFT;
  2340. print $form->editfieldkey("CurrencyRate", 'multicurrencyrate', '', $object, $editenable);
  2341. print '</td><td class="valuefield">';
  2342. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  2343. if ($action == 'actualizemulticurrencyrate') {
  2344. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  2345. }
  2346. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  2347. } else {
  2348. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  2349. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2350. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2351. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  2352. print '</div>';
  2353. }
  2354. }
  2355. print '</td></tr>';
  2356. }
  2357. }
  2358. // TODO Order mode (how we receive order). Not yet implemented
  2359. /*
  2360. print '<tr><td>';
  2361. $editenable = $usercancreate;
  2362. print $form->editfieldkey("SourceMode", 'inputmode', '', $object, $editenable);
  2363. print '</td><td>';
  2364. if ($action == 'editinputmode') {
  2365. $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'input_mode_id', 1);
  2366. } else {
  2367. $form->formInputMode($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->source, 'none');
  2368. }
  2369. print '</td></tr>';
  2370. */
  2371. $tmparray = $object->getTotalWeightVolume();
  2372. $totalWeight = $tmparray['weight'];
  2373. $totalVolume = $tmparray['volume'];
  2374. if ($totalWeight) {
  2375. print '<tr><td>'.$langs->trans("CalculatedWeight").'</td>';
  2376. print '<td class="valuefield">';
  2377. print showDimensionInBestUnit($totalWeight, 0, "weight", $langs, isset($conf->global->MAIN_WEIGHT_DEFAULT_ROUND) ? $conf->global->MAIN_WEIGHT_DEFAULT_ROUND : -1, isset($conf->global->MAIN_WEIGHT_DEFAULT_UNIT) ? $conf->global->MAIN_WEIGHT_DEFAULT_UNIT : 'no');
  2378. print '</td></tr>';
  2379. }
  2380. if ($totalVolume) {
  2381. print '<tr><td>'.$langs->trans("CalculatedVolume").'</td>';
  2382. print '<td class="valuefield">';
  2383. print showDimensionInBestUnit($totalVolume, 0, "volume", $langs, isset($conf->global->MAIN_VOLUME_DEFAULT_ROUND) ? $conf->global->MAIN_VOLUME_DEFAULT_ROUND : -1, isset($conf->global->MAIN_VOLUME_DEFAULT_UNIT) ? $conf->global->MAIN_VOLUME_DEFAULT_UNIT : 'no');
  2384. print '</td></tr>';
  2385. }
  2386. // TODO How record was recorded OrderMode (llx_c_input_method)
  2387. // Incoterms
  2388. if (isModEnabled('incoterm')) {
  2389. print '<tr><td>';
  2390. $editenable = $usercancreate;
  2391. print $form->editfieldkey("IncotermLabel", 'incoterm', '', $object, $editenable);
  2392. print '</td>';
  2393. print '<td class="valuefield">';
  2394. if ($action != 'editincoterm') {
  2395. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  2396. } else {
  2397. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  2398. }
  2399. print '</td></tr>';
  2400. }
  2401. // Bank Account
  2402. if (getDolGlobalString('BANK_ASK_PAYMENT_BANK_DURING_ORDER') && isModEnabled("banque")) {
  2403. print '<tr><td>';
  2404. $editenable = $usercancreate;
  2405. print $form->editfieldkey("BankAccount", 'bankaccount', '', $object, $editenable);
  2406. print '</td><td class="valuefield">';
  2407. if ($action == 'editbankaccount') {
  2408. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  2409. } else {
  2410. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  2411. }
  2412. print '</td>';
  2413. print '</tr>';
  2414. }
  2415. // Other attributes
  2416. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  2417. print '</table>';
  2418. print '</div>';
  2419. print '<div class="fichehalfright">';
  2420. print '<div class="underbanner clearboth"></div>';
  2421. print '<table class="border tableforfield centpercent">';
  2422. $alert = '';
  2423. if (getDolGlobalString('ORDER_MANAGE_MIN_AMOUNT') && $object->total_ht < $object->thirdparty->order_min_amount) {
  2424. $alert = ' ' . img_warning($langs->trans('OrderMinAmount') . ': ' . price($object->thirdparty->order_min_amount));
  2425. }
  2426. print '<tr>';
  2427. print '<td class="titlefieldmiddle">' . $langs->trans('AmountHT') . '</td>';
  2428. print '<td class="nowrap amountcard right">' . price($object->total_ht, '', $langs, 0, -1, -1, $conf->currency) . '</td>';
  2429. if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
  2430. // Multicurrency Amount HT
  2431. print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_ht, '', $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
  2432. }
  2433. print '</tr>';
  2434. print '<tr>';
  2435. print '<td class="titlefieldmiddle">' . $langs->trans('AmountVAT') . '</td>';
  2436. print '<td class="nowrap amountcard right">' . price($object->total_tva, '', $langs, 0, -1, -1, $conf->currency) . '</td>';
  2437. if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
  2438. // Multicurrency Amount VAT
  2439. print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_tva, '', $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
  2440. }
  2441. print '</tr>';
  2442. // Amount Local Taxes
  2443. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
  2444. print '<tr>';
  2445. print '<td class="titlefieldmiddle">' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td>';
  2446. print '<td class="nowrap amountcard right">' . price($object->total_localtax1, '', $langs, 0, -1, -1, $conf->currency) . '</td>';
  2447. if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
  2448. $object->multicurrency_total_localtax1 = price2num($object->total_localtax1 * $object->multicurrency_tx, 'MT');
  2449. print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_localtax1, '', $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
  2450. }
  2451. print '</tr>';
  2452. }
  2453. // Amount Local Taxes
  2454. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
  2455. print '<tr>';
  2456. print '<td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td>';
  2457. print '<td class="nowrap amountcard right">' . price($object->total_localtax2, '', $langs, 0, -1, -1, $conf->currency) . '</td>';
  2458. if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
  2459. $object->multicurrency_total_localtax2 = price2num($object->total_localtax2 * $object->multicurrency_tx, 'MT');
  2460. print '<td class="nowrap amountcard right">' . price($object->multicurrency_total_localtax2, '', $langs, 0, -1, -1, $object->multicurrency_code) . '</td>';
  2461. }
  2462. print '</tr>';
  2463. }
  2464. print '<tr>';
  2465. print '<td>' . $langs->trans('AmountTTC') . '</td>';
  2466. print '<td class="valuefield nowrap right amountcard">' . price($object->total_ttc, 1, '', 1, -1, -1, $conf->currency) . '</td>';
  2467. if (isModEnabled("multicurrency") && ($object->multicurrency_code && $object->multicurrency_code != $conf->currency)) {
  2468. // Multicurrency Amount TTC
  2469. print '<td class="valuefield nowrap right amountcard">' . price($object->multicurrency_total_ttc, 1, '', 1, -1, -1, $object->multicurrency_code) . '</td>';
  2470. }
  2471. print '</tr>'."\n";
  2472. print '</table>';
  2473. // Statut
  2474. //print '<tr><td>' . $langs->trans('Status') . '</td><td>' . $object->getLibStatut(4) . '</td></tr>';
  2475. // Margin Infos
  2476. if (isModEnabled('margin')) {
  2477. $formmargin->displayMarginInfos($object);
  2478. }
  2479. print '</div>';
  2480. print '</div>'; // Close fichecenter
  2481. print '<div class="clearboth"></div><br>';
  2482. if (getDolGlobalString('MAIN_DISABLE_CONTACTS_TAB')) {
  2483. $blocname = 'contacts';
  2484. $title = $langs->trans('ContactsAddresses');
  2485. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2486. }
  2487. if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
  2488. $blocname = 'notes';
  2489. $title = $langs->trans('Notes');
  2490. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2491. }
  2492. /*
  2493. * Lines
  2494. */
  2495. // Get object lines
  2496. $result = $object->getLinesArray();
  2497. // Add products/services form
  2498. //$forceall = 1;
  2499. global $inputalsopricewithtax;
  2500. $inputalsopricewithtax = 1;
  2501. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="POST">
  2502. <input type="hidden" name="token" value="' . newToken().'">
  2503. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
  2504. <input type="hidden" name="mode" value="">
  2505. <input type="hidden" name="page_y" value="">
  2506. <input type="hidden" name="id" value="' . $object->id.'">
  2507. <input type="hidden" name="backtopage" value="'.$backtopage.'">
  2508. ';
  2509. if (!empty($conf->use_javascript_ajax) && $object->statut == Commande::STATUS_DRAFT) {
  2510. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  2511. }
  2512. print '<div class="div-table-responsive-no-min">';
  2513. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  2514. // Show object lines
  2515. if (!empty($object->lines)) {
  2516. $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  2517. }
  2518. $numlines = count($object->lines);
  2519. /*
  2520. * Form to add new line
  2521. */
  2522. if ($object->statut == Commande::STATUS_DRAFT && $usercancreate && $action != 'selectlines') {
  2523. if ($action != 'editline') {
  2524. // Add free products/services
  2525. $parameters = array();
  2526. // Note that $action and $object may be modified by hook
  2527. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action);
  2528. if ($reshook < 0) {
  2529. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2530. }
  2531. if (empty($reshook)) {
  2532. $object->formAddObjectLine(1, $mysoc, $soc);
  2533. }
  2534. } else {
  2535. $parameters = array();
  2536. $reshook = $hookmanager->executeHooks('formEditObjectLine', $parameters, $object, $action);
  2537. }
  2538. }
  2539. print '</table>';
  2540. print '</div>';
  2541. print "</form>\n";
  2542. }
  2543. print dol_get_fiche_end();
  2544. /*
  2545. * Buttons for actions
  2546. */
  2547. if ($action != 'presend' && $action != 'editline') {
  2548. print '<div class="tabsAction">';
  2549. $parameters = array();
  2550. // Note that $action and $object may be modified by hook
  2551. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action);
  2552. if (empty($reshook)) {
  2553. // Reopen a closed order
  2554. if (($object->statut == Commande::STATUS_CLOSED || $object->statut == Commande::STATUS_CANCELED) && $usercancreate) {
  2555. print dolGetButtonAction('', $langs->trans('ReOpen'), 'default', $_SERVER["PHP_SELF"].'?action=reopen&amp;token='.newToken().'&amp;id='.$object->id, '');
  2556. }
  2557. // Send
  2558. if (empty($user->socid)) {
  2559. if ($object->statut > Commande::STATUS_DRAFT || getDolGlobalString('COMMANDE_SENDBYEMAIL_FOR_ALL_STATUS')) {
  2560. if ($usercansend) {
  2561. print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER["PHP_SELF"].'?action=presend&token='.newToken().'&id='.$object->id.'&mode=init#formmailbeforetitle', '');
  2562. } else {
  2563. print dolGetButtonAction('', $langs->trans('SendMail'), 'email', $_SERVER['PHP_SELF']. '#', '', false);
  2564. }
  2565. }
  2566. }
  2567. // Valid
  2568. if ($object->statut == Commande::STATUS_DRAFT && ($object->total_ttc >= 0 || getDolGlobalString('ORDER_ENABLE_NEGATIVE')) && $usercanvalidate) {
  2569. if ($numlines > 0) {
  2570. print dolGetButtonAction('', $langs->trans('Validate'), 'default', $_SERVER["PHP_SELF"].'?action=validate&amp;token='.newToken().'&amp;id='.$object->id, $object->id, 1);
  2571. } else {
  2572. print dolGetButtonAction($langs->trans("ErrorObjectMustHaveLinesToBeValidated", $object->ref), $langs->trans('Validate'), 'default', $_SERVER["PHP_SELF"].'?action=validate&amp;token='.newToken().'&amp;id='.$object->id, $object->id, 0);
  2573. }
  2574. }
  2575. // Edit
  2576. if ($object->statut == Commande::STATUS_VALIDATED && $usercancreate) {
  2577. print dolGetButtonAction('', $langs->trans('Modify'), 'default', $_SERVER["PHP_SELF"].'?action=modif&amp;token='.newToken().'&amp;id='.$object->id, '');
  2578. }
  2579. $arrayforbutaction = array();
  2580. // Create a purchase order
  2581. $arrayforbutaction[] = array('lang'=>'orders', 'enabled'=>(isModEnabled("supplier_order") && $object->statut > Commande::STATUS_DRAFT && $object->getNbOfServicesLines() > 0), 'perm'=>$usercancreatepurchaseorder, 'label'=>'AddPurchaseOrder', 'url'=>'/fourn/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id);
  2582. /*if (isModEnabled("supplier_order") && $object->statut > Commande::STATUS_DRAFT && $object->getNbOfServicesLines() > 0) {
  2583. if ($usercancreatepurchaseorder) {
  2584. print dolGetButtonAction('', $langs->trans('AddPurchaseOrder'), 'default', DOL_URL_ROOT.'/fourn/commande/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id, '');
  2585. }
  2586. }*/
  2587. // Create intervention
  2588. $arrayforbutaction[] = array('lang'=>'interventions', 'enabled'=>(isModEnabled("ficheinter") && $object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0), 'perm'=>$user->hasRight('ficheinter', 'creer'), 'label'=>'AddIntervention', 'url'=>'/fichinter/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid);
  2589. /*if (isModEnabled('ficheinter')) {
  2590. $langs->load("interventions");
  2591. if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && $object->getNbOfServicesLines() > 0) {
  2592. if ($user->hasRight('ficheinter', 'creer')) {
  2593. print dolGetButtonAction('', $langs->trans('AddIntervention'), 'default', DOL_URL_ROOT.'/fichinter/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid, '');
  2594. } else {
  2595. print dolGetButtonAction($langs->trans('NotAllowed'), $langs->trans('AddIntervention'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
  2596. }
  2597. }
  2598. }*/
  2599. // Create contract
  2600. $arrayforbutaction[] = array('lang'=>'contracts', 'enabled'=>(isModEnabled("contrat") && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)), 'perm'=>$user->hasRight('contrat', 'creer'), 'label'=>'AddContract', 'url'=>'/contrat/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid);
  2601. /*if (isModEnabled('contrat') && ($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS || $object->statut == Commande::STATUS_CLOSED)) {
  2602. $langs->load("contracts");
  2603. if ($user->hasRight('contrat', 'creer')) {
  2604. print dolGetButtonAction('', $langs->trans('AddContract'), 'default', DOL_URL_ROOT.'/contrat/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid, '');
  2605. }
  2606. }*/
  2607. $numshipping = 0;
  2608. if (isModEnabled('expedition')) {
  2609. $numshipping = $object->countNbOfShipments();
  2610. }
  2611. // Create shipment
  2612. if ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  2613. if ((getDolGlobalInt('MAIN_SUBMODULE_EXPEDITION') && $user->hasRight('expedition', 'creer')) || (getDolGlobalInt('MAIN_SUBMODULE_DELIVERY') && $user->hasRight('expedition', 'delivery', 'creer'))) {
  2614. $arrayforbutaction[] = array('lang'=>'sendings', 'enabled'=>(isModEnabled("expedition") && ($object->statut > Commande::STATUS_DRAFT && $object->statut < Commande::STATUS_CLOSED && ($object->getNbOfProductsLines() > 0 || getDolGlobalString('STOCK_SUPPORTS_SERVICES')))), 'perm'=>$user->hasRight('expedition', 'creer'), 'label'=>'CreateShipment', 'url'=>'/expedition/shipment.php?id='.$object->id);
  2615. /*
  2616. if ($user->hasRight('expedition', 'creer')) {
  2617. print dolGetButtonAction('', $langs->trans('CreateShipment'), 'default', DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id, '');
  2618. } else {
  2619. print dolGetButtonAction($langs->trans('NotAllowed'), $langs->trans('CreateShipment'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
  2620. }*/
  2621. } else {
  2622. $langs->load("errors");
  2623. print dolGetButtonAction($langs->trans('ErrorModuleSetupNotComplete'), $langs->trans('CreateShipment'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
  2624. }
  2625. }
  2626. // Create bill
  2627. $arrayforbutaction[] = array(
  2628. 'lang'=>'bills',
  2629. 'enabled'=>(isModEnabled('facture') && $object->statut > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0),
  2630. 'perm'=>($user->hasRight('facture', 'creer') && !getDolGlobalInt('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')),
  2631. 'label'=>'CreateBill',
  2632. 'url'=>'/compta/facture/card.php?action=create&amp;token='.newToken().'&amp;origin='.urlencode($object->element).'&amp;originid='.$object->id.'&amp;socid='.$object->socid
  2633. );
  2634. /*
  2635. if (isModEnabled('facture') && $object->statut > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) {
  2636. if (isModEnabled('facture') && $user->hasRight('facture', 'creer') && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) {
  2637. print dolGetButtonAction('', $langs->trans('CreateBill'), 'default', DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;token='.newToken().'&amp;origin='.urlencode($object->element).'&amp;originid='.$object->id.'&amp;socid='.$object->socid, '');
  2638. }
  2639. }*/
  2640. if ($numlines > 0) {
  2641. print dolGetButtonAction('', $langs->trans("Create"), 'default', $arrayforbutaction, $object->id, 1);
  2642. } else {
  2643. print dolGetButtonAction($langs->trans("ErrorObjectMustHaveLinesToBeValidated", $object->ref), $langs->trans("Create"), 'default', $arrayforbutaction, $object->id, 0);
  2644. }
  2645. // Set to shipped
  2646. if (($object->statut == Commande::STATUS_VALIDATED || $object->statut == Commande::STATUS_SHIPMENTONPROCESS) && $usercanclose) {
  2647. print dolGetButtonAction('', $langs->trans('ClassifyShipped'), 'default', $_SERVER["PHP_SELF"].'?action=shipped&amp;token='.newToken().'&amp;id='.$object->id, '');
  2648. }
  2649. // Set billed or unbilled
  2650. // Note: Even if module invoice is not enabled, we should be able to use button "Classified billed"
  2651. if ($object->statut > Commande::STATUS_DRAFT && !$object->billed && $object->total_ttc >= 0) {
  2652. if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && !getDolGlobalString('WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER') && !getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')) {
  2653. print dolGetButtonAction('', $langs->trans('ClassifyBilled'), 'default', $_SERVER["PHP_SELF"].'?action=classifybilled&amp;token='.newToken().'&amp;id='.$object->id, '');
  2654. }
  2655. }
  2656. if ($object->statut > Commande::STATUS_DRAFT && $object->billed) {
  2657. if ($usercancreate && $object->statut >= Commande::STATUS_VALIDATED && !getDolGlobalString('WORKFLOW_DISABLE_CLASSIFY_BILLED_FROM_ORDER') && !getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')) {
  2658. print dolGetButtonAction('', $langs->trans('ClassifyUnBilled'), 'delete', $_SERVER["PHP_SELF"].'?action=classifyunbilled&amp;token='.newToken().'&amp;id='.$object->id, '');
  2659. }
  2660. }
  2661. // Clone
  2662. if ($usercancreate) {
  2663. print dolGetButtonAction('', $langs->trans('ToClone'), 'default', $_SERVER["PHP_SELF"].'?action=clone&amp;token='.newToken().'&amp;id='.$object->id.'&amp;socid='.$object->socid, '');
  2664. }
  2665. // Cancel order
  2666. if ($object->statut == Commande::STATUS_VALIDATED && !empty($usercancancel)) {
  2667. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=cancel&token='.newToken().'">'.$langs->trans("CancelOrder").'</a>';
  2668. }
  2669. // Delete order
  2670. if ($usercandelete) {
  2671. if ($numshipping == 0) {
  2672. print dolGetButtonAction('', $langs->trans('Delete'), 'delete', $_SERVER["PHP_SELF"].'?action=delete&token='.newToken().'&id='.$object->id, '');
  2673. } else {
  2674. print dolGetButtonAction($langs->trans('ShippingExist'), $langs->trans('Delete'), 'default', $_SERVER['PHP_SELF']. '#', '', false);
  2675. }
  2676. }
  2677. }
  2678. print '</div>';
  2679. }
  2680. // Select mail models is same action as presend
  2681. if (GETPOST('modelselected')) {
  2682. $action = 'presend';
  2683. }
  2684. if ($action != 'presend') {
  2685. print '<div class="fichecenter"><div class="fichehalfleft">';
  2686. print '<a name="builddoc"></a>'; // ancre
  2687. // Documents
  2688. $objref = dol_sanitizeFileName($object->ref);
  2689. $relativepath = $objref.'/'.$objref.'.pdf';
  2690. $filedir = $conf->commande->multidir_output[$object->entity].'/'.$objref;
  2691. $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
  2692. $genallowed = $usercanread;
  2693. $delallowed = $usercancreate;
  2694. print $formfile->showdocuments('commande', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $soc->default_lang, '', $object);
  2695. // Show links to link elements
  2696. $linktoelem = $form->showLinkToObjectBlock($object, null, array('order'));
  2697. $compatibleImportElementsList = false;
  2698. if ($usercancreate
  2699. && $object->statut == Commande::STATUS_DRAFT) {
  2700. $compatibleImportElementsList = array('commande', 'propal', 'facture'); // import from linked elements
  2701. }
  2702. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
  2703. // Show online payment link
  2704. $useonlinepayment = (isModEnabled('paypal') || isModEnabled('stripe') || isModEnabled('paybox'));
  2705. if (getDolGlobalString('ORDER_HIDE_ONLINE_PAYMENT_ON_ORDER')) {
  2706. $useonlinepayment = 0;
  2707. }
  2708. if ($object->statut != Commande::STATUS_DRAFT && $useonlinepayment) {
  2709. print '<br><!-- Link to pay -->';
  2710. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  2711. print showOnlinePaymentUrl('order', $object->ref).'<br>';
  2712. }
  2713. print '</div><div class="fichehalfright">';
  2714. $MAXEVENT = 10;
  2715. $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', DOL_URL_ROOT.'/commande/agenda.php?id='.$object->id);
  2716. // List of actions on element
  2717. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  2718. $formactions = new FormActions($db);
  2719. $somethingshown = $formactions->showactions($object, 'order', $socid, 1, '', $MAXEVENT, '', $morehtmlcenter); // Show all action for thirdparty
  2720. print '</div></div>';
  2721. }
  2722. // Presend form
  2723. $modelmail = 'order_send';
  2724. $defaulttopic = 'SendOrderRef';
  2725. $diroutput = getMultidirOutput($object);
  2726. $trackid = 'ord'.$object->id;
  2727. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  2728. }
  2729. }
  2730. // End of page
  2731. llxFooter();
  2732. $db->close();