card.php 121 KB

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