card.php 126 KB

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