card.php 125 KB

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