card.php 130 KB

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