card.php 124 KB

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