card.php 122 KB

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